Skip to contentSkip to conversation

block: Use size_add() and array_size() for safe memory allocation

PATCH In review Fushuai Wang 2 participants 2 messages Nov 25, 2025 Block layer

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 block: Use size_add() and array_size() for safe memory allocation

Dynamic size calculations should not be performed in memory allocator due to the risk of overflowing. So use size_add() and array_size(), which have overflow checks, in bio_kmalloc() for safe size calculation.

---
 block/bio.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
block/bio.c +3 -2
index b3a79285c278..c7789469c892 100644
@@ -617,8 +617,9 @@ struct bio *bio_kmalloc(unsigned short nr_vecs, gfp_t gfp_mask)
 
 	if (nr_vecs > BIO_MAX_INLINE_VECS)
 		return NULL;
-	return kmalloc(sizeof(*bio) + nr_vecs * sizeof(struct bio_vec),
-			gfp_mask);
+	return kmalloc(size_add(sizeof(*bio),
+				array_size(nr_vecs, sizeof(struct bio_vec))),
+		       gfp_mask);
 }
 EXPORT_SYMBOL(bio_kmalloc);
 
Signature · 1 line
2.36.1
#1 lore raw
Quoted 3 lines · Fushuai Wang

Dynamic size calculations should not be performed in memory allocator due to the risk of overflowing. So use size_add()

nr_vecs is an unsigned short and sizeof(struct bio_vec) is 16. I don't see how the multiplication could possibly overflow a size_t.

Quoted 28 lines

and array_size(), which have overflow checks, in bio_kmalloc() for safe size calculation.

---
 block/bio.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
block/bio.c +3 -3
index b3a79285c278..c7789469c892 100644
@@ -617,8 +617,9 @@ struct bio *bio_kmalloc(unsigned short nr_vecs, gfp_t gfp_mask)
 
        if (nr_vecs > BIO_MAX_INLINE_VECS)
                return NULL;
-       return kmalloc(sizeof(*bio) + nr_vecs * sizeof(struct bio_vec),
-                       gfp_mask);
+       return kmalloc(size_add(sizeof(*bio),
+                               array_size(nr_vecs, sizeof(struct bio_vec))),
+                      gfp_mask);
 }
 EXPORT_SYMBOL(bio_kmalloc);
 
--

2.36.1