Skip to contentSkip to conversation

x86/alternatives: Adjust all insn-relative fields

PATCH In review Andrew Cooper 3 participants 17 messages Oct 2, 2024 – Oct 8, 2024

lore
Share & tools
lore
#0 lore raw

v2 cover x86/alternatives: Adjust all insn-relative fields

Alternatives have had a reasonably severe restriction since their introduction. This has been the source of several bugs, and several inefficiencies particularly in the speculative safety paths.

v2:
Most work is in patch 1 and the new patch 2 (userspace harness). Other patches with minor or no change.

Andrew Cooper (7):
x86: Introduce x86_decode_lite()
tests/x86: Introduce a userspace test harness for x86_decode_lite() x86/alternative: Walk all replacements during self tests x86/alternative: Indent the relocation logic x86/alternative: Replace a continue with a goto x86/alternative: Relocate all insn-relative fields x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

 tools/tests/Makefile                      |   1 +
 tools/tests/x86-decode-lite/.gitignore    |   1 +
 tools/tests/x86-decode-lite/Makefile      |  45 ++
 tools/tests/x86-decode-lite/insns.S       | 703 ++++++++++++++++++++++
 tools/tests/x86-decode-lite/macro-magic.h |  52 ++
 tools/tests/x86-decode-lite/main.c        | 111 ++++
 tools/tests/x86-decode-lite/x86-emulate.h |  27 +
 xen/arch/x86/alternative.c                | 213 +++++--
 xen/arch/x86/hvm/vmx/entry.S              |  12 +-
 xen/arch/x86/include/asm/spec_ctrl_asm.h  |  43 +-
 xen/arch/x86/x86_emulate/Makefile         |   6 +
 xen/arch/x86/x86_emulate/decode-lite.c    | 311 ++++++++++
 xen/arch/x86/x86_emulate/private.h        |   2 +
 xen/arch/x86/x86_emulate/x86_emulate.h    |  14 +
 14 files changed, 1456 insertions(+), 85 deletions(-)
 create mode 100644 tools/tests/x86-decode-lite/.gitignore
 create mode 100644 tools/tests/x86-decode-lite/Makefile
 create mode 100644 tools/tests/x86-decode-lite/insns.S
 create mode 100644 tools/tests/x86-decode-lite/macro-magic.h
 create mode 100644 tools/tests/x86-decode-lite/main.c
 create mode 100644 tools/tests/x86-decode-lite/x86-emulate.h
 create mode 100644 xen/arch/x86/x86_emulate/decode-lite.c
Signature · 1 line
2.39.5
#1 lore raw

PATCH v2 1/7 x86: Introduce x86_decode_lite()

In order to relocate all IP-relative fields in an alternative replacement block, we need to decode the instructions enough to obtain their length and any relative fields.

Full x86_decode() is far too heavyweight, so introduce a minimal form which can make several simplifying assumptions.

This a mostly-complete decoder for integer instruction in the onebyte and twobyte maps. Some instructions are intentionally unsupported, owing to being unlikely to find in alternatives, and so as to reduce decode complexity. See the subsequent patch adding a userspace test harness for further details.

This logic can decode all alternative blocks that exist in Xen right now.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

v2:
* Switch to 0 on failure, rel_sz in bytes
* Mostly complete the integer instructions; paird with userspace harness
* Put in .init when !CONFIG_LIVEPATCH

---
 xen/arch/x86/x86_emulate/Makefile      |   6 +
 xen/arch/x86/x86_emulate/decode-lite.c | 311 +++++++++++++++++++++++++
 xen/arch/x86/x86_emulate/private.h     |   2 +
 xen/arch/x86/x86_emulate/x86_emulate.h |  14 ++
 4 files changed, 333 insertions(+)
 create mode 100644 xen/arch/x86/x86_emulate/decode-lite.c
xen/arch/x86/x86_emulate/Makefile +6 -0
index 2e20d65d788a..7a56de877f25 100644
@@ -6,3 +6,9 @@ obj-y += decode.o
 obj-$(CONFIG_HVM) += fpu.o
 obj-y += util.o
 obj-y += util-xen.o
+
+ifeq ($(CONFIG_LIVEPATCH),y)
+obj-y += decode-lite.o
+else
+obj-bin-y += decode-lite.init.o
+endif
xen/arch/x86/x86_emulate/decode-lite.c new file +311 -0

311 lines not on this page · raw message

xen/arch/x86/x86_emulate/private.h +2 -0
index 172270a458bd..c5e0983948ce 100644
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>
 # include <asm/endbr.h>
 # include <asm/msr-index.h>
 # include <asm/x86-vendors.h>
xen/arch/x86/x86_emulate/x86_emulate.h +14 -0
index 3e819d41746e..01c371057626 100644
@@ -846,4 +846,18 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};
 }
 
+/*
+ * x86_decode_lite().  Very minimal decoder for managing alternatives.
+ *
+ * @len is 0 on error, or nonzero on success.  If the instruction has a
+ * relative field, @rel_sz is nonzero, and @rel points at the field.
+ */
+typedef struct {
+    uint8_t len;
+    uint8_t rel_sz; /* bytes: 0, 1 or 4 */
+    void *rel;
+} x86_decode_lite_t;
+
+x86_decode_lite_t x86_decode_lite(void *ip, void *end);
+
 #endif /* __X86_EMULATE_H__ */
Signature · 1 line
2.39.5
#2 lore raw

Re: [PATCH v2 1/7] x86: Introduce x86_decode_lite()

Quoted 18 lines · Andrew Cooper
xen/arch/x86/x86_emulate/decode-lite.c new file +15 -0
@@ -0,0 +1,311 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include "private.h"
+
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Moffs  (1 << 2)
+#define Branch (1 << 5) /* ... that we care about */
+/*      ModRM  (1 << 6) */
+#define Known  (1 << 7)
+
+#define ALU_OPS                                 \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \

xen/arch/x86/x86_emulate/decode-lite.c line 25

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    (Known|ModRM),                              \
+    (Known|Imm8),                               \
+    (Known|Imm)
+
+static const uint8_t init_or_livepatch_const onebyte[256] = {
+    [0x00] = ALU_OPS, /* ADD */ [0x08] = ALU_OPS, /* OR  */
+    [0x10] = ALU_OPS, /* ADC */ [0x18] = ALU_OPS, /* SBB */
+    [0x20] = ALU_OPS, /* AND */ [0x28] = ALU_OPS, /* SUB */
+    [0x30] = ALU_OPS, /* XOR */ [0x38] = ALU_OPS, /* CMP */
+/*  [0x40 ... 0x4f] = REX prefixes */

For these and other aspects further down, may I ask for a comment at the top of the file setting the scope for this new function (and its associated data) as being strictly 64-bit only? And perhaps even strictly covering only what Xen may legitimately use (largely excluding APX for the foreseeable future, i.e. until such time that we might decide to allow Xen itself to use APX throughout its code).

Besides APX, with more immediate uses in mind, I wonder about e.g. BMI/BMI2 insns, which live outside the one/two-byte maps.

I would further appreciate if we could be consistent with the mentioning (or not) of prefixes: The REX ones here are the only ones that the table mentions right now. In fact I wonder whether a Prefix attribute wouldn't be nice to have, so you don't need to open-code all of them in the function itself.

xen/arch/x86/x86_emulate/decode-lite.c line 33

Quoted 8 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +8 -0
+    [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+    [0x63]          = (Known|ModRM),       /* MOVSxd */
+
+    [0x68]          = (Known|Imm),         /* PUSH $imm */
+    [0x69]          = (Known|ModRM|Imm),   /* IMUL $imm/r/rm */
+    [0x6a]          = (Known|Imm8),        /* PUSH $imm8 */
+    [0x6b]          = (Known|ModRM|Imm8),  /* PUSH $imm8/r/rm */

IMUL? I'm also slightly irritated by $imm{,8}/r/rm - better to use commas to separate operands, and then rm is the middle one (2nd source) while r is the destination (last), if already you want AT&T operand order.

xen/arch/x86/x86_emulate/decode-lite.c line 43

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    [0x6c ... 0x6f] = (Known),             /* INS/OUTS */
+
+    [0x70 ... 0x7f] = (Known|Branch|Imm8), /* Jcc disp8 */
+    [0x80]          = (Known|ModRM|Imm8),  /* Grp1 */
+    [0x81]          = (Known|ModRM|Imm),   /* Grp1 */
+
+    [0x83]          = (Known|ModRM|Imm8),  /* Grp1 */
+    [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA r/rm */
+
+    [0x90 ... 0x99] = (Known),             /* NOP/XCHG rAX/CLTQ/CQTO */

Omitting PUSH (at 0x8f) is somewhat odd, considering that it's a pretty "normal" insn.

xen/arch/x86/x86_emulate/decode-lite.c line 50

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+    [0x9b ... 0x9f] = (Known),             /* FWAIT/PUSHF/POPF/SAHF/LAHF */
+
+    [0xa0 ... 0xa3] = (Known|Moffs),       /* MOVABS */
+    [0xa4 ... 0xa7] = (Known),             /* MOVS/CMPS */
+    [0xa8]          = (Known|Imm8),        /* TEST %al */
+    [0xa9]          = (Known|Imm),         /* TEST %al */

%rAX?

xen/arch/x86/x86_emulate/decode-lite.c line 56

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+    [0xaa ... 0xaf] = (Known),             /* STOS/LODS/SCAS */
+    [0xb0 ... 0xb7] = (Known|Imm8),        /* MOV $imm8, %reg */
+    [0xb8 ... 0xbf] = (Known|Imm),         /* MOV $imm{16,32,64}, %reg */
+    [0xc0 ... 0xc1] = (Known|ModRM|Imm8),  /* Grp2 (ROL..SAR $imm8, %reg) */
+
+    [0xc3]          = (Known),             /* RET */

With the absence of Branch here I think it would be nice if at least the description went into a little more detail as to the comment higher up saying "... that we care about".

xen/arch/x86/x86_emulate/decode-lite.c line 61

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+    [0xc6]          = (Known|ModRM|Imm8),  /* Grp11, Further ModRM decode */
+    [0xc7]          = (Known|ModRM|Imm),   /* Grp11, Further ModRM decode */
+
+    [0xcb ... 0xcc] = (Known),             /* LRET/INT3 */
+    [0xcd]          = (Known|Imm8),        /* INT $imm8 */

No IRET, when you have things like e.g. ICEBP and CLTS?

Quoted 32 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +32 -0
+    [0xd0 ... 0xd3] = (Known|ModRM),       /* Grp2 (ROL..SAR {$1,%cl}, %reg) */
+
+    [0xe4 ... 0xe7] = (Known|Imm8),        /* IN/OUT $imm8 */
+    [0xe8 ... 0xe9] = (Known|Branch|Imm),  /* CALL/JMP disp32 */
+    [0xeb]          = (Known|Branch|Imm8), /* JMP disp8 */
+    [0xec ... 0xef] = (Known),             /* IN/OUT %dx */
+
+    [0xf1]          = (Known),             /* ICEBP */
+    [0xf4]          = (Known),             /* HLT */
+    [0xf5]          = (Known),             /* CMC */
+    [0xf6 ... 0xf7] = (Known|ModRM),       /* Grp3, Further ModRM decode */
+    [0xf8 ... 0xfd] = (Known),             /* CLC ... STD */
+    [0xfe ... 0xff] = (Known|ModRM),       /* Grp4 */
+};
+static const uint8_t init_or_livepatch_const twobyte[256] = {
+    [0x00 ... 0x03] = (Known|ModRM),       /* Grp6/Grp7/LAR/LSL */
+    [0x06]          = (Known),             /* CLTS */
+    [0x09]          = (Known),             /* WBINVD */
+    [0x0b]          = (Known),             /* UD2 */
+
+    [0x18 ... 0x1f] = (Known|ModRM),       /* Grp16 (Hint Nop) */
+    [0x20 ... 0x23] = (Known|ModRM),       /* MOV %cr/%dr */
+
+    [0x30 ... 0x33] = (Known),             /* WRMSR/RDTSC/RDMSR/RDPMC */
+
+    [0x40 ... 0x4f] = (Known|ModRM),       /* CMOVcc */
+
+    [0x80 ... 0x8f] = (Known|Branch|Imm),  /* Jcc disp32 */
+    [0x90 ... 0x9f] = (Known|ModRM),       /* SETcc */
+
+    [0xa0 ... 0xa2] = (Known),             /* PUSH/POP %fs/CPUID */
+    [0xa3]          = (Known|ModRM),       /* BT r/rm */

xen/arch/x86/x86_emulate/decode-lite.c line 104

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    [0xa4]          = (Known|ModRM|Imm8),  /* SHLD $imm8 */
+    [0xa5]          = (Known|ModRM),       /* SHLD %cl */
+
+    [0xa8 ... 0xa9] = (Known),             /* PUSH/POP %gs */
+
+    [0xab]          = (Known|ModRM),       /* BTS */
+    [0xac]          = (Known|ModRM|Imm8),  /* SHRD $imm8 */
+    [0xad ... 0xaf] = (Known|ModRM),       /* SHRD %cl/Grp15/IMUL */
+
+    [0xb0 ... 0xb9] = (Known|ModRM),       /* CMPXCHG/LSS/BTR/LFS/LGS/MOVZxx/POPCNT/Grp10 */

Grp10 is kind of odd - I think UD1 would be more concise, despite the SDM indeed using group 10 there.

xen/arch/x86/x86_emulate/decode-lite.c line 106

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+    [0xbb ... 0xbf] = (Known|ModRM),       /* BSR/BSF/BSR/MOVSX */

0xbb is BTC I think.

xen/arch/x86/x86_emulate/decode-lite.c line 109

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0xc0 ... 0xc1] = (Known|ModRM),       /* XADD */
+    [0xc7]          = (Known|ModRM),       /* Grp9 */
+    [0xc8 ... 0xcf] = (Known),             /* BSWAP */

With UD1 and UD2, perhaps UD0 would make sense to also have in the table?

xen/arch/x86/x86_emulate/decode-lite.c line 122

Quoted 13 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +13 -0
+};
+
+/*
+ * Bare minimum x86 instruction decoder to parse the alternative replacement
+ * instructions and locate the IP-relative references that may need updating.
+ *
+ * These are:
+ *  - disp8/32 from near branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:
+ *  - All code is 64bit, and the instruction stream is safe to read.
+ *  - The 67 prefix is not implemented, so the address size is only 64bit.

As to the earlier remark - maybe this part of the comment could simply move to the top of the file?

xen/arch/x86/x86_emulate/decode-lite.c line 133

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.
+ *
+ * Returns: x86_decode_lite_t
+ *  - On failure, length of 0.
+ *  - On success, length > 0.  For rel_sz > 0, rel points at the relative
+ *    field in the instruction stream.
+ */
+x86_decode_lite_t init_or_livepatch x86_decode_lite(void *ip, void *end)

Imo both pointers would be nice to be to-const.

Quoted 19 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +19 -0
+{
+    void *start = ip, *rel = NULL;
+    unsigned int opc, rel_sz = 0;
+    uint8_t b, d, rex = 0, osize = 4;
+
+#define OPC_TWOBYTE (1 << 8)
+
+    /* Mutates IP, uses END. */
+#define FETCH(ty)                                       \
+    ({                                                  \
+        ty _val;                                        \
+                                                        \
+        if ( (ip + sizeof(ty)) > end )                  \
+            goto overrun;                               \
+        _val = *(ty *)ip;                               \
+        ip += sizeof(ty);                               \
+        _val;                                           \
+    })
+

xen/arch/x86/x86_emulate/decode-lite.c line 162

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    for ( ;; ) /* Prefixes */
+    {
+        switch ( b = FETCH(uint8_t) )
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */

If you don't like the idea of a Prefix attribute I wonder in how far we actually need all of the above, when you already ...

xen/arch/x86/x86_emulate/decode-lite.c line 172

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        case 0xf0: /* LOCK */
+        case 0xf2: /* REPNE */
+        case 0xf3: /* REP */
+            break;
+
+        case 0x66: /* Operand size override */
+            osize = 2;
+            break;
+
+        /* case 0x67: Address size override, not implemented */

... deliberately leave of this one.

xen/arch/x86/x86_emulate/decode-lite.c line 185

Quoted 12 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +12 -0
+        case 0x40 ... 0x4f: /* REX */
+            rex = b;
+            continue;
+
+        default:
+            goto prefixes_done;
+        }
+        rex = 0; /* REX cancelled by subsequent legacy prefix. */
+    }
+ prefixes_done:
+
+    if ( rex & 0x08 ) /* REX.W */

Can you please use REX_W here?

Quoted 38 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +38 -0
+        osize = 8;
+
+    /* Fetch the main opcode byte(s) */
+    if ( b == 0x0f )
+    {
+        b = FETCH(uint8_t);
+        opc = OPC_TWOBYTE | b;
+
+        d = twobyte[b];
+    }
+    else
+    {
+        opc = b;
+        d = onebyte[b];
+    }
+
+    if ( unlikely(!(d & Known)) )
+        goto unknown;
+
+    if ( d & ModRM )
+    {
+        uint8_t modrm = FETCH(uint8_t);
+        uint8_t mod = modrm >> 6;
+        uint8_t reg = (modrm >> 3) & 7;
+        uint8_t rm = modrm & 7;
+
+        /* ModRM/SIB decode */
+        if ( mod == 0 && rm == 5 ) /* RIP relative */
+        {
+            rel = ip;
+            rel_sz = 4;
+            FETCH(uint32_t);
+        }
+        else if ( mod != 3 && rm == 4 ) /* SIB */
+        {
+            uint8_t sib = FETCH(uint8_t);
+            uint8_t base = sib & 7;
+

xen/arch/x86/x86_emulate/decode-lite.c line 233

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+            if ( mod == 0 && base == 5 )
+                goto disp32;
+        }
+
+        if ( mod == 1 ) /* disp8 */
+            FETCH(uint8_t);
+        else if ( mod == 2 ) /* disp32 */
+        {
+        disp32:
+            FETCH(uint32_t);

The values aren't used, so the types don't matter overly much, yet int8_t and int32_t would be a more accurate representation of what's being fetched.

Quoted 8 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +8 -0
+        }
+
+        /* ModRM based decode adjustements */
+        switch ( opc )
+        {
+        case 0xc7: /* Grp11 XBEGIN is a branch. */
+            if ( modrm == 0xf8 )
+                d |= Branch;

xen/arch/x86/x86_emulate/decode-lite.c line 251

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+            break;
+        case 0xf6: /* Grp3 TEST(s) have extra Imm8 */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm8;
+            break;
+        case 0xf7: /* Grp3 TEST(s) have extra Imm */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm;
+            break;
+        }

In this switch() you don't distinguish 1- and 2-byte maps at all. This is an issue in particular for 0xc7.

Blank lines between case blocks would also be nice, as this switch() is going to only ever grow.

Quoted 15 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +15 -0
+    }
+
+    if ( d & Branch )
+    {
+        /*
+         * We don't tolerate 66-prefixed call/jmp in alternatives.  Some are
+         * genuinely decoded differently between Intel and AMD CPUs.
+         *
+         * We also don't support APX instructions, so don't have to cope with
+         * JMPABS which is the first branch to have an 8-byte immediate.
+         */
+        if ( osize < 4 )
+            goto bad_osize;
+
+        rel = ip;

xen/arch/x86/x86_emulate/decode-lite.c line 276

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        rel_sz = (d & Imm8) ? 1 : 4;
+    }
+
+    if ( d & (Imm | Imm8 | Moffs) )
+    {
+        if ( d & Imm8 )
+            osize = 1;
+        else if ( d & Moffs )
+            osize = 8;
+        else if ( osize == 8 && !(opc >= 0xb8 && opc <= 0xbf) )

Again want to also take the opcode map into account, even if - by luck - this would work as is for now.

Also could I talk you into converting the two comparisons into one, along the lines of "(opc | 7) != 0xbf"?

xen/arch/x86/x86_emulate/private.h line 17

Quoted 12 lines
xen/arch/x86/x86_emulate/private.h +2 -0
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>
 # include <asm/endbr.h>
 # include <asm/msr-index.h>
 # include <asm/x86-vendors.h>

It's only the new file that needs these - can we limit the dependencies to just that one by putting these new #include-s there?

Jan

#3 lore raw

Re: [PATCH v2 1/7] x86: Introduce x86_decode_lite()

Quoted 36 lines · Jan Beulich
Quoted 18 lines · Andrew Cooper
xen/arch/x86/x86_emulate/decode-lite.c new file +15 -0
@@ -0,0 +1,311 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include "private.h"
+
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Moffs  (1 << 2)
+#define Branch (1 << 5) /* ... that we care about */
+/*      ModRM  (1 << 6) */
+#define Known  (1 << 7)
+
+#define ALU_OPS                                 \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \

xen/arch/x86/x86_emulate/decode-lite.c line 25

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    (Known|ModRM),                              \
+    (Known|Imm8),                               \
+    (Known|Imm)
+
+static const uint8_t init_or_livepatch_const onebyte[256] = {
+    [0x00] = ALU_OPS, /* ADD */ [0x08] = ALU_OPS, /* OR  */
+    [0x10] = ALU_OPS, /* ADC */ [0x18] = ALU_OPS, /* SBB */
+    [0x20] = ALU_OPS, /* AND */ [0x28] = ALU_OPS, /* SUB */
+    [0x30] = ALU_OPS, /* XOR */ [0x38] = ALU_OPS, /* CMP */
+/*  [0x40 ... 0x4f] = REX prefixes */

For these and other aspects further down, may I ask for a comment at the top of the file setting the scope for this new function (and its associated data) as being strictly 64-bit only? And perhaps even strictly covering only what Xen may legitimately use (largely excluding APX for the foreseeable future, i.e. until such time that we might decide to allow Xen itself to use APX throughout its code).

Quoted 2 lines

Besides APX, with more immediate uses in mind, I wonder about e.g. BMI/BMI2 insns, which live outside the one/two-byte maps.

They're not needed yet, and it would require extra decode complexity.

Quoted 5 lines

I would further appreciate if we could be consistent with the mentioning (or not) of prefixes: The REX ones here are the only ones that the table mentions right now. In fact I wonder whether a Prefix attribute wouldn't be nice to have, so you don't need to open-code all of them in the function itself.

The comment about REX prefixes is only here because you insisted on it.

But I really don't like double-explaining things.

Quoted 4 lines
Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    [0x6c ... 0x6f] = (Known),             /* INS/OUTS */
+
+    [0x70 ... 0x7f] = (Known|Branch|Imm8), /* Jcc disp8 */
+    [0x80]          = (Known|ModRM|Imm8),  /* Grp1 */
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 43

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+    [0x81]          = (Known|ModRM|Imm),   /* Grp1 */
+
+    [0x83]          = (Known|ModRM|Imm8),  /* Grp1 */
+    [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA r/rm */
+
+    [0x90 ... 0x99] = (Known),             /* NOP/XCHG rAX/CLTQ/CQTO */

Omitting PUSH (at 0x8f) is somewhat odd, considering that it's a pretty "normal" insn.

Except it's not.  It's the XOP prefix too, and would require extra decode complexity.

Quoted 6 lines

xen/arch/x86/x86_emulate/decode-lite.c line 61

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+    [0xc6]          = (Known|ModRM|Imm8),  /* Grp11, Further ModRM decode */
+    [0xc7]          = (Known|ModRM|Imm),   /* Grp11, Further ModRM decode */
+
+    [0xcb ... 0xcc] = (Known),             /* LRET/INT3 */
+    [0xcd]          = (Known|Imm8),        /* INT $imm8 */

No IRET, when you have things like e.g. ICEBP and CLTS?

The absence of IRET is intentional, because it can't be used safely. SYSRET/EXIT are excluded too for consistency.

IRET can be added if/when it is needed, and someone has figured out a way of adjusting the exception table entry.

Quoted 7 lines
Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+};
+
+/*
+ * Bare minimum x86 instruction decoder to parse the alternative replacement
+ * instructions and locate the IP-relative references that may need updating.
+ *
+ * These are:
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 122

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+ *  - disp8/32 from near branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:
+ *  - All code is 64bit, and the instruction stream is safe to read.
+ *  - The 67 prefix is not implemented, so the address size is only 64bit.

As to the earlier remark - maybe this part of the comment could simply move to the top of the file?

I really don't want to split the comment.  It needs to all live together.

Given this is a single-function file, I also don't see the need for this comment to move away from here.  You can't interpret the decode tables without reading the function.

Quoted 11 lines

xen/arch/x86/x86_emulate/decode-lite.c line 133

Quoted 11 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.
+ *
+ * Returns: x86_decode_lite_t
+ *  - On failure, length of 0.
+ *  - On success, length > 0.  For rel_sz > 0, rel points at the relative
+ *    field in the instruction stream.
+ */
+x86_decode_lite_t init_or_livepatch x86_decode_lite(void *ip, void *end)
Quoted 1 line

Imo both pointers would be nice to be to-const.

In v1, you also identified why that wouldn't compile.

Quoted 23 lines
Quoted 23 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +22 -0
+{
+    void *start = ip, *rel = NULL;
+    unsigned int opc, rel_sz = 0;
+    uint8_t b, d, rex = 0, osize = 4;
+
+#define OPC_TWOBYTE (1 << 8)
+
+    /* Mutates IP, uses END. */
+#define FETCH(ty)                                       \
+    ({                                                  \
+        ty _val;                                        \
+                                                        \
+        if ( (ip + sizeof(ty)) > end )                  \
+            goto overrun;                               \
+        _val = *(ty *)ip;                               \
+        ip += sizeof(ty);                               \
+        _val;                                           \
+    })
+
+    for ( ;; ) /* Prefixes */
+    {
+        switch ( b = FETCH(uint8_t) )
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 162

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */

If you don't like the idea of a Prefix attribute

I don't like the idea of making this intentionally dissimilar to the main decoder, just to safe a few lines of source code.

GCC optimises it into a bitmap anyway.

Quoted 14 lines

I wonder in how far we
actually need all of the above, when you already ...

xen/arch/x86/x86_emulate/decode-lite.c line 172

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        case 0xf0: /* LOCK */
+        case 0xf2: /* REPNE */
+        case 0xf3: /* REP */
+            break;
+
+        case 0x66: /* Operand size override */
+            osize = 2;
+            break;
+
+        /* case 0x67: Address size override, not implemented */

... deliberately leave of this one.

Excluding 67 is intentional because it a) has no business being used, and b) adds a huge amount of decode complexity.

Whereas two of segment prefixes are already necessary to decode the alternatives we have today.

Quoted 5 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+        case 0x40 ... 0x4f: /* REX */
+            rex = b;
+            continue;
+
+        default:
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 185

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+            goto prefixes_done;
+        }
+        rex = 0; /* REX cancelled by subsequent legacy prefix. */
+    }
+ prefixes_done:
+
+    if ( rex & 0x08 ) /* REX.W */

Can you please use REX_W here?

Oh, it is available.  Ok.

Quoted 44 lines
Quoted 44 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +43 -0
+        osize = 8;
+
+    /* Fetch the main opcode byte(s) */
+    if ( b == 0x0f )
+    {
+        b = FETCH(uint8_t);
+        opc = OPC_TWOBYTE | b;
+
+        d = twobyte[b];
+    }
+    else
+    {
+        opc = b;
+        d = onebyte[b];
+    }
+
+    if ( unlikely(!(d & Known)) )
+        goto unknown;
+
+    if ( d & ModRM )
+    {
+        uint8_t modrm = FETCH(uint8_t);
+        uint8_t mod = modrm >> 6;
+        uint8_t reg = (modrm >> 3) & 7;
+        uint8_t rm = modrm & 7;
+
+        /* ModRM/SIB decode */
+        if ( mod == 0 && rm == 5 ) /* RIP relative */
+        {
+            rel = ip;
+            rel_sz = 4;
+            FETCH(uint32_t);
+        }
+        else if ( mod != 3 && rm == 4 ) /* SIB */
+        {
+            uint8_t sib = FETCH(uint8_t);
+            uint8_t base = sib & 7;
+
+            if ( mod == 0 && base == 5 )
+                goto disp32;
+        }
+
+        if ( mod == 1 ) /* disp8 */
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 233

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+            FETCH(uint8_t);
+        else if ( mod == 2 ) /* disp32 */
+        {
+        disp32:
+            FETCH(uint32_t);

The values aren't used, so the types don't matter overly much, yet int8_t and int32_t would be a more accurate representation of what's being fetched.

Why does that matter?  I'm skipping a number of bytes, not interpreting the result.

Quoted 19 lines
Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +8 -0
+        }
+
+        /* ModRM based decode adjustements */
+        switch ( opc )
+        {
+        case 0xc7: /* Grp11 XBEGIN is a branch. */
+            if ( modrm == 0xf8 )
+                d |= Branch;

xen/arch/x86/x86_emulate/decode-lite.c line 251

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+            break;
+        case 0xf6: /* Grp3 TEST(s) have extra Imm8 */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm8;
+            break;
+        case 0xf7: /* Grp3 TEST(s) have extra Imm */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm;
+            break;
+        }
Quoted 1 line

In this switch() you don't distinguish 1- and 2-byte maps at all.

See OPC_TWOBYTE.  They are distinguished here.

Quoted 28 lines
Quoted 15 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +15 -0
+    }
+
+    if ( d & Branch )
+    {
+        /*
+         * We don't tolerate 66-prefixed call/jmp in alternatives.  Some are
+         * genuinely decoded differently between Intel and AMD CPUs.
+         *
+         * We also don't support APX instructions, so don't have to cope with
+         * JMPABS which is the first branch to have an 8-byte immediate.
+         */
+        if ( osize < 4 )
+            goto bad_osize;
+
+        rel = ip;

xen/arch/x86/x86_emulate/decode-lite.c line 276

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        rel_sz = (d & Imm8) ? 1 : 4;
+    }
+
+    if ( d & (Imm | Imm8 | Moffs) )
+    {
+        if ( d & Imm8 )
+            osize = 1;
+        else if ( d & Moffs )
+            osize = 8;
+        else if ( osize == 8 && !(opc >= 0xb8 && opc <= 0xbf) )

Again want to also take the opcode map into account, even if - by luck - this would work as is for now.

Quoted 2 lines

Also could I talk you into converting the two comparisons into one, along the lines of "(opc | 7) != 0xbf"?

That's the kind of obfuscation which should be left to the compiler.

I know you think like that, but most others (including myself) do not.

Quoted 5 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/private.h +0 -0
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
Quoted 9 lines

xen/arch/x86/x86_emulate/private.h line 17

Quoted 7 lines
xen/arch/x86/x86_emulate/private.h +2 -0
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>
 # include <asm/endbr.h>
 # include <asm/msr-index.h>
 # include <asm/x86-vendors.h>

It's only the new file that needs these - can we limit the dependencies to just that one by putting these new #include-s there?

Not if you want the userspace harness in patch 2 to compile.

~Andrew

#4 lore raw

Re: [PATCH v2 1/7] x86: Introduce x86_decode_lite()

Quoted 42 lines · Andrew Cooper
Quoted 36 lines · Jan Beulich
Quoted 18 lines · Andrew Cooper
xen/arch/x86/x86_emulate/decode-lite.c new file +15 -0
@@ -0,0 +1,311 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include "private.h"
+
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Moffs  (1 << 2)
+#define Branch (1 << 5) /* ... that we care about */
+/*      ModRM  (1 << 6) */
+#define Known  (1 << 7)
+
+#define ALU_OPS                                 \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \

xen/arch/x86/x86_emulate/decode-lite.c line 25

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    (Known|ModRM),                              \
+    (Known|Imm8),                               \
+    (Known|Imm)
+
+static const uint8_t init_or_livepatch_const onebyte[256] = {
+    [0x00] = ALU_OPS, /* ADD */ [0x08] = ALU_OPS, /* OR  */
+    [0x10] = ALU_OPS, /* ADC */ [0x18] = ALU_OPS, /* SBB */
+    [0x20] = ALU_OPS, /* AND */ [0x28] = ALU_OPS, /* SUB */
+    [0x30] = ALU_OPS, /* XOR */ [0x38] = ALU_OPS, /* CMP */
+/*  [0x40 ... 0x4f] = REX prefixes */

For these and other aspects further down, may I ask for a comment at the top of the file setting the scope for this new function (and its associated data) as being strictly 64-bit only? And perhaps even strictly covering only what Xen may legitimately use (largely excluding APX for the foreseeable future, i.e. until such time that we might decide to allow Xen itself to use APX throughout its code).

Quoted 2 lines

Besides APX, with more immediate uses in mind, I wonder about e.g. BMI/BMI2 insns, which live outside the one/two-byte maps.

They're not needed yet, and it would require extra decode complexity.

Quoted 7 lines
Quoted 5 lines

I would further appreciate if we could be consistent with the mentioning (or not) of prefixes: The REX ones here are the only ones that the table mentions right now. In fact I wonder whether a Prefix attribute wouldn't be nice to have, so you don't need to open-code all of them in the function itself.

The comment about REX prefixes is only here because you insisted on it.

Did I? Looking back at my v1 replies I can't spot such a comment. But anyway, what I'd like to ask for is consistency: Mention all (relevant) prefixes, or none of them.

Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    [0x6c ... 0x6f] = (Known),             /* INS/OUTS */
+
+    [0x70 ... 0x7f] = (Known|Branch|Imm8), /* Jcc disp8 */
+    [0x80]          = (Known|ModRM|Imm8),  /* Grp1 */
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 43

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+    [0x81]          = (Known|ModRM|Imm),   /* Grp1 */
+
+    [0x83]          = (Known|ModRM|Imm8),  /* Grp1 */
+    [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA r/rm */
+
+    [0x90 ... 0x99] = (Known),             /* NOP/XCHG rAX/CLTQ/CQTO */

Omitting PUSH (at 0x8f) is somewhat odd, considering that it's a pretty "normal" insn.

Quoted 2 lines

Except it's not.  It's the XOP prefix too, and would require extra decode complexity.

Well, just like you don't decode VEX/EVEX, you could opt not to decode XOP despite decoding this PUSH form. Otherwise I'm inclined to ask that no PUSH or POP should be decoded.

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+    [0xc6]          = (Known|ModRM|Imm8),  /* Grp11, Further ModRM decode */
+    [0xc7]          = (Known|ModRM|Imm),   /* Grp11, Further ModRM decode */
+
+    [0xcb ... 0xcc] = (Known),             /* LRET/INT3 */
+    [0xcd]          = (Known|Imm8),        /* INT $imm8 */
Quoted 7 lines
Quoted 1 line

No IRET, when you have things like e.g. ICEBP and CLTS?

The absence of IRET is intentional, because it can't be used safely. SYSRET/EXIT are excluded too for consistency.

IRET can be added if/when it is needed, and someone has figured out a way of adjusting the exception table entry.

If it has an attached exception table entry. If it doesn't, I think its use would in principle be fine. And an attached exception table entry could similarly be a problem for any other insn, couldn't it? The same argument would in particular apply to LRET, I think.

Anyway, once again my main concern here are apparent inconsistencies. Any of them will make it more difficult to judge what needs / doesn't need adding here going forward.

Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+};
+
+/*
+ * Bare minimum x86 instruction decoder to parse the alternative replacement
+ * instructions and locate the IP-relative references that may need updating.
+ *
+ * These are:
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 122

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+ *  - disp8/32 from near branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:
+ *  - All code is 64bit, and the instruction stream is safe to read.
+ *  - The 67 prefix is not implemented, so the address size is only 64bit.

As to the earlier remark - maybe this part of the comment could simply move to the top of the file?

Quoted 5 lines

I really don't want to split the comment.  It needs to all live together.

Given this is a single-function file, I also don't see the need for this comment to move away from here.  You can't interpret the decode tables without reading the function.

I'm torn; I think having some fundamental information at the top of the file would help. Yet keeping commentary together is also a valid aspect.

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.
+ *
+ * Returns: x86_decode_lite_t
+ *  - On failure, length of 0.
+ *  - On success, length > 0.  For rel_sz > 0, rel points at the relative
+ *    field in the instruction stream.
+ */
+x86_decode_lite_t init_or_livepatch x86_decode_lite(void *ip, void *end)
Quoted 3 lines
Quoted 1 line

Imo both pointers would be nice to be to-const.

In v1, you also identified why that wouldn't compile.

Hmm, right. It's been a while. Would it be too much to ask that you add a sentence to that effect to the description?

Quoted 31 lines
Quoted 22 lines
Quoted 22 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +22 -0
+{
+    void *start = ip, *rel = NULL;
+    unsigned int opc, rel_sz = 0;
+    uint8_t b, d, rex = 0, osize = 4;
+
+#define OPC_TWOBYTE (1 << 8)
+
+    /* Mutates IP, uses END. */
+#define FETCH(ty)                                       \
+    ({                                                  \
+        ty _val;                                        \
+                                                        \
+        if ( (ip + sizeof(ty)) > end )                  \
+            goto overrun;                               \
+        _val = *(ty *)ip;                               \
+        ip += sizeof(ty);                               \
+        _val;                                           \
+    })
+
+    for ( ;; ) /* Prefixes */
+    {
+        switch ( b = FETCH(uint8_t) )
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 162

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */

If you don't like the idea of a Prefix attribute

Quoted 4 lines

I don't like the idea of making this intentionally dissimilar to the main decoder, just to safe a few lines of source code.

GCC optimises it into a bitmap anyway.

Well, okay then.

Quoted 15 lines
Quoted 14 lines

I wonder in how far we
actually need all of the above, when you already ...

xen/arch/x86/x86_emulate/decode-lite.c line 172

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        case 0xf0: /* LOCK */
+        case 0xf2: /* REPNE */
+        case 0xf3: /* REP */
+            break;
+
+        case 0x66: /* Operand size override */
+            osize = 2;
+            break;
+
+        /* case 0x67: Address size override, not implemented */

... deliberately leave of this one.

Quoted 2 lines

Excluding 67 is intentional because it a) has no business being used, and b) adds a huge amount of decode complexity.

I largely agree with a), but why b)? The only difference in decode is how to treat moffs. In any event - the comments here again were because things looks somewhat inconsistent the way they are right now. As that's deliberate, it's perhaps tolerable.

Quoted 71 lines

Whereas two of segment prefixes are already necessary to decode the alternatives we have today.

Quoted 5 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+        case 0x40 ... 0x4f: /* REX */
+            rex = b;
+            continue;
+
+        default:
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 185

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+            goto prefixes_done;
+        }
+        rex = 0; /* REX cancelled by subsequent legacy prefix. */
+    }
+ prefixes_done:
+
+    if ( rex & 0x08 ) /* REX.W */

Can you please use REX_W here?

Oh, it is available.  Ok.

Quoted 44 lines
Quoted 44 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +43 -0
+        osize = 8;
+
+    /* Fetch the main opcode byte(s) */
+    if ( b == 0x0f )
+    {
+        b = FETCH(uint8_t);
+        opc = OPC_TWOBYTE | b;
+
+        d = twobyte[b];
+    }
+    else
+    {
+        opc = b;
+        d = onebyte[b];
+    }
+
+    if ( unlikely(!(d & Known)) )
+        goto unknown;
+
+    if ( d & ModRM )
+    {
+        uint8_t modrm = FETCH(uint8_t);
+        uint8_t mod = modrm >> 6;
+        uint8_t reg = (modrm >> 3) & 7;
+        uint8_t rm = modrm & 7;
+
+        /* ModRM/SIB decode */
+        if ( mod == 0 && rm == 5 ) /* RIP relative */
+        {
+            rel = ip;
+            rel_sz = 4;
+            FETCH(uint32_t);
+        }
+        else if ( mod != 3 && rm == 4 ) /* SIB */
+        {
+            uint8_t sib = FETCH(uint8_t);
+            uint8_t base = sib & 7;
+
+            if ( mod == 0 && base == 5 )
+                goto disp32;
+        }
+
+        if ( mod == 1 ) /* disp8 */
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 233

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+            FETCH(uint8_t);
+        else if ( mod == 2 ) /* disp32 */
+        {
+        disp32:
+            FETCH(uint32_t);

The values aren't used, so the types don't matter overly much, yet int8_t and int32_t would be a more accurate representation of what's being fetched.

Quoted 2 lines

Why does that matter?  I'm skipping a number of bytes, not interpreting the result.

It matters from a doc pov only at this point. When one simply reads this code, one may wonder "why unsigned". Just like I did.

Quoted 18 lines
Quoted 18 lines
Quoted 18 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +18 -0
+        }
+
+        /* ModRM based decode adjustements */
+        switch ( opc )
+        {
+        case 0xc7: /* Grp11 XBEGIN is a branch. */
+            if ( modrm == 0xf8 )
+                d |= Branch;
+            break;
+        case 0xf6: /* Grp3 TEST(s) have extra Imm8 */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm8;
+            break;
+        case 0xf7: /* Grp3 TEST(s) have extra Imm */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm;
+            break;
+        }
Quoted 3 lines
Quoted 1 line

In this switch() you don't distinguish 1- and 2-byte maps at all.

See OPC_TWOBYTE.  They are distinguished here.

Oh, I've overlooked that, sorry.

Quoted 28 lines
Quoted 28 lines
Quoted 15 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +15 -0
+    }
+
+    if ( d & Branch )
+    {
+        /*
+         * We don't tolerate 66-prefixed call/jmp in alternatives.  Some are
+         * genuinely decoded differently between Intel and AMD CPUs.
+         *
+         * We also don't support APX instructions, so don't have to cope with
+         * JMPABS which is the first branch to have an 8-byte immediate.
+         */
+        if ( osize < 4 )
+            goto bad_osize;
+
+        rel = ip;

xen/arch/x86/x86_emulate/decode-lite.c line 276

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        rel_sz = (d & Imm8) ? 1 : 4;
+    }
+
+    if ( d & (Imm | Imm8 | Moffs) )
+    {
+        if ( d & Imm8 )
+            osize = 1;
+        else if ( d & Moffs )
+            osize = 8;
+        else if ( osize == 8 && !(opc >= 0xb8 && opc <= 0xbf) )

Again want to also take the opcode map into account, even if - by luck - this would work as is for now.

Quoted 4 lines
Quoted 2 lines

Also could I talk you into converting the two comparisons into one, along the lines of "(opc | 7) != 0xbf"?

That's the kind of obfuscation which should be left to the compiler.

If only it actually did. I didn't check recently, but last I checked they still didn't take opportunities like this.

Quoted 15 lines
Quoted 5 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/private.h +0 -0
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
Quoted 9 lines

xen/arch/x86/x86_emulate/private.h line 17

Quoted 7 lines
xen/arch/x86/x86_emulate/private.h +2 -0
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>
 # include <asm/endbr.h>
 # include <asm/msr-index.h>
 # include <asm/x86-vendors.h>

It's only the new file that needs these - can we limit the dependencies to just that one by putting these new #include-s there?

Quoted 1 line

Not if you want the userspace harness in patch 2 to compile.

This is inside #ifdef __XEN__, so how can the userspace harness'es build matter? Of course the #include-s, once moved, would need to be inside a similar #ifdef.

Jan

#5 lore raw

PATCH v2 2/7 tests/x86: Introduce a userspace test harness for x86_decode_lite()

In reply to Andrew Cooper

All the interesting behaviour is in insns.S.

There are 4 interesting cases; "not an instruction we tolerate", or one we do tolerate, split by no relation, disp8 or disp32. The DECL()/END() macros start and terminate the tests_*[] arrays used by C.

Between DECL()/END(), a macro named _ adds an entry into the array, including a name and the length of the instruction according to the assembler, while being as visually unintrusive as possible.

Plain labels are ad-hoc and there to aid legibility during disassembly. In a couple of cases, the macro named n (for name) allows for choosing a name manually, and is used for cases where the assembler doesn't like the mnemonic.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

v2:
* New

Despite claiming full APX support in the 2.43 release, binutils trunk doesn't tolerate JMPABS at all. Clang-IAS like it but only when encoded as an immediate, despite the fact the operand should be a moffset and encoded without a $ prefix. https://godbolt.org/z/P4Ph3svha

Back to this patch, I can't find any way to get Clang happy with rex.w for explicit prefixing. I suspect we're just going to need to ignore this test case for clang=y.

Also, Clang and GAS disagree on needing .allow_index_reg for %riz.

---
 tools/tests/Makefile                      |   1 +
 tools/tests/x86-decode-lite/.gitignore    |   1 +
 tools/tests/x86-decode-lite/Makefile      |  45 ++
 tools/tests/x86-decode-lite/insns.S       | 703 ++++++++++++++++++++++
 tools/tests/x86-decode-lite/macro-magic.h |  52 ++
 tools/tests/x86-decode-lite/main.c        | 111 ++++
 tools/tests/x86-decode-lite/x86-emulate.h |  27 +
 7 files changed, 940 insertions(+)
 create mode 100644 tools/tests/x86-decode-lite/.gitignore
 create mode 100644 tools/tests/x86-decode-lite/Makefile
 create mode 100644 tools/tests/x86-decode-lite/insns.S
 create mode 100644 tools/tests/x86-decode-lite/macro-magic.h
 create mode 100644 tools/tests/x86-decode-lite/main.c
 create mode 100644 tools/tests/x86-decode-lite/x86-emulate.h
tools/tests/Makefile +1 -0
index 1319c3a9d88c..6a8844673abc 100644
@@ -5,6 +5,7 @@ SUBDIRS-y :=
 SUBDIRS-y += resource
 SUBDIRS-$(CONFIG_X86) += cpu-policy
 SUBDIRS-$(CONFIG_X86) += tsx
+SUBDIRS-$(CONFIG_X86) += x86-decode-lite
 ifneq ($(clang),y)
 SUBDIRS-$(CONFIG_X86) += x86_emulator
 endif
tools/tests/x86-decode-lite/.gitignore new file +1 -0
new file mode 100644
index 000000000000..e726b493c993
@@ -0,0 +1 @@
+test-x86-decode-lite
tools/tests/x86-decode-lite/Makefile new file +45 -0

45 lines not on this page · raw message

tools/tests/x86-decode-lite/insns.S new file +703 -0

703 lines not on this page · raw message

tools/tests/x86-decode-lite/macro-magic.h new file +52 -0

52 lines not on this page · raw message

tools/tests/x86-decode-lite/main.c new file +111 -0

111 lines not on this page · raw message

tools/tests/x86-decode-lite/x86-emulate.h new file +27 -0
new file mode 100644
index 000000000000..558dab1b768e
@@ -0,0 +1,27 @@
+#ifndef X86_EMULATE_H
+#define X86_EMULATE_H
+
+#include <assert.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <xen/asm/x86-defns.h>
+#include <xen/asm/x86-vendors.h>
+
+#include <xen-tools/common-macros.h>
+
+#define ASSERT assert
+
+#define printk(...)
+
+#define likely
+#define unlikely
+#define cf_check
+#define init_or_livepatch
+#define init_or_livepatch_const
+
+#include "x86_emulate/x86_emulate.h"
+
+#endif /* X86_EMULATE_H */
Signature · 1 line
2.39.5
#6 lore raw

Re: [PATCH v2 2/7] tests/x86: Introduce a userspace test harness for x86_decode_lite()

Quoted 4 lines · Andrew Cooper

Despite claiming full APX support in the 2.43 release, binutils trunk doesn't tolerate JMPABS at all. Clang-IAS like it but only when encoded as an immediate, despite the fact the operand should be a moffset and encoded without a $ prefix. https://godbolt.org/z/P4Ph3svha

Actually, no.  Despite overlaying MOV moffs/rax, to share decode with another instruction that has a forced 8-byte immedate operation, it's used as a proper immediate, not a memory address.

So on further consideration, the $ prefix is correct.

~Andrew

#7 lore raw

Re: [PATCH v2 2/7] tests/x86: Introduce a userspace test harness for x86_decode_lite()

Quoted 11 lines · Andrew Cooper
Quoted 4 lines · Andrew Cooper

Despite claiming full APX support in the 2.43 release, binutils trunk doesn't tolerate JMPABS at all. Clang-IAS like it but only when encoded as an immediate, despite the fact the operand should be a moffset and encoded without a $ prefix. https://godbolt.org/z/P4Ph3svha

Actually, no.  Despite overlaying MOV moffs/rax, to share decode with another instruction that has a forced 8-byte immedate operation, it's used as a proper immediate, not a memory address.

So on further consideration, the $ prefix is correct.

This one's actually pretty ambiguous. Other direct branches don't use $, i.e. consider the operand a "displacement", not an "immediate". Except for far direct branches, which have (two) immediate operands. Originally coming from the Intel syntax world, where this distinction doesn't even exist, I question that arrangement. Imo far direct branches should have a non-immediate and an immediate operand (the latter being the segment / selector). That would also properly distinguish which one's which. Yet that ship has sailed; we could add support for the alternative forms, but we can't drop support for the 2- immediate variants.

I'd prefer to not repeat the mistake for JMPABS: The destination generally is a symbol, and hence more natural to use without $. In the end it may be prudent to simply permit both forms.

In any event I've added to my gas TODO list the need for JMPABS support.

Jan

#8 lore raw

Re: [PATCH v2 2/7] tests/x86: Introduce a userspace test harness for x86_decode_lite()

In reply to Andrew Cooper
Quoted 3 lines · Andrew Cooper

Back to this patch, I can't find any way to get Clang happy with rex.w for explicit prefixing. I suspect we're just going to need to ignore this test case for clang=y.

ISTR experimenting with that too a little while back, finding that newer Clang supports at least rex64.

Quoted 1 line

Also, Clang and GAS disagree on needing .allow_index_reg for %riz.

Disagree in which way? Does Clang accept it even without the directive? If so, that maybe fine for AT&T syntax code, but it definitely isn't for Intel syntax.

tools/tests/Makefile SUBDIRS-y := · line 8

Quoted 7 lines
tools/tests/Makefile +1 -0
@@ -5,6 +5,7 @@ SUBDIRS-y :=
 SUBDIRS-y += resource
 SUBDIRS-$(CONFIG_X86) += cpu-policy
 SUBDIRS-$(CONFIG_X86) += tsx
+SUBDIRS-$(CONFIG_X86) += x86-decode-lite

Won't this be wrong when the tool stack is built 32-bit?

Quoted 26 lines
tools/tests/x86-decode-lite/Makefile new file +23 -0
@@ -0,0 +1,45 @@
+XEN_ROOT = $(CURDIR)/../../..
+include $(XEN_ROOT)/tools/Rules.mk
+
+TARGET := test-x86-decode-lite
+
+.PHONY: all
+all: $(TARGET)
+
+.PHONY: run
+run: $(TARGET)
+	./$<
+
+.PHONY: clean
+clean:
+	$(RM) -- *.o $(TARGET) $(DEPS_RM)
+
+.PHONY: distclean
+distclean: clean
+	$(RM) -- *~
+
+.PHONY: install
+install: all
+	$(INSTALL_DIR) $(DESTDIR)$(LIBEXEC_BIN)

tools/tests/x86-decode-lite/Makefile line 33

Quoted 10 lines
tools/tests/x86-decode-lite/Makefile new file +10 -0
+	$(INSTALL_PROG) $(TARGET) $(DESTDIR)$(LIBEXEC_BIN)
+
+.PHONY: uninstall
+uninstall:
+	$(RM) -- $(DESTDIR)$(LIBEXEC_BIN)/$(TARGET)
+
+.PHONY: uninstall
+uninstall:
+
+vpath %.c ../../../xen/arch/x86/x86_emulate

What is it that you take from there? All ...

tools/tests/x86-decode-lite/Makefile line 42

Quoted 8 lines
tools/tests/x86-decode-lite/Makefile new file +8 -0
+CFLAGS += $(CFLAGS_xeninclude) -I. -I../../../xen/arch/x86/
+CFLAGS += $(APPEND_CFLAGS)
+
+LDFLAGS += $(APPEND_LDFLAGS)
+
+%.o: Makefile
+
+$(TARGET): main.o insns.o decode-lite.o

... objects enumerated here come from local sources.

Quoted 21 lines
tools/tests/x86-decode-lite/insns.S new file +18 -0
@@ -0,0 +1,703 @@
+#include "macro-magic.h"
+
+        .code64
+
+#ifndef __clang__
+        .allow_index_reg
+#endif
+        .text
+
+DECL(tests_rel0)
+modrm:
+        /* Mod=0, Reg=0, RM {0..f} */
+        _ add %al, (%rax)
+        _ add %al, (%rcx)
+        _ add %al, (%rdx)
+        _ add %al, (%rbx)
+        _ add %al, (%rsp) /* SIB */
+        /*add %al, (%rbp)    RIP --> tests_rel4 */

tools/tests/x86-decode-lite/insns.S line 28

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ add %al, (%rsi)
+        _ add %al, (%rdi)
+        _ add %al, (%r8)
+        _ add %al, (%r9)
+        _ add %al, (%r10)
+        _ add %al, (%r11)
+        _ add %al, (%r12) /* SIB */
+        /*add %al, (%r13)    RIP --> tests_rel4 */
+        _ add %al, (%r14)
+        _ add %al, (%r15)

There's a lot of redundancy here and below - did you consider using .irp to reduce this some?

Quoted 160 lines
tools/tests/x86-decode-lite/insns.S new file +160 -0
+        /* Mod=1, Reg=0, RM {0..f} */
+        _ add %al, 0x01(%rax)
+        _ add %al, 0x01(%rcx)
+        _ add %al, 0x01(%rdx)
+        _ add %al, 0x01(%rbx)
+        _ add %al, 0x01(%rsp) /* SIB */
+        _ add %al, 0x01(%rbp)
+        _ add %al, 0x01(%rsi)
+        _ add %al, 0x01(%rdi)
+        _ add %al, 0x01(%r8)
+        _ add %al, 0x01(%r9)
+        _ add %al, 0x01(%r10)
+        _ add %al, 0x01(%r11)
+        _ add %al, 0x01(%r12) /* SIB */
+        _ add %al, 0x01(%r13)
+        _ add %al, 0x01(%r14)
+        _ add %al, 0x01(%r15)
+
+        /* Mod=2, Reg=0, RM {0..f} */
+        _ add %al, 0x7f000001(%rax)
+        _ add %al, 0x7f000001(%rcx)
+        _ add %al, 0x7f000001(%rdx)
+        _ add %al, 0x7f000001(%rbx)
+        _ add %al, 0x7f000001(%rsp) /* SIB */
+        _ add %al, 0x7f000001(%rbp)
+        _ add %al, 0x7f000001(%rsi)
+        _ add %al, 0x7f000001(%rdi)
+        _ add %al, 0x7f000001(%r8)
+        _ add %al, 0x7f000001(%r9)
+        _ add %al, 0x7f000001(%r10)
+        _ add %al, 0x7f000001(%r11)
+        _ add %al, 0x7f000001(%r12) /* SIB */
+        _ add %al, 0x7f000001(%r13)
+        _ add %al, 0x7f000001(%r14)
+        _ add %al, 0x7f000001(%r15)
+
+        /* Mod=3, Reg=0, RM {0..f} */
+        _ add %al, %al
+        _ add %al, %cl
+        _ add %al, %dl
+        _ add %al, %bl
+        _ add %al, %ah
+        _ add %al, %ch
+        _ add %al, %dh
+        _ add %al, %dl
+        _ add %al, %r8b
+        _ add %al, %r9b
+        _ add %al, %r10b
+        _ add %al, %r11b
+        _ add %al, %r12b
+        _ add %al, %r13b
+        _ add %al, %r14b
+        _ add %al, %r15b
+
+sib:
+        /* Mod=0, Reg=0, RM=4, SIB S=3, I=0, B {0..f} */
+        _ add %al, (%rax, %rax, 8)
+        _ add %al, (%rcx, %rax, 8)
+        _ add %al, (%rdx, %rax, 8)
+        _ add %al, (%rbx, %rax, 8)
+        _ add %al, (%rsp, %rax, 8)
+        _ add %al, (    , %rax, 8) /* "none", %rbp encoded with mod=1/2 */
+        _ add %al, (%rsi, %rax, 8)
+        _ add %al, (%rdi, %rax, 8)
+        _ add %al, (%r8,  %rax, 8)
+        _ add %al, (%r9,  %rax, 8)
+        _ add %al, (%r10, %rax, 8)
+        _ add %al, (%r11, %rax, 8)
+        _ add %al, (%r12, %rax, 8)
+        _ rex.b add %al,(,%rax, 8) /* "none", %r13 encoded with mod=1/2 */
+        _ add %al, (%r14, %rax, 8)
+        _ add %al, (%r15, %rax, 8)
+
+        /* Mod=1, Reg=0, RM=4, SIB S=3, I=0, B {0..f} */
+        _ add %al, 0x01(%rax, %rax, 8)
+        _ add %al, 0x01(%rcx, %rax, 8)
+        _ add %al, 0x01(%rdx, %rax, 8)
+        _ add %al, 0x01(%rbx, %rax, 8)
+        _ add %al, 0x01(%rsp, %rax, 8)
+        _ add %al, 0x01(%rbp, %rax, 8)
+        _ add %al, 0x01(%rsi, %rax, 8)
+        _ add %al, 0x01(%rdi, %rax, 8)
+        _ add %al, 0x01(%r8,  %rax, 8)
+        _ add %al, 0x01(%r9,  %rax, 8)
+        _ add %al, 0x01(%r10, %rax, 8)
+        _ add %al, 0x01(%r11, %rax, 8)
+        _ add %al, 0x01(%r12, %rax, 8)
+        _ add %al, 0x01(%r13, %rax, 8)
+        _ add %al, 0x01(%r14, %rax, 8)
+        _ add %al, 0x01(%r15, %rax, 8)
+
+        /* Mod=2, Reg=0, RM=4, SIB S=3, I=0, B {0..f} */
+        _ add %al, 0x7f000001(%rax, %rax, 8)
+        _ add %al, 0x7f000001(%rcx, %rax, 8)
+        _ add %al, 0x7f000001(%rdx, %rax, 8)
+        _ add %al, 0x7f000001(%rbx, %rax, 8)
+        _ add %al, 0x7f000001(%rsp, %rax, 8)
+        _ add %al, 0x7f000001(%rbp, %rax, 8)
+        _ add %al, 0x7f000001(%rsi, %rax, 8)
+        _ add %al, 0x7f000001(%rdi, %rax, 8)
+        _ add %al, 0x7f000001(%r8,  %rax, 8)
+        _ add %al, 0x7f000001(%r9,  %rax, 8)
+        _ add %al, 0x7f000001(%r10, %rax, 8)
+        _ add %al, 0x7f000001(%r11, %rax, 8)
+        _ add %al, 0x7f000001(%r12, %rax, 8)
+        _ add %al, 0x7f000001(%r13, %rax, 8)
+        _ add %al, 0x7f000001(%r14, %rax, 8)
+        _ add %al, 0x7f000001(%r15, %rax, 8)
+
+        /* Mod=0, Reg=0, RM=4, SIB S=3, I=4, B {0..f} */
+        _ add %al, (%rax, %riz, 8)
+        _ add %al, (%rcx, %riz, 8)
+        _ add %al, (%rdx, %riz, 8)
+        _ add %al, (%rbx, %riz, 8)
+        _ add %al, (%rsp, %riz, 8)
+        _ add %al, (    , %riz, 8) /* %rbp encoded with mod=1/2 */
+        _ add %al, (%rsi, %riz, 8)
+        _ add %al, (%rdi, %riz, 8)
+        _ add %al, (%r8,  %riz, 8)
+        _ add %al, (%r9,  %riz, 8)
+        _ add %al, (%r10, %riz, 8)
+        _ add %al, (%r11, %riz, 8)
+        _ add %al, (%r12, %riz, 8)
+        _ rex.b add %al,(,%riz, 8) /* %r13 encoded with mod=1/2 */
+        _ add %al, (%r14, %riz, 8)
+        _ add %al, (%r15, %riz, 8)
+
+        /* Mod=1, Reg=0, RM=4, SIB S=3, I=4, B {0..f} */
+        _ add %al, 0x01(%rax, %riz, 8)
+        _ add %al, 0x01(%rcx, %riz, 8)
+        _ add %al, 0x01(%rdx, %riz, 8)
+        _ add %al, 0x01(%rbx, %riz, 8)
+        _ add %al, 0x01(%rsp, %riz, 8)
+        _ add %al, 0x01(%rbp, %riz, 8)
+        _ add %al, 0x01(%rsi, %riz, 8)
+        _ add %al, 0x01(%rdi, %riz, 8)
+        _ add %al, 0x01(%r8,  %riz, 8)
+        _ add %al, 0x01(%r9,  %riz, 8)
+        _ add %al, 0x01(%r10, %riz, 8)
+        _ add %al, 0x01(%r11, %riz, 8)
+        _ add %al, 0x01(%r12, %riz, 8)
+        _ add %al, 0x01(%r13, %riz, 8)
+        _ add %al, 0x01(%r14, %riz, 8)
+        _ add %al, 0x01(%r15, %riz, 8)
+
+        /* Mod=2, Reg=0, RM=4, SIB S=3, I=4, B {0..f} */
+        _ add %al, 0x7f000001(%rax, %riz, 8)
+        _ add %al, 0x7f000001(%rcx, %riz, 8)
+        _ add %al, 0x7f000001(%rdx, %riz, 8)
+        _ add %al, 0x7f000001(%rbx, %riz, 8)
+        _ add %al, 0x7f000001(%rsp, %riz, 8)
+        _ add %al, 0x7f000001(%rbp, %riz, 8)
+        _ add %al, 0x7f000001(%rsi, %riz, 8)
+        _ add %al, 0x7f000001(%rdi, %riz, 8)
+        _ add %al, 0x7f000001(%r8,  %riz, 8)
+        _ add %al, 0x7f000001(%r9,  %riz, 8)
+        _ add %al, 0x7f000001(%r10, %riz, 8)
+        _ add %al, 0x7f000001(%r11, %riz, 8)
+        _ add %al, 0x7f000001(%r12, %riz, 8)
+        _ add %al, 0x7f000001(%r13, %riz, 8)

tools/tests/x86-decode-lite/insns.S line 199

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ add %al, 0x7f000001(%r14, %riz, 8)
+        _ add %al, 0x7f000001(%r15, %riz, 8)
+
+        .macro alu_ops op
+        _ \op %al, (%rax)
+        _ \op %eax, (%rax)
+        _ \op (%rax), %al
+        _ \op (%rax), %eax
+        _ \op $1, %al
+        _ \op $0x7f000001, %eax

While immediate forms below also come in word and qword flavors, no such exist for the non-immediate forms above. Is that intentional?

tools/tests/x86-decode-lite/insns.S line 204

Quoted 4 lines
tools/tests/x86-decode-lite/insns.S new file +4 -0
+        /* Vary osize on imm fields */
+        _ data16 \op $1, %al
+        _ rex.w \op $1, %al
+        _ data16 rex.w \op $1, %al

Yet for byte ops the immediate is never going to be wider than a byte. Wouldn't these be more interesting with word/dword/qword operand size?

Quoted 147 lines
tools/tests/x86-decode-lite/insns.S new file +147 -0
+        _ \op $0x7f01, %ax
+        _ \op $0x7f000001, %rax
+        _ data16 \op $0x7f000001, %rax
+        .endm
+
+onebyte_row_0x:
+        alu_ops add
+        alu_ops or
+
+onebyte_row_1x:
+        alu_ops adc
+        alu_ops sbb
+
+onebyte_row_2x:
+        alu_ops and
+        .code32
+        _ es nop
+        .code64
+        alu_ops sub
+        _ cs nop
+
+onebyte_row_3x:
+        alu_ops xor
+        .code32
+        _ ss nop
+        .code64
+        alu_ops cmp
+        _ ds nop
+
+/* onebyte_row_4x --> rex prefixes */
+
+onebyte_row_5x:
+        _ push %rax
+        _ push %rcx
+        _ push %rdx
+        _ push %rbx
+        _ push %rsp
+        _ push %rbp
+        _ push %rsi
+        _ push %rdi
+        _ pop %rax
+        _ pop %rcx
+        _ pop %rdx
+        _ pop %rbx
+        _ pop %rsp
+        _ pop %rbp
+        _ pop %rsi
+        _ pop %rdi
+
+onebyte_row_6x:
+        /*pusha,popa,bound --> not supported */
+        _ movsxd (%rax), %eax
+        _ movslq (%rax), %rax
+        _ fs nop
+        _ gs nop
+        _ data16 nop
+        /* addr32 --> not supported */
+        _ pushq $0x7f000001
+        _ pushw $0x7f01
+        _ rex.w pushq $0x7f000001
+        _ imul $0x7f01, %ax, %ax
+        _ imul $0x7f000001, %eax, %eax
+        _ imul $0x7f000001, %rax, %rax
+        _ pushq $0
+        _ pushw $0
+        _ rex.w pushq $0
+        _ imul $0, %ax, %ax
+        _ imul $0, %eax, %eax
+        _ imul $0, %rax, %rax
+        _ insb
+        _ insw
+        _ insl
+        _ outsb
+        _ outsw
+        _ outsl
+
+/* onebyte_row_7x: --> Jcc disp8 */
+
+onebyte_row_8x:
+        _ add $0, %cl /* Grp1 */
+        _ data16 add $0, %cl
+        _ rex.w add $0, %cl
+        _ add $0x7f01, %cx
+        _ add $0x7f000001, %ecx
+        _ add $0x7f000001, %rcx
+        _ add $0, %cx
+        _ add $0, %ecx
+        _ add $0, %rcx
+        _ test %cl, %cl
+        _ test %ecx, %ecx
+        _ xchg %cl, %cl
+        _ xchg %ecx, %ecx
+        _ mov %cl, (%rax)
+        _ mov %ecx, (%rax)
+        _ mov (%rax), %cl
+        _ mov (%rax), %ecx
+        _ mov %cs, (%rax)
+        _ lea (%rax), %eax
+        _ mov (%rax), %cs
+        /*pop mem --> Grp1a, Not supported (XOP prefix adjacent) */
+
+onebyte_row_9x:
+        _ nop
+        _ pause
+        _ xchg %ax, %ax
+        _ xchg %eax, %eax
+        _ xchg %rax, %rax
+        _ rex.w xchg %rax, %rax
+        _ cltq
+        _ cqto
+        _ wait
+        _ pushf
+        _ popf
+        _ sahf
+        _ lahf
+
+onebyte_row_ax:
+        _ mov 0x8000000000000001, %al
+        _ mov 0x8000000000000001, %ax
+        _ mov 0x8000000000000001, %eax
+        _ mov 0x8000000000000001, %rax
+        _ mov %al,  0x8000000000000001
+        _ mov %ax,  0x8000000000000001
+        _ mov %eax, 0x8000000000000001
+        _ mov %rax, 0x8000000000000001
+        _ movsb
+        _ movsl
+        _ cmpsb
+        _ cmpsl
+        _ test $0, %al
+        _ test $0x80000001, %eax
+        _ test $0x7f000001, %rax
+        _ stosb
+        _ stosl
+        _ lodsb
+        _ lodsl
+        _ scasb
+        _ scasl
+
+onebyte_row_bx:
+        _ mov $0, %al
+        _ mov $0, %cl
+        _ mov $0x7f01, %ax
+        _ mov $0x7f01, %cx
+        _ mov $0x7f000001, %eax
+        _ mov $0x7f000001, %ecx
+        _ mov $0x7f00000000000001, %rax

tools/tests/x86-decode-lite/insns.S line 362

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ mov $0x7f00000000000001, %rcx
+
+onebyte_row_cx:
+        _ rol $0, %al /* Grp2 */
+        _ rol $0, %ax
+        _ rol $0, %eax
+        _ rol $0, %rax
+        /*ret $0 --> not supported */
+        _ ret
+        /*les,lds --> not supported */

LES and LDS don't even exist for 64-bit code.

Quoted 20 lines
tools/tests/x86-decode-lite/insns.S new file +20 -0
+        _ movb $0, (%rax) /* Grp11 */
+        _ movw $0, (%rax)
+        _ movl $0, (%rax)
+        _ movq $0, (%rax)
+        /*xbegin (Grp11) --> disp32 */
+        /*enter,leave,lretq $0 --> not supported */
+        _ lretq
+        _ int3
+        _ int $0
+        /*into,iret --> not supported */
+
+onebyte_row_dx:
+        _ rol $1, %al /* Grp2 */
+        _ rol $1, %ax
+        _ rol $1, %eax
+        _ rol $1, %rax
+        _ rol %cl, %al
+        _ rol %cl, %ax
+        _ rol %cl, %eax
+        _ rol %cl, %rax

tools/tests/x86-decode-lite/insns.S line 392

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        /*aam,aad,setalc,xlat,d8...df --> not supported */
+
+onebyte_row_ex:
+        /*loop{ne,e,},jrcxz --> not supported */
+        _ in $0, %al
+        _ in $0, %eax
+        _ out %al,  $0
+        _ out %eax, $0
+        /*call,jmp --> disp32 */
+        /*ljmp --> not supported */

Nor does this, and you also don't have a similar comment for lcall (0x9a).

Quoted 277 lines
tools/tests/x86-decode-lite/insns.S new file +277 -0
+        /*jmp --> disp8 */
+        _ in %dx, %al
+        _ in %dx, %eax
+        _ out %al,  %dx
+        _ out %eax, %dx
+
+onebyte_row_fx:
+        _ lock addb $0, (%rax)
+        n "icebp" .byte 0xf1 /* icebp */
+        _ repne nop
+        _ repe nop
+        _ hlt
+        _ cmc
+        _ test $0, %cl /* Grp3, /0 has extra Imm{8,} */
+        _ not %cl
+        _ test $0x7f01, %cx
+        _ not %cx
+        _ test $0x7f000001, %ecx
+        _ not %ecx
+        _ test $0x7f000001, %rcx
+        _ not %rcx
+        _ clc
+        _ stc
+        _ cli
+        _ sti
+        _ cld
+        _ std
+        _ inc %cl /* Grp4 */
+        _ dec %cl
+        _ inc %ecx /* Grp5 */
+        _ dec %ecx
+        _ call *(%rax)
+        _ lcall *(%rax)
+        _ jmp *(%rax)
+        _ ljmp *(%rax)
+        _ push (%rax)
+
+twobyte_row_0x:
+        _ sldt (%rax) /* Grp6 */
+        _ sgdt (%rax) /* Grp7 */
+        _ lar (%rax), %eax
+        _ lsl (%rax), %eax
+        _ clts
+        _ wbinvd
+        _ ud2a
+
+twobyte_row_1x:
+        _ prefetchnta (%rax) /* Grp16 (Hint Nop) */
+        _ nopl (%rax)
+
+twobyte_row_2x:
+        _ mov %cr0, %rax
+        _ mov %dr0, %rax
+        _ mov %rax, %cr0
+        _ mov %rax, %dr0
+
+twobyte_row_3x:
+        _ wrmsr
+        _ rdtsc
+        _ rdmsr
+        _ rdpmc
+
+twobyte_row_4x:
+        _ cmovo (%rax), %eax
+        _ cmovg (%rax), %eax
+
+/* twobyte_row_8x: --> Jcc disp32 */
+
+twobyte_row_9x:
+        _ seto (%rax)
+        _ setg (%rax)
+
+twobyte_row_ax:
+        _ push %fs
+        _ pop %fs
+        _ cpuid
+        _ bt %eax, (%rax)
+        _ shld $0, %ax, (%rax)
+        _ shld $0, %eax, (%rax)
+        _ shld $0, %rax, (%rax)
+        _ shld %cl, %ax, (%rax)
+        _ shld %cl, %eax, (%rax)
+        _ shld %cl, %rax, (%rax)
+        _ push %gs
+        _ pop %gs
+        /*rsm --> not supported */
+        _ bts %eax, (%rax)
+        _ shrd $0, %ax, (%rax)
+        _ shrd $0, %eax, (%rax)
+        _ shrd $0, %rax, (%rax)
+        _ shrd %cl, %ax, (%rax)
+        _ shrd %cl, %eax, (%rax)
+        _ shrd %cl, %rax, (%rax)
+        _ fxsave (%rax) /* Grp15 */
+        _ imul (%rax), %eax
+
+twobyte_row_bx:
+        _ cmpxchg %al, (%rax)
+        _ cmpxchg %eax, (%rax)
+        _ lss (%rax), %eax
+        _ btr %eax, (%rax)
+        _ lfs (%rax), %eax
+        _ lgs (%rax), %eax
+        _ movzbl (%rax), %eax
+        _ movzwl (%rax), %eax
+        _ popcnt (%rax), %eax
+        _ ud1 (%rax), %eax /* Grp10 */
+        _ bt $0, %ax /* Grp8 */
+        _ bt $0, %eax
+        _ bt $0, %rax
+        _ btc %eax, (%rax)
+        _ bsf (%rax), %eax
+        _ bsr (%rax), %eax
+        _ movsbl (%rax), %eax
+        _ movswl (%rax), %eax
+
+twobyte_row_cx:
+        _ xadd %al, (%rax)
+        _ xadd %eax, (%rax)
+        _ cmpxchg8b (%rax) /* Grp9 */
+        _ bswap %eax
+        _ bswap %edi
+
+END(tests_rel0)
+
+DECL(tests_rel1)
+disp8:
+1:
+        _ jo   1b
+        _ jno  1b
+        _ jb   1b
+        _ jae  1b
+        _ je   1b
+        _ jne  1b
+        _ jbe  1b
+        _ ja   1b
+        _ js   1b
+        _ jns  1b
+        _ jp   1b
+        _ jnp  1b
+        _ jl   1b
+        _ jge  1b
+        _ jle  1b
+        _ jg   1b
+        _ jmp  1b
+
+disp8_rex:
+        _ rex.w jo   1b
+        _ rex.w jno  1b
+        _ rex.w jb   1b
+        _ rex.w jae  1b
+        _ rex.w je   1b
+        _ rex.w jne  1b
+        _ rex.w jbe  1b
+        _ rex.w ja   1b
+        _ rex.w js   1b
+        _ rex.w jns  1b
+        _ rex.w jp   1b
+        _ rex.w jnp  1b
+        _ rex.w jl   1b
+        _ rex.w jge  1b
+        _ rex.w jle  1b
+        _ rex.w jg   1b
+        _ rex.w jmp  1b
+END(tests_rel1)
+
+DECL(tests_rel4)
+disp32:
+        _ call   other_section
+        _ jmp    other_section
+        _ jo     other_section
+        _ jno    other_section
+        _ jb     other_section
+        _ jae    other_section
+        _ je     other_section
+        _ jne    other_section
+        _ jbe    other_section
+        _ ja     other_section
+        _ js     other_section
+        _ jns    other_section
+        _ jp     other_section
+        _ jnp    other_section
+        _ jl     other_section
+        _ jge    other_section
+        _ jle    other_section
+        _ jg     other_section
+        _ xbegin other_section
+
+disp32_rex:
+        _ rex.w call   other_section
+        _ rex.w jmp    other_section
+        _ rex.w jo     other_section
+        _ rex.w jno    other_section
+        _ rex.w jb     other_section
+        _ rex.w jae    other_section
+        _ rex.w je     other_section
+        _ rex.w jne    other_section
+        _ rex.w jbe    other_section
+        _ rex.w ja     other_section
+        _ rex.w js     other_section
+        _ rex.w jns    other_section
+        _ rex.w jp     other_section
+        _ rex.w jnp    other_section
+        _ rex.w jl     other_section
+        _ rex.w jge    other_section
+        _ rex.w jle    other_section
+        _ rex.w jg     other_section
+        _ rex.w xbegin other_section
+
+riprel:
+        _ add %al, 0(%rip)
+        _ rex.b add %al, 0(%rip)
+
+        _ addb $1, 0(%rip)
+        _ rex.b addb $1, 0(%rip)
+
+        _ addl $0x7f000001, 0(%rip)
+        _ rex.b addl $0x7f000001, 0(%rip)
+END(tests_rel4)
+
+DECL(tests_unsup)
+
+unsup_prefix: /* Prefixes unimplemented for simplicity. */
+        _ vaddpd %zmm0, %zmm0, %zmm0 /* 0x62 EVEX */
+        _ addr32 nop                 /* 0x67 Address size override */
+        _ bextr $0, %eax, %eax       /* 0x8f XOP */
+        _ bextr %eax, %eax, %eax     /* 0xc4 VEX3 */
+        _ vaddpd %ymm0, %ymm0, %ymm0 /* 0xc5 VEX2 */
+        n "jmpabs 0" .byte 0xd5, 0x00, 0xa1, 0x01, 0, 0, 0, 0, 0, 0, 0x80 /* 0xd5 REX2 */
+        _ fadds (%rax)               /* 0xd8 ... 0xdf ESCAPE (x87) */
+        _ femms                      /* 0x0f,0x0e ... 0x0f 3DNOW */
+
+unsup_branch:
+1:
+        _ loopne 1b
+        _ loope  1b
+        _ loop   1b
+        _ jrcxz  1b
+
+opsize_branch: /* 66-prefixed branches are decoded differently by vendors */
+        _ data16 call   other_section
+        _ data16 jmp    other_section
+        _ data16 jo     other_section
+        _ data16 jno    other_section
+        _ data16 jb     other_section
+        _ data16 jae    other_section
+        _ data16 je     other_section
+        _ data16 jne    other_section
+        _ data16 jbe    other_section
+        _ data16 ja     other_section
+        _ data16 js     other_section
+        _ data16 jns    other_section
+        _ data16 jp     other_section
+        _ data16 jnp    other_section
+        _ data16 jl     other_section
+        _ data16 jge    other_section
+        _ data16 jle    other_section
+        _ data16 jg     other_section
+        _ data16 xbegin other_section
+
+not_64bit: /* Not valid/encodable in 64bit mode */
+        .code32
+        _ push %es
+        _ pop %es
+        _ push %cs
+        _ push %ss
+        _ pop %ss
+        _ push %ds
+        _ pop %ds
+        _ daa
+        _ das
+        _ aaa
+        _ aas
+        _ pusha
+        _ popa
+        _ bound %eax, (%eax)
+        /*arpl %ax, %ax --> movsxd in 64bit mode */

tools/tests/x86-decode-lite/insns.S line 679

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        /* Grp1 */
+        _ lcall $-1, $-1
+        _ les (%eax), %eax
+        _ lds (%eax), %eax
+        _ into
+        _ aam $0
+        _ aad $0 /* Also REX2, also not supported */
+        n "salc" .byte 0xd6
+        _ ljmp $-1, $-1
+        .code64

I'm not sure we want to test these. Any of them can gain meaning (like D5 now did as REX2, and like D6 was for L1OM). Yes, for now we don't support e.g. REX2, but that can change.

tools/tests/x86-decode-lite/macro-magic.h line 9

Quoted 12 lines
tools/tests/x86-decode-lite/macro-magic.h new file +9 -0
@@ -0,0 +1,52 @@
+#ifndef X86_DECODE_LITE_LINKAGE_H
+#define X86_DECODE_LITE_LINKAGE_H
+
+/* Start a 'struct test' array */
+.macro start_arr aname
+    .pushsection .data.rel.ro.\aname, "aw", @progbits
+    .globl \aname
+    .type \aname, STT_OBJECT
+\aname:

No .align (or alike)?

Quoted 6 lines
tools/tests/x86-decode-lite/macro-magic.h new file +6 -0
+    .popsection
+
+    /* Declare a macro wrapping \aname */
+    .macro pushsection_arr
+    .pushsection .data.rel.ro.\aname, "aw", @progbits
+    .endm

tools/tests/x86-decode-lite/macro-magic.h line 25

Quoted 10 lines
tools/tests/x86-decode-lite/macro-magic.h new file +10 -0
+.endm
+
+/* Macro 'n' to wrap the metadata of an instruction.  Name can be different. */
+.macro n name:req insn:vararg
+    /* Emit the instruction, with start & end markers. */
+.Ls\@: \insn
+.Le\@:
+
+    /* Emit \name as a string. */
+    .pushsection .rosdata.str1, "aMS", @progbits, 1

.rodata.str1?

tools/tests/x86-decode-lite/macro-magic.h line 37

Quoted 12 lines
tools/tests/x86-decode-lite/macro-magic.h new file +12 -0
+.Ln\@: .asciz "\name"
+    .popsection
+
+    /* Emit an entry into the array. */
+    pushsection_arr
+    .quad .Ln\@, .Ls\@, .Le\@ - .Ls\@
+    .popsection
+.endm
+
+/* Macro '_' where the name is the instruction itself. */
+.macro _ insn:vararg
+    n "\insn" \insn

As agreed upon elsewhere, perhaps better to use a comma to separate the arguments (and also macro parameters further up).

Quoted 20 lines
tools/tests/x86-decode-lite/x86-emulate.h new file +17 -0
@@ -0,0 +1,27 @@
+#ifndef X86_EMULATE_H
+#define X86_EMULATE_H
+
+#include <assert.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <xen/asm/x86-defns.h>
+#include <xen/asm/x86-vendors.h>
+
+#include <xen-tools/common-macros.h>
+
+#define ASSERT assert
+
+#define printk(...)

tools/tests/x86-decode-lite/x86-emulate.h line 27

Quoted 10 lines
tools/tests/x86-decode-lite/x86-emulate.h new file +10 -0
+
+#define likely
+#define unlikely
+#define cf_check
+#define init_or_livepatch
+#define init_or_livepatch_const
+
+#include "x86_emulate/x86_emulate.h"
+
+#endif /* X86_EMULATE_H */

Deliberately not re-using the test harness'es x86-emulate.h?

Jan

#9 lore raw

PATCH v2 3/7 x86/alternative: Walk all replacements during self tests

In reply to Andrew Cooper

When self tests are active, walk all alternative replacements with x86_decode_lite().

This checks that we can decode all instructions, and also lets us check that disp8's don't leave the replacement block as such a case will definitely malfunction.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

v2:
* Rebase over API changes in patch 1
* Use +%lu and drop casts
* Swap to CONFIG_SELF_TESTS

---
 xen/arch/x86/alternative.c | 52 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 52 insertions(+)
xen/arch/x86/alternative.c +52 -0
index 1ba35cb9ede9..2dc759abd858 100644
@@ -15,6 +15,7 @@
 #include <asm/traps.h>
 #include <asm/nmi.h>
 #include <asm/nops.h>
+#include <asm/x86_emulate.h>
 #include <xen/livepatch.h>
 
 #define MAX_PATCH_LEN (255-1)
@@ -490,6 +491,57 @@ static void __init _alternative_instructions(bool force)
 void __init alternative_instructions(void)
 {
     arch_init_ideal_nops();
+
+    /*
+     * Walk all replacement instructions with x86_decode_lite().  This checks
+     * both that we can decode all instructions within the replacement, and
+     * that any near branch with a disp8 stays within the alternative itself.
+     */
+    if ( IS_ENABLED(CONFIG_SELF_TESTS) )
+    {
+        struct alt_instr *a;
+
+        for ( a = __alt_instructions;
+              a < __alt_instructions_end; ++a )
+        {
+            void *repl = ALT_REPL_PTR(a);
+            void *ip = repl, *end = ip + a->repl_len;
+
+            if ( !a->repl_len )
+                continue;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
+            {
+                const int8_t *d8;
+                const void *target;
+
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len == 0 )
+                {
+                    printk("Alt for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    panic("  Unable to decode instruction at +%lu in alternative\n",
+                          ip - repl);
+                }
+
+                if ( res.rel_sz != 1 )
+                    continue;
+
+                d8 = res.rel;
+                target = ip + res.len + *d8;
+
+                if ( target < repl || target > end )
+                {
+                    printk("Alt for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    panic("  'JMP/Jcc disp8' at +%lu leaves alternative block\n",
+                          ip - repl);
+                }
+            }
+        }
+    }
+
     _alternative_instructions(false);
 }
 
Signature · 1 line
2.39.5
#10 lore raw

PATCH v2 4/7 x86/alternative: Indent the relocation logic

In reply to Andrew Cooper

... to make subsequent patches legible.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 124 +++++++++++++++++++------------------
 1 file changed, 63 insertions(+), 61 deletions(-)
xen/arch/x86/alternative.c +63 -61
index 2dc759abd858..5ea7f51b007c 100644
@@ -264,78 +264,80 @@ static int init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
-        /* 0xe8/0xe9 are relative branches; fix the offset. */
-        if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
         {
-            /*
-             * Detect the special case of indirect-to-direct branch patching:
-             * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
-             *   checked above),
-             * - replacement's displacement is -5 (pointing back at the very
-             *   insn, which makes no sense in a real replacement insn),
-             * - original is an indirect CALL/JMP (opcodes 0xFF/2 or 0xFF/4)
-             *   using RIP-relative addressing.
-             * Some branch destinations may still be NULL when we come here
-             * the first time. Defer patching of those until the post-presmp-
-             * initcalls re-invocation (with force set to true). If at that
-             * point the branch destination is still NULL, insert "UD2; UD0"
-             * (for ease of recognition) instead of CALL/JMP.
-             */
-            if ( a->cpuid == X86_FEATURE_ALWAYS &&
-                 *(int32_t *)(buf + 1) == -5 &&
-                 a->orig_len >= 6 &&
-                 orig[0] == 0xff &&
-                 orig[1] == (*buf & 1 ? 0x25 : 0x15) )
+            /* 0xe8/0xe9 are relative branches; fix the offset. */
+            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
             {
-                long disp = *(int32_t *)(orig + 2);
-                const uint8_t *dest = *(void **)(orig + 6 + disp);
-
-                if ( dest )
+                /*
+                 * Detect the special case of indirect-to-direct branch patching:
+                 * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
+                 *   checked above),
+                 * - replacement's displacement is -5 (pointing back at the very
+                 *   insn, which makes no sense in a real replacement insn),
+                 * - original is an indirect CALL/JMP (opcodes 0xFF/2 or 0xFF/4)
+                 *   using RIP-relative addressing.
+                 * Some branch destinations may still be NULL when we come here
+                 * the first time. Defer patching of those until the post-presmp-
+                 * initcalls re-invocation (with force set to true). If at that
+                 * point the branch destination is still NULL, insert "UD2; UD0"
+                 * (for ease of recognition) instead of CALL/JMP.
+                 */
+                if ( a->cpuid == X86_FEATURE_ALWAYS &&
+                     *(int32_t *)(buf + 1) == -5 &&
+                     a->orig_len >= 6 &&
+                     orig[0] == 0xff &&
+                     orig[1] == (*buf & 1 ? 0x25 : 0x15) )
                 {
-                    /*
-                     * When building for CET-IBT, all function pointer targets
-                     * should have an endbr64 instruction.
-                     *
-                     * If this is not the case, leave a warning because
-                     * something is probably wrong with the build.  A CET-IBT
-                     * enabled system might have exploded already.
-                     *
-                     * Otherwise, skip the endbr64 instruction.  This is a
-                     * marginal perf improvement which saves on instruction
-                     * decode bandwidth.
-                     */
-                    if ( IS_ENABLED(CONFIG_XEN_IBT) )
+                    long disp = *(int32_t *)(orig + 2);
+                    const uint8_t *dest = *(void **)(orig + 6 + disp);
+
+                    if ( dest )
                     {
-                        if ( is_endbr64(dest) )
-                            dest += ENDBR64_LEN;
-                        else
-                            printk(XENLOG_WARNING
-                                   "altcall %ps dest %ps has no endbr64\n",
-                                   orig, dest);
+                        /*
+                         * When building for CET-IBT, all function pointer targets
+                         * should have an endbr64 instruction.
+                         *
+                         * If this is not the case, leave a warning because
+                         * something is probably wrong with the build.  A CET-IBT
+                         * enabled system might have exploded already.
+                         *
+                         * Otherwise, skip the endbr64 instruction.  This is a
+                         * marginal perf improvement which saves on instruction
+                         * decode bandwidth.
+                         */
+                        if ( IS_ENABLED(CONFIG_XEN_IBT) )
+                        {
+                            if ( is_endbr64(dest) )
+                                dest += ENDBR64_LEN;
+                            else
+                                printk(XENLOG_WARNING
+                                       "altcall %ps dest %ps has no endbr64\n",
+                                       orig, dest);
+                        }
+
+                        disp = dest - (orig + 5);
+                        ASSERT(disp == (int32_t)disp);
+                        *(int32_t *)(buf + 1) = disp;
                     }
-
-                    disp = dest - (orig + 5);
-                    ASSERT(disp == (int32_t)disp);
-                    *(int32_t *)(buf + 1) = disp;
-                }
-                else if ( force )
-                {
-                    buf[0] = 0x0f;
-                    buf[1] = 0x0b;
-                    buf[2] = 0x0f;
-                    buf[3] = 0xff;
-                    buf[4] = 0xff;
+                    else if ( force )
+                    {
+                        buf[0] = 0x0f;
+                        buf[1] = 0x0b;
+                        buf[2] = 0x0f;
+                        buf[3] = 0xff;
+                        buf[4] = 0xff;
+                    }
+                    else
+                        continue;
                 }
+                else if ( force && system_state < SYS_STATE_active )
+                    ASSERT_UNREACHABLE();
                 else
-                    continue;
+                    *(int32_t *)(buf + 1) += repl - orig;
             }
             else if ( force && system_state < SYS_STATE_active )
                 ASSERT_UNREACHABLE();
-            else
-                *(int32_t *)(buf + 1) += repl - orig;
         }
-        else if ( force && system_state < SYS_STATE_active  )
-            ASSERT_UNREACHABLE();
 
         a->priv = 1;
 
Signature · 1 line
2.39.5
#11 lore raw

PATCH v2 5/7 x86/alternative: Replace a continue with a goto

In reply to Andrew Cooper

A subsequent patch is going to insert a loop, which interferes with the continue in the devirtualisation logic.

Replace it with a goto, and a paragraph explaining why we intentionally avoid setting a->priv = 1.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
xen/arch/x86/alternative.c +10 -1
index 5ea7f51b007c..b745f112154a 100644
@@ -328,7 +328,15 @@ static int init_or_livepatch _apply_alternatives(struct alt_instr *start,
                         buf[4] = 0xff;
                     }
                     else
-                        continue;
+                    {
+                        /*
+                         * The function pointer we're wanting to devirtualise
+                         * is still NULL, and we're not sealing yet.  Leave
+                         * the alternative fully un-processed, in order to try
+                         * again next time around.
+                         */
+                        goto skip_this_alternative;
+                    }
                 }
                 else if ( force && system_state < SYS_STATE_active )
                     ASSERT_UNREACHABLE();
@@ -343,6 +351,7 @@ static int init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         add_nops(buf + a->repl_len, total_len - a->repl_len);
         text_poke(orig, buf, total_len);
+    skip_this_alternative:;
     }
 
     /*
Signature · 1 line
2.39.5
#12 lore raw

PATCH v2 6/7 x86/alternative: Relocate all insn-relative fields

In reply to Andrew Cooper

Right now, relocation of displacements is restricted to finding 0xe8/e9 as the first byte of the replacement, but this is overly restrictive.

Use x86_decode_lite() to find and adjust all insn-relative fields.

As with disp8's not leaving the replacemnet block, some disp32's don't either. e.g. the RSB stuffing loop. These stay unmodified.

For now, leave the altcall devirtualisation alone. These require more care to transform into the new scheme.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 46 +++++++++++++++++++++++++++++++-------
 1 file changed, 38 insertions(+), 8 deletions(-)
xen/arch/x86/alternative.c +38 -8
index b745f112154a..da1a4af56377 100644
@@ -264,10 +264,31 @@ static int init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
+        /* Walk buf[] and adjust any insn-relative operands. */
+        if ( a->repl_len )
         {
-            /* 0xe8/0xe9 are relative branches; fix the offset. */
-            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
+            uint8_t *ip = buf, *end = ip + a->repl_len;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
             {
+                int32_t *d32;
+                const uint8_t *target;
+
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len == 0 )
+                {
+                    printk("Alt for %ps [%*ph]\n"
+                           "  Unable to decode instruction at +%lu in alternative\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl, ip - repl);
+                    return -EINVAL;
+                }
+
+                if ( res.rel_sz != 4 )
+                    continue;
+
+                d32 = res.rel;
+
                 /*
                  * Detect the special case of indirect-to-direct branch patching:
                  * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
@@ -337,14 +358,23 @@ static int init_or_livepatch _apply_alternatives(struct alt_instr *start,
                          */
                         goto skip_this_alternative;
                     }
+
+                    continue;
+                }
+
+                target = ip + res.len + *d32;
+
+                if ( target >= buf && target <= end )
+                {
+                    /*
+                     * Target doesn't leave the replacement block.  e.g. RSB
+                     * stuffing.  Leave it unmodified.
+                     */
+                    continue;
                 }
-                else if ( force && system_state < SYS_STATE_active )
-                    ASSERT_UNREACHABLE();
-                else
-                    *(int32_t *)(buf + 1) += repl - orig;
+
+                *d32 += repl - orig;
             }
-            else if ( force && system_state < SYS_STATE_active )
-                ASSERT_UNREACHABLE();
         }
 
         a->priv = 1;
Signature · 1 line
2.39.5
Reviewed-by on v2 6/7
#13 lore raw

Re: [PATCH v2 6/7] x86/alternative: Relocate all insn-relative fields

Quoted 5 lines · Andrew Cooper

Right now, relocation of displacements is restricted to finding 0xe8/e9 as the first byte of the replacement, but this is overly restrictive.

Use x86_decode_lite() to find and adjust all insn-relative fields.

Quoted 7 lines

As with disp8's not leaving the replacemnet block, some disp32's don't either. e.g. the RSB stuffing loop. These stay unmodified.

For now, leave the altcall devirtualisation alone. These require more care to transform into the new scheme.

#14 lore raw

PATCH v2 7/7 x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

In reply to Andrew Cooper

Now that alternatives can fix up call displacements even when they're not the first instruction of the replacement, move the SCF_entry_bhb conditional inside the replacement block.

This removes a conditional branch from the fastpaths of BHI-unaffected hardware.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/hvm/vmx/entry.S             | 12 +++----
 xen/arch/x86/include/asm/spec_ctrl_asm.h | 43 +++++++++++++-----------
 2 files changed, 30 insertions(+), 25 deletions(-)
xen/arch/x86/hvm/vmx/entry.S +6 -6
index 6aaeb28a5b96..e901a41f252a 100644
@@ -62,12 +62,12 @@ FUNC(vmx_asm_vmexit_handler)
          * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs
          * itself so must be after we've perfomed all the RET-safety we can.
          */
-        testb $SCF_entry_bhb, CPUINFO_scf(%rsp)
-        jz .L_skip_bhb
-        ALTERNATIVE_2 "",                                    \
-            "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-            "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L_skip_bhb:
+        .macro VMX_BHB_SEQ fn:req
+            DO_COND_BHB_SEQ \fn scf=CPUINFO_scf(%rsp)
+        .endm
+        ALTERNATIVE_2 "",                                         \
+            "VMX_BHB_SEQ fn=clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+            "VMX_BHB_SEQ fn=clear_bhb_tsx",   X86_SPEC_BHB_TSX
 
         ALTERNATIVE "lfence", "", X86_SPEC_NO_LFENCE_ENTRY_VMX
         /* WARNING! `ret`, `call *`, `jmp *` not safe before this point. */
xen/arch/x86/include/asm/spec_ctrl_asm.h +24 -19

67 lines not on this page · raw message

Signature · 1 line
2.39.5
Reviewed-by on v2 7/7
#15 lore raw

Re: [PATCH v2 7/7] x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

Quoted 8 lines · Andrew Cooper

Now that alternatives can fix up call displacements even when they're not the first instruction of the replacement, move the SCF_entry_bhb conditional inside the replacement block.

This removes a conditional branch from the fastpaths of BHI-unaffected hardware.

Reviewed-by on the v2 series
#16 lore raw
In reply to Andrew Cooper
Quoted 32 lines · Andrew Cooper

Alternatives have had a reasonably severe restriction since their introduction. This has been the source of several bugs, and several inefficiencies particularly in the speculative safety paths.

v2:
Most work is in patch 1 and the new patch 2 (userspace harness). Other patches with minor or no change.

Andrew Cooper (7):
x86: Introduce x86_decode_lite()
tests/x86: Introduce a userspace test harness for x86_decode_lite() x86/alternative: Walk all replacements during self tests x86/alternative: Indent the relocation logic x86/alternative: Replace a continue with a goto x86/alternative: Relocate all insn-relative fields x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

 tools/tests/Makefile                      |   1 +
 tools/tests/x86-decode-lite/.gitignore    |   1 +
 tools/tests/x86-decode-lite/Makefile      |  45 ++
 tools/tests/x86-decode-lite/insns.S       | 703 ++++++++++++++++++++++
 tools/tests/x86-decode-lite/macro-magic.h |  52 ++
 tools/tests/x86-decode-lite/main.c        | 111 ++++
 tools/tests/x86-decode-lite/x86-emulate.h |  27 +
 xen/arch/x86/alternative.c                | 213 +++++--
 xen/arch/x86/hvm/vmx/entry.S              |  12 +-
 xen/arch/x86/include/asm/spec_ctrl_asm.h  |  43 +-
 xen/arch/x86/x86_emulate/Makefile         |   6 +
 xen/arch/x86/x86_emulate/decode-lite.c    | 311 ++++++++++
 xen/arch/x86/x86_emulate/private.h        |   2 +
 xen/arch/x86/x86_emulate/x86_emulate.h    |  14 +
Quoted 9 lines
 14 files changed, 1456 insertions(+), 85 deletions(-)
 create mode 100644 tools/tests/x86-decode-lite/.gitignore
 create mode 100644 tools/tests/x86-decode-lite/Makefile
 create mode 100644 tools/tests/x86-decode-lite/insns.S
 create mode 100644 tools/tests/x86-decode-lite/macro-magic.h
 create mode 100644 tools/tests/x86-decode-lite/main.c
 create mode 100644 tools/tests/x86-decode-lite/x86-emulate.h
 create mode 100644 xen/arch/x86/x86_emulate/decode-lite.c

For patches 1 to 6

Frediano