leds: pwm: Use struct_size() helper
authorGustavo A. R. Silva <gustavo@embeddedor.com>
Fri, 30 Aug 2019 00:53:20 +0000 (19:53 -0500)
committerJacek Anaszewski <jacek.anaszewski@gmail.com>
Sun, 1 Sep 2019 11:33:29 +0000 (13:33 +0200)
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 led_pwm_priv {
...
        struct led_pwm_data leds[0];
};

Make use of the struct_size() helper instead of an open-coded version
in order to avoid any potential type mistakes.

So, replace the following function:

static inline size_t sizeof_pwm_leds_priv(int num_leds)
{
       return sizeof(struct led_pwm_priv) +
                     (sizeof(struct led_pwm_data) * num_leds);
}

with:

struct_size(priv, leds, count)

This code was detected with the help of Coccinelle.

Signed-off-by: Gustavo A. R. Silva <gustavo@embeddedor.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Jacek Anaszewski <jacek.anaszewski@gmail.com>
drivers/leds/leds-pwm.c

index d0e1f27..8b6965a 100644 (file)
@@ -65,12 +65,6 @@ static int led_pwm_set(struct led_classdev *led_cdev,
        return 0;
 }
 
-static inline size_t sizeof_pwm_leds_priv(int num_leds)
-{
-       return sizeof(struct led_pwm_priv) +
-                     (sizeof(struct led_pwm_data) * num_leds);
-}
-
 static int led_pwm_add(struct device *dev, struct led_pwm_priv *priv,
                       struct led_pwm *led, struct fwnode_handle *fwnode)
 {
@@ -174,7 +168,7 @@ static int led_pwm_probe(struct platform_device *pdev)
        if (!count)
                return -EINVAL;
 
-       priv = devm_kzalloc(&pdev->dev, sizeof_pwm_leds_priv(count),
+       priv = devm_kzalloc(&pdev->dev, struct_size(priv, leds, count),
                            GFP_KERNEL);
        if (!priv)
                return -ENOMEM;