Re: [PATCH] KVM: x86: Fix C++ user API for structures with variable length arrays
From: Kees Cook
Date: Thu Feb 26 2026 - 14:10:33 EST
On Thu, Feb 26, 2026 at 11:44:21AM +0000, David Woodhouse wrote:
> From: David Woodhouse <dwmw@xxxxxxxxxxxx>
>
> Commit 94dfc73e7cf4 ("treewide: uapi: Replace zero-length arrays with
> flexible-array members") broke the userspace API for C++. Not just in
> the sense of 'userspace needs to be updated, but UAPI is supposed to be
> stable", but broken in the sense that I can't actually see *how* the
> structures can be used from C++ in the same way that they were usable
> before.
>
> These structures ending in VLAs are typically a *header*, which can be
> followed by an arbitrary number of entries. Userspace typically creates
> a larger structure with some non-zero number of entries, for example in
> QEMU's kvm_arch_get_supported_msr_feature():
>
> struct {
> struct kvm_msrs info;
> struct kvm_msr_entry entries[1];
> } msr_data = {};
>
> While that works in C, it fails in C++ with an error like:
> flexible array member ‘kvm_msrs::entries’ not at end of ‘struct msr_data’
>
> Fix this by using __DECLARE_FLEX_ARRAY() for the VLA, which is a helper
> provided by <linux/stddef.h> that already uses [0] for C++ compilation.
This is likely the best plan for these cases. I had to do similar for
ACPICA upstream, leaving these flex arrays as [0] for the non-GCC (and
Clang) builds:
https://github.com/acpica/acpica/commit/e73b227e8e475c20cc394f237ea35d592fdf9ec3
> Also put the header fields into a struct_group() to provide (in C) a
> separate struct (e.g 'struct kvm_msrs_hdr') without the trailing VLA.
Right, my only worry is if C++ would want those header structs too. In
that case, you'd probably want to use a macro to include them (since not
all compilers are supporting transparent struct members yet):
#define __kvm_msrs_hdr \
__u32 nmsrs; /* number of msrs in entries */ \
__u32 pad
struct kvm_msrs_hdr {
__kvm_msrs_hdr;
};
struct kvm_msrs {
__kvm_msrs_hdr;
__DECLARE_FLEX_ARRAY(struct kvm_msr_entry, entries);
};
> Fixes: 94dfc73e7cf4 ("treewide: uapi: Replace zero-length arrays with flexible-array members")
>
> Signed-off-by: David Woodhouse <dwmw@xxxxxxxxxxxx>
Regardless:
Reviewed-by: Kees Cook <kees@xxxxxxxxxx>
--
Kees Cook