[PATCH 01/26] lib/test_vmalloc.c: use array_size

From: Julia Lawall
Date: Fri Jun 23 2023 - 17:15:17 EST


Use array_size to protect against multiplication overflows.

The changes were done using the following Coccinelle semantic patch:

// <smpl>
@@
size_t e1,e2;
expression COUNT;
identifier alloc = {vmalloc,vzalloc,kvmalloc,kvzalloc};
@@

(
alloc(
- (e1) * (e2)
+ array_size(e1, e2)
,...)
|
alloc(
- (e1) * (COUNT)
+ array_size(COUNT, e1)
,...)
)

@@
expression E1, E2;
constant C1, C2;
identifier alloc = {vmalloc,vzalloc};
@@

(
alloc(C1 * C2,...)
|
alloc(
- (E1) * (E2)
+ array_size(E1, E2)
,...)
)
// </smpl>

Signed-off-by: Julia Lawall <Julia.Lawall@xxxxxxxx>

---
lib/test_vmalloc.c | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/lib/test_vmalloc.c b/lib/test_vmalloc.c
index 3718d9886407..d02a47e0a72b 100644
--- a/lib/test_vmalloc.c
+++ b/lib/test_vmalloc.c
@@ -156,7 +156,7 @@ static int random_size_alloc_test(void)

for (i = 0; i < test_loop_count; i++) {
n = get_random_u32_inclusive(1, 100);
- p = vmalloc(n * PAGE_SIZE);
+ p = vmalloc(array_size(n, PAGE_SIZE));

if (!p)
return -1;
@@ -175,7 +175,7 @@ static int long_busy_list_alloc_test(void)
int rv = -1;
int i;

- ptr = vmalloc(sizeof(void *) * 15000);
+ ptr = vmalloc(array_size(15000, sizeof(void *)));
if (!ptr)
return rv;

@@ -221,11 +221,11 @@ static int full_fit_alloc_test(void)
junk_length = fls(num_online_cpus());
junk_length *= (32 * 1024 * 1024 / PAGE_SIZE);

- ptr = vmalloc(sizeof(void *) * junk_length);
+ ptr = vmalloc(array_size(junk_length, sizeof(void *)));
if (!ptr)
return rv;

- junk_ptr = vmalloc(sizeof(void *) * junk_length);
+ junk_ptr = vmalloc(array_size(junk_length, sizeof(void *)));
if (!junk_ptr) {
vfree(ptr);
return rv;
@@ -271,7 +271,7 @@ static int fix_size_alloc_test(void)
if (use_huge)
ptr = vmalloc_huge((nr_pages > 0 ? nr_pages:1) * PAGE_SIZE, GFP_KERNEL);
else
- ptr = vmalloc((nr_pages > 0 ? nr_pages:1) * PAGE_SIZE);
+ ptr = vmalloc(array_size(nr_pages > 0 ? nr_pages : 1, PAGE_SIZE));

if (!ptr)
return -1;
@@ -293,7 +293,7 @@ pcpu_alloc_test(void)
size_t size, align;
int i;

- pcpu = vmalloc(sizeof(void __percpu *) * 35000);
+ pcpu = vmalloc(array_size(35000, sizeof(void __percpu *)));
if (!pcpu)
return -1;