Skip to content

Commit 398180f

Browse files
committed
KVM: TDX: Use struct_size to simplify tdx_get_capabilities()
Use struct_size() instead of manually calculating the number of bytes to allocate for 'caps', including the nested flexible array, and copy all of 'caps' to user space with a single copy_to_user() call (thanks to the full size being provided by struct_size()). Signed-off-by: Thorsten Blum <thorsten.blum@linux.dev> Tested-by: Rick Edgecombe <rick.p.edgecombe@intel.com> Link: https://patch.msgid.link/20251017213914.167301-1-thorsten.blum@linux.dev [sean: separate from swap of get_user() vs. kzalloc() ordering] Signed-off-by: Sean Christopherson <seanjc@google.com>
1 parent 11b79f8 commit 398180f

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

arch/x86/kvm/vmx/tdx.c

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2231,26 +2231,21 @@ static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
22312231
if (nr_user_entries < td_conf->num_cpuid_config)
22322232
return -E2BIG;
22332233

2234-
caps = kzalloc(sizeof(*caps) +
2235-
sizeof(struct kvm_cpuid_entry2) * td_conf->num_cpuid_config,
2236-
GFP_KERNEL);
2234+
caps = kzalloc(struct_size(caps, cpuid.entries,
2235+
td_conf->num_cpuid_config), GFP_KERNEL);
22372236
if (!caps)
22382237
return -ENOMEM;
22392238

22402239
ret = init_kvm_tdx_caps(td_conf, caps);
22412240
if (ret)
22422241
goto out;
22432242

2244-
if (copy_to_user(user_caps, caps, sizeof(*caps))) {
2243+
if (copy_to_user(user_caps, caps, struct_size(caps, cpuid.entries,
2244+
caps->cpuid.nent))) {
22452245
ret = -EFAULT;
22462246
goto out;
22472247
}
22482248

2249-
if (copy_to_user(user_caps->cpuid.entries, caps->cpuid.entries,
2250-
caps->cpuid.nent *
2251-
sizeof(caps->cpuid.entries[0])))
2252-
ret = -EFAULT;
2253-
22542249
out:
22552250
/* kfree() accepts NULL. */
22562251
kfree(caps);

0 commit comments

Comments
 (0)