mtd: maps: sa1100-flash: Prefer struct_size over open coded arithmetic
authorErick Archer <erick.archer@outlook.com>
Sat, 30 Mar 2024 17:55:35 +0000 (18:55 +0100)
committerMiquel Raynal <miquel.raynal@bootlin.com>
Tue, 9 Apr 2024 06:35:37 +0000 (08:35 +0200)
This is an effort to get rid of all multiplications from allocation
functions in order to prevent integer overflows [1][2].

As the "info" variable is a pointer to "struct sa_info" and this
structure ends in a flexible array:

struct sa_info {
[...]
struct sa_subdev_info subdev[];
};

the preferred way in the kernel is to use the struct_size() helper to
do the arithmetic instead of the calculation "size + size * count" in
the kzalloc() function.

This way, the code is more readable and safer.

This code was detected with the help of Coccinelle, and audited and
modified manually.

Link: https://www.kernel.org/doc/html/latest/process/deprecated.html#open-coded-arithmetic-in-allocator-arguments
Link: https://github.com/KSPP/linux/issues/160
Signed-off-by: Erick Archer <erick.archer@outlook.com>
Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
Link: https://lore.kernel.org/linux-mtd/AS8PR02MB7237AC633B0D1D2EBD3C40E98B392@AS8PR02MB7237.eurprd02.prod.outlook.com
drivers/mtd/maps/sa1100-flash.c

index d4ce237..ac8a0a1 100644 (file)
@@ -153,7 +153,7 @@ static struct sa_info *sa1100_setup_mtd(struct platform_device *pdev,
                                        struct flash_platform_data *plat)
 {
        struct sa_info *info;
-       int nr, size, i, ret = 0;
+       int nr, i, ret = 0;
 
        /*
         * Count number of devices.
@@ -167,12 +167,10 @@ static struct sa_info *sa1100_setup_mtd(struct platform_device *pdev,
                goto out;
        }
 
-       size = sizeof(struct sa_info) + sizeof(struct sa_subdev_info) * nr;
-
        /*
         * Allocate the map_info structs in one go.
         */
-       info = kzalloc(size, GFP_KERNEL);
+       info = kzalloc(struct_size(info, subdev, nr), GFP_KERNEL);
        if (!info) {
                ret = -ENOMEM;
                goto out;