[PATCH v2 08/24] virtio-mem: use vmalloc_array and vcalloc

From: Julia Lawall
Date: Tue Jun 27 2023 - 10:46:10 EST


Use vmalloc_array and vcalloc to protect against
multiplication overflows.

The changes were done using the following Coccinelle
semantic patch:

// <smpl>
@initialize:ocaml@
@@

let rename alloc =
match alloc with
"vmalloc" -> "vmalloc_array"
| "vzalloc" -> "vcalloc"
| _ -> failwith "unknown"

@@
size_t e1,e2;
constant C1, C2;
expression E1, E2, COUNT, x1, x2, x3;
typedef u8;
typedef __u8;
type t = {u8,__u8,char,unsigned char};
identifier alloc = {vmalloc,vzalloc};
fresh identifier realloc = script:ocaml(alloc) { rename alloc };
@@

(
alloc(x1*x2*x3)
|
alloc(C1 * C2)
|
alloc((sizeof(t)) * (COUNT), ...)
|
- alloc((e1) * (e2))
+ realloc(e1, e2)
|
- alloc((e1) * (COUNT))
+ realloc(COUNT, e1)
|
- alloc((E1) * (E2))
+ realloc(E1, E2)
)
// </smpl>

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

---
v2: Use vmalloc_array and vcalloc instead of array_size.
This also leaves a multiplication of a constant by a sizeof
as is. Two patches are thus dropped from the series.

drivers/virtio/virtio_mem.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)

diff -u -p a/drivers/virtio/virtio_mem.c b/drivers/virtio/virtio_mem.c
--- a/drivers/virtio/virtio_mem.c
+++ b/drivers/virtio/virtio_mem.c
@@ -399,7 +399,7 @@ static int virtio_mem_bbm_bb_states_prep
if (vm->bbm.bb_states && old_pages == new_pages)
return 0;

- new_array = vzalloc(new_pages * PAGE_SIZE);
+ new_array = vcalloc(new_pages, PAGE_SIZE);
if (!new_array)
return -ENOMEM;

@@ -465,7 +465,7 @@ static int virtio_mem_sbm_mb_states_prep
if (vm->sbm.mb_states && old_pages == new_pages)
return 0;

- new_array = vzalloc(new_pages * PAGE_SIZE);
+ new_array = vcalloc(new_pages, PAGE_SIZE);
if (!new_array)
return -ENOMEM;

@@ -588,7 +588,7 @@ static int virtio_mem_sbm_sb_states_prep
if (vm->sbm.sb_states && old_pages == new_pages)
return 0;

- new_bitmap = vzalloc(new_pages * PAGE_SIZE);
+ new_bitmap = vcalloc(new_pages, PAGE_SIZE);
if (!new_bitmap)
return -ENOMEM;