KVM: x86: Replace memset() "optimization" with normal per-field writes
authorSean Christopherson <seanjc@google.com>
Wed, 18 Aug 2021 15:03:08 +0000 (08:03 -0700)
committerKees Cook <keescook@chromium.org>
Mon, 14 Feb 2022 00:48:04 +0000 (16:48 -0800)
Explicitly zero select fields in the emulator's decode cache instead of
zeroing the fields via a gross memset() that spans six fields. gcc and
clang are both clever enough to batch the first five fields into a single
quadword MOV, i.e. memset() and individually zeroing generate identical
code.

Removing the wart also prepares KVM for FORTIFY_SOURCE performing
compile-time and run-time field bounds checking for memset().

No functional change intended.

Reported-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Sean Christopherson <seanjc@google.com>
Link: https://lore.kernel.org/lkml/YR0jIEzEcUom/7rd@google.com
Signed-off-by: Kees Cook <keescook@chromium.org>
arch/x86/kvm/emulate.c
arch/x86/kvm/kvm_emulate.h

index 5719d8cfdbd90aff763e306da68262429847f13f..6b820cc2b51b936f9a7ada347e379bb5b233307e 100644 (file)
@@ -5380,8 +5380,13 @@ static int fastop(struct x86_emulate_ctxt *ctxt, fastop_t fop)
 
 void init_decode_cache(struct x86_emulate_ctxt *ctxt)
 {
-       memset(&ctxt->rip_relative, 0,
-              (void *)&ctxt->modrm - (void *)&ctxt->rip_relative);
+       /* Clear fields that are set conditionally but read without a guard. */
+       ctxt->rip_relative = false;
+       ctxt->rex_prefix = 0;
+       ctxt->lock_prefix = 0;
+       ctxt->rep_prefix = 0;
+       ctxt->regs_valid = 0;
+       ctxt->regs_dirty = 0;
 
        ctxt->io_read.pos = 0;
        ctxt->io_read.end = 0;
index 39eded2426ffd2f4b2551ab56a2e80b72e352d7e..840ddb4a93025de7b8f070b02beb05ae3661bf4b 100644 (file)
@@ -336,11 +336,7 @@ struct x86_emulate_ctxt {
                fastop_t fop;
        };
        int (*check_perm)(struct x86_emulate_ctxt *ctxt);
-       /*
-        * The following six fields are cleared together,
-        * the rest are initialized unconditionally in x86_decode_insn
-        * or elsewhere
-        */
+
        bool rip_relative;
        u8 rex_prefix;
        u8 lock_prefix;