Re: [drivers/gpio] Question about `ljca_gpio_config`: misuse of __counted_by
From: Linus Walleij
Date: Fri Jul 26 2024 - 16:08:04 EST
Hi Haoyu,
On Wed, Jul 24, 2024 at 11:12 AM Haoyu Li <lihaoyu499@xxxxxxxxx> wrote:
> Dear Linux Developers for GPIO SUBSYSTEM,
>
> We are curious about the use of `struct ljca_gpio_packet *packet` in the function `ljca_gpio_config` (https://elixir.bootlin.com/linux/v6.10/source/drivers/gpio/gpio-ljca.c#L80).
> ```
> static int ljca_gpio_config(struct ljca_gpio_dev *ljca_gpio, u8 gpio_id,
> u8 config)
> {
> struct ljca_gpio_packet *packet =
> (struct ljca_gpio_packet *)ljca_gpio->obuf;
> int ret;
>
> mutex_lock(&ljca_gpio->trans_lock);
> packet->item[0].index = gpio_id;
> packet->item[0].value = config | ljca_gpio->connect_mode[gpio_id];
> packet->num = 1;
>
> ret = ljca_transfer(ljca_gpio->ljca, LJCA_GPIO_CONFIG, (u8 *)packet,
> struct_size(packet, item, packet->num), NULL, 0);
> mutex_unlock(&ljca_gpio->trans_lock);
>
> return ret < 0 ? ret : 0;
> }
> ```
> The definition of `struct ljca_gpio_packet` is at https://elixir.bootlin.com/linux/v6.10/source/drivers/gpio/gpio-ljca.c#L53.
> ```
> struct ljca_gpio_packet {
> u8 num;
> struct ljca_gpio_op item[] __counted_by(num);
> } __packed;
> ```
>
> Our question is: The `item` member of `struct ljca_gpio_packet` is annotated with "__counted_by". Only if we set `packet->num = 1` before accessing `packet->item[0]`, the flexible member `item` can be properly bounds-checked at run-time when enabling CONFIG_UBSAN_BOUNDS and CONFIG_FORTIFY_SOURCE. Or there will be a warning from each access prior to the initialization because the number of elements is zero.
> So we think relocating `packet->num = 1` before accessing `packet->item[0]` is needed.
>
> Here is a fix example of a similar situation : https://lore.kernel.org/stable/20240613113225.898955993@xxxxxxxxxxxxxxxxxxx/.
>
> Please kindly correct us if we missed any key information. Looking forward to your response!
This is a Gustavo AR Silvia question, so let's loop him in.
(I think you're right, and we should make a patch.)
Yours,
Linus Walleij