block: bio: Use struct_size() in kmalloc()
authorGustavo A. R. Silva <gustavo@embeddedor.com>
Mon, 10 Jun 2019 15:04:12 +0000 (10:04 -0500)
committerJens Axboe <axboe@kernel.dk>
Sat, 15 Jun 2019 07:47:58 +0000 (01:47 -0600)
One of the more common cases of allocation size calculations is finding
the size of a structure that has a zero-sized array at the end, along
with memory for some number of elements for that array. For example:

struct bio_map_data {
...
        struct iovec iov[];
};

instance = kmalloc(sizeof(sizeof(struct bio_map_data) + sizeof(struct iovec) *
                          count, GFP_KERNEL);

Instead of leaving these open-coded and prone to type mistakes, we can
now use the new struct_size() helper:

instance = kmalloc(struct_size(instance, iov, count), GFP_KERNEL);

This code was detected with the help of Coccinelle.

Reviewed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Gustavo A. R. Silva <gustavo@embeddedor.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
block/bio.c

index 683cbb4..4bcdcd3 100644 (file)
@@ -1120,8 +1120,7 @@ static struct bio_map_data *bio_alloc_map_data(struct iov_iter *data,
        if (data->nr_segs > UIO_MAXIOV)
                return NULL;
 
-       bmd = kmalloc(sizeof(struct bio_map_data) +
-                      sizeof(struct iovec) * data->nr_segs, gfp_mask);
+       bmd = kmalloc(struct_size(bmd, iov, data->nr_segs), gfp_mask);
        if (!bmd)
                return NULL;
        memcpy(bmd->iov, data->iov, sizeof(struct iovec) * data->nr_segs);