Re: [PATCH 03/10] efi/libstub: use a helper to iterate over a EFI handle array

From: Arvind Sankar
Date: Sat Dec 14 2019 - 15:33:04 EST


On Sat, Dec 14, 2019 at 06:57:28PM +0100, Ard Biesheuvel wrote:
> Iterating over a EFI handle array is a bit finicky, since we have
> to take mixed mode into account, where handles are only 32-bit
> while the native efi_handle_t type is 64-bit.
>
> So introduce a helper, and replace the various occurrences of
> this pattern.
>
> Signed-off-by: Ard Biesheuvel <ardb@xxxxxxxxxx>
> ---
>
> +#define for_each_efi_handle(handle, array, size, i) \
> + for (i = 1, handle = efi_is_64bit() \
> + ? (efi_handle_t)(unsigned long)((u64 *)(array))[0] \
> + : (efi_handle_t)(unsigned long)((u32 *)(array))[0]; \
> + i++ <= (size) / (efi_is_64bit() ? sizeof(efi_handle_t) \
> + : sizeof(u32)); \
> + handle = efi_is_64bit() \
> + ? (efi_handle_t)(unsigned long)((u64 *)(array))[i] \
> + : (efi_handle_t)(unsigned long)((u32 *)(array))[i])
> +
> /*
> * The UEFI spec and EDK2 reference implementation both define EFI_GUID as
> * struct { u32 a; u16; b; u16 c; u8 d[8]; }; and so the implied alignment
> --
> 2.17.1
>

This would access one past the array, no? Eg if the array has one
handle, i is incremented to 2 the first time the condition is checked,
then the loop increment will access array[2] before the condition is
checked again. There seem to be at least a couple of other for_each
macros that might have similar issues.

How about the below instead?

#define for_each_efi_handle(handle, array, size, i) \
for (i = 0; \
(i < (size) / (efi_is_64bit() ? sizeof(efi_handle_t) \
: sizeof(u32))) && \
((handle = efi_is_64bit() \
? ((efi_handle_t *)(array))[i] \
: (efi_handle_t)(unsigned long)((u32 *)(array))[i]), 1);\
i++)