Skip to contentSkip to conversation

x86/alternatives: Adjust all insn-relative fields

PATCH Superseded Andrew Cooper 2 participants 16 messages Aug 3 – Aug 18

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 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.

https://gitlab.com/xen-project/hardware/xen-staging/-/pipelines/2724019865

v3:
* Run through Gitlab CI.
* Fix up Eclair issues, Clang issues, and older-binutils issues.

Andrew Cooper (5):
x86/emul: 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: 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      |  56 ++
 tools/tests/x86-decode-lite/insns.S       | 703 ++++++++++++++++++++++
 tools/tests/x86-decode-lite/macro-magic.h |  62 ++
 tools/tests/x86-decode-lite/main.c        | 111 ++++
 tools/tests/x86-decode-lite/x86-emulate.h |  27 +
 xen/arch/x86/alternative.c                | 102 +++-
 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    | 330 ++++++++++
 xen/arch/x86/x86_emulate/x86_emulate.h    |  14 +
 13 files changed, 1434 insertions(+), 34 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 v3 1/5 x86/emul: 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 unrecognised, as finding them in an alternative is more likely to be a bug than intentional. Some instruction groups and prefixes are unimplemented to reduce decode complexity.

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

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

v3:
* Rearrange decode tables to satisfy comment requests without splitting
* Recognise UDB now it's used by Xen
* Fix MISRA violations
* Misc other changes

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 | 330 +++++++++++++++++++++++++
 xen/arch/x86/x86_emulate/x86_emulate.h |  14 ++
 3 files changed, 350 insertions(+)
 create mode 100644 xen/arch/x86/x86_emulate/decode-lite.c
xen/arch/x86/x86_emulate/Makefile +6 -0
index 295e602f6b86..679bddbb1584 100644
@@ -17,3 +17,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 +330 -0

330 lines not on this page · raw message

xen/arch/x86/x86_emulate/x86_emulate.h +14 -0
index 0fd20747dc43..566a8297d8a5 100644
@@ -835,4 +835,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 v3 1/5] x86/emul: Introduce x86_decode_lite()

Quoted 6 lines · Andrew Cooper
xen/arch/x86/x86_emulate/decode-lite.c new file +0 -0
new file mode 100644
index 000000000000..131cc07d5516

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

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

GCC 12 does transform this into sub $0xb8; cmp $7.

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

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+
+        switch ( osize )
+        {
+        case 1: FETCH(uint8_t);  break;
+        case 2: FETCH(uint16_t); break;
+        case 4: FETCH(uint32_t); break;
+        case 8: FETCH(uint64_t); break;
+        default: goto bad_osize;
+        }

On further consideration:

        switch ( osize )
        {
        case 1:
        case 2:
        case 4:
        case 8:
            if ( ip + osize > end )
                goto overrun;
            ip += osize;
            break;

        default: goto bad_osize;
        }

drops nearly 10% of the function:

    add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-91 (-91) Function                                     old     new   delta x86_decode_lite                              972     881     -91

GCC clearly can't reason about the relationship between osize and sizeof(type), and needs the help.

I also tried the further simplification:

        if ( osize > 8 || (osize & (osize - 1)) != 0 ) goto bad_osize;
        if ( ip + osize > end )
            goto overrun;

        ip += osize;

but interestingly this delta grows the function by 30 bytes.  It only seems to add the block checking osize, meaning that GCC managed to optimise away all of the switch dispatch previously.  In hindsight this is probably quite easy; because we're 64bit only, osize only ever has constant values that GCC can see.

Anyway, I've folded in the first optimisation.

~Andrew

#3 lore raw

Re: [PATCH v3 1/5] x86/emul: Introduce x86_decode_lite()

In reply to Andrew Cooper
Quoted 23 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +20 -0
@@ -0,0 +1,330 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#ifdef __XEN__
+# include <xen/init.h>
+# include <xen/livepatch.h>
+#endif
+
+#include "private.h"
+
+#undef ModRM
+
+/*
+ * 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 direct branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+ *  - All code is 64bit, the instruction stream is well formed and safe to
+ *    read.
+ *  - Instruction groups and prefixes not used by Xen's current alternatives
+ *    are not implemented in order to reduce the decode complexity.
+ *  - Certain instructions are intentionally not recognised, when it is more
+ *    likely for their presence to be an error than intentional.
+ *
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.

Why do you mention replacement blocks here? Are we entirely set on this code not possibly gaining any purpose beyond the scanning of those?

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

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+ * 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)

Is there a reason the parameters can't be pointer-to-const? Hmm, apparently for x86_decode_lite_t's "rel" field not be plaing void *, "ip" needs to be this way as well. But not "end", I don't think.

Quoted 32 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +32 -0
+{
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Moffs  (1 << 2)
+#define Branch (1 << 5) /* Near direct branches, which have a displacement */
+#define ModRM  (1 << 6)
+#define Known  (1 << 7)
+
+    static const uint8_t init_or_livepatch_const onebyte[256] = {
+
+#define ALU_OPS(x)                              \
+        [(x) + 0] = (Known|ModRM),              \
+        [(x) + 1] = (Known|ModRM),              \
+        [(x) + 2] = (Known|ModRM),              \
+        [(x) + 3] = (Known|ModRM),              \
+        [(x) + 4] = (Known|Imm8),               \
+        [(x) + 5] = (Known|Imm)
+
+        ALU_OPS(0x00) /* ADD */, ALU_OPS(0x08) /* OR  */,
+        ALU_OPS(0x10) /* ADC */, ALU_OPS(0x18) /* SBB */,
+        ALU_OPS(0x20) /* AND */, ALU_OPS(0x28) /* SUB */,
+        ALU_OPS(0x30) /* XOR */, ALU_OPS(0x38) /* CMP */,
+
+#undef ALU_OPS
+
+        [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+        [0x62]          = 0,                   /* BOUND, but also EVEX prefix, not implemented. */
+        [0x63]          = (Known|ModRM),       /* MOVSxd */
+
+        [0x68]          = (Known|Imm),         /* PUSH $imm */
+        [0x69]          = (Known|ModRM|Imm),   /* IMUL $imm */

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [0x6a]          = (Known|Imm8),        /* PUSH $imm8 */
+        [0x6b]          = (Known|ModRM|Imm8),  /* PUSH $imm8 */
+        [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 */
+        [0x8f]          = 0,                   /* Grp1A - POP but also XOP prefix, not implemented. */

POP doesn't look all that unlikely to be used in inline assembly, and hence in alternatives. That said, of course using it with a memory operand requires quite a bit of care. I don't see you excluding the PUSH counterpart, though - being consistent for any such pairs would seem somewhat desirable.

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+        [0x90 ... 0x99] = (Known),             /* NOP/XCHG %rAX/CLTQ/CQTO */
+
+        [0x9b ... 0x9f] = (Known),             /* FWAIT/PUSHF/POPF/SAHF/LAHF */
+        [0xa0 ... 0xa3] = (Known|Moffs),       /* MOVABS */

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [0xa4 ... 0xa7] = (Known),             /* MOVS/CMPS */
+        [0xa8]          = (Known|Imm8),        /* TEST %al */
+        [0xa9]          = (Known|Imm),         /* TEST %rAX */
+        [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 */
+        [0xc4 ... 0xc5] = 0,                   /* LES/LDS but also VEX prefixes, not implemented. */

This may bite us sooner or later, due to the VEX-encoded integer insns that there are. Of course as long as we don't use this function on compiled code, and as long as my "x86: allow Kconfig control over psABI level" doesn't come close to going in, that's merely a theoretical concern.

Same goes for not supporting the 3-byte opcodes, which also encode certain integer insns.

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

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -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 */
+
+        [0xd0 ... 0xd3] = (Known|ModRM),       /* Grp2 (ROL..SAR {$1,%cl}, %reg) */
+
+        [0xd6]          = (Known),             /* UDB */

I guess you consider XLAT, LOOP*, and J*CXZ as too odd to use in alternatives? Decoding-wise they're rather easy to implement.

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+        [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 */
+

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [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 */

Leaving out INVD is surely find, but WBINVD?

Quoted 17 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +17 -0
+        [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 */
+        [0xa4]          = (Known|ModRM|Imm8),  /* SHLD $imm8 */
+        [0xa5]          = (Known|ModRM),       /* SHLD %cl */
+

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [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/UD1 */
+        [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+        [0xbb ... 0xbf] = (Known|ModRM),       /* BTC/BSF/BSR/MOVSX */
+        [0xc0 ... 0xc1] = (Known|ModRM),       /* XADD */

What about MOVNTI?

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

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

What about UD0?

Quoted 73 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +73 -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) )
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */
+        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 */
+
+        case 0x40 ... 0x4f: /* REX */
+            rex = b;
+            continue;
+
+        default:
+            goto prefixes_done;
+        }
+        rex = 0; /* REX cancelled by subsequent legacy prefix. */
+    }
+ prefixes_done:
+
+    if ( rex & REX_W )
+        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);

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        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(int32_t);

FETCH() here but ...

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

Quoted 8 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +8 -0
+        }
+        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;

... goto here?

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

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+        }
+
+        if ( mod == 1 ) /* disp8 */
+            FETCH(int8_t);
+        else if ( mod == 2 ) /* disp32 */
+        {
+        disp32:
+            FETCH(int32_t);
+        }

In several cases the FETCH()ed value isn't used. Compilers as well as Eclair (and alike) are happy with that? And compilers also manage to eliminate the memory accesses then?

Quoted 5 lines
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
@@ -835,4 +835,18 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};
 }

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 846

Quoted 10 lines
xen/arch/x86/x86_emulate/x86_emulate.h +9 -0
 
+/*
+ * 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 */

Perhaps use bitfields in favor of fixed-width integers, seeing what ./CODING_STYLE says?

Jan

#4 lore raw

Re: [PATCH v3 1/5] x86/emul: Introduce x86_decode_lite()

Quoted 109 lines · Jan Beulich
Quoted 23 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +20 -0
@@ -0,0 +1,330 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#ifdef __XEN__
+# include <xen/init.h>
+# include <xen/livepatch.h>
+#endif
+
+#include "private.h"
+
+#undef ModRM
+
+/*
+ * 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 direct branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+ *  - All code is 64bit, the instruction stream is well formed and safe to
+ *    read.
+ *  - Instruction groups and prefixes not used by Xen's current alternatives
+ *    are not implemented in order to reduce the decode complexity.
+ *  - Certain instructions are intentionally not recognised, when it is more
+ *    likely for their presence to be an error than intentional.
+ *
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.

Why do you mention replacement blocks here? Are we entirely set on this code not possibly gaining any purpose beyond the scanning of those?

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

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+ * 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)

Is there a reason the parameters can't be pointer-to-const? Hmm, apparently for x86_decode_lite_t's "rel" field not be plaing void *, "ip" needs to be this way as well. But not "end", I don't think.

Quoted 32 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +32 -0
+{
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Moffs  (1 << 2)
+#define Branch (1 << 5) /* Near direct branches, which have a displacement */
+#define ModRM  (1 << 6)
+#define Known  (1 << 7)
+
+    static const uint8_t init_or_livepatch_const onebyte[256] = {
+
+#define ALU_OPS(x)                              \
+        [(x) + 0] = (Known|ModRM),              \
+        [(x) + 1] = (Known|ModRM),              \
+        [(x) + 2] = (Known|ModRM),              \
+        [(x) + 3] = (Known|ModRM),              \
+        [(x) + 4] = (Known|Imm8),               \
+        [(x) + 5] = (Known|Imm)
+
+        ALU_OPS(0x00) /* ADD */, ALU_OPS(0x08) /* OR  */,
+        ALU_OPS(0x10) /* ADC */, ALU_OPS(0x18) /* SBB */,
+        ALU_OPS(0x20) /* AND */, ALU_OPS(0x28) /* SUB */,
+        ALU_OPS(0x30) /* XOR */, ALU_OPS(0x38) /* CMP */,
+
+#undef ALU_OPS
+
+        [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+        [0x62]          = 0,                   /* BOUND, but also EVEX prefix, not implemented. */
+        [0x63]          = (Known|ModRM),       /* MOVSxd */
+
+        [0x68]          = (Known|Imm),         /* PUSH $imm */
+        [0x69]          = (Known|ModRM|Imm),   /* IMUL $imm */

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [0x6a]          = (Known|Imm8),        /* PUSH $imm8 */
+        [0x6b]          = (Known|ModRM|Imm8),  /* PUSH $imm8 */
+        [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 */
+        [0x8f]          = 0,                   /* Grp1A - POP but also XOP prefix, not implemented. */

POP doesn't look all that unlikely to be used in inline assembly, and hence in alternatives. That said, of course using it with a memory operand requires quite a bit of care. I don't see you excluding the PUSH counterpart, though - being consistent for any such pairs would seem somewhat desirable.

Quoted 12 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +12 -0
+        [0x90 ... 0x99] = (Known),             /* NOP/XCHG %rAX/CLTQ/CQTO */
+
+        [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 %rAX */
+        [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) */
+
Quoted 8 lines

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

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+        [0xc3]          = (Known),             /* RET */
+        [0xc4 ... 0xc5] = 0,                   /* LES/LDS but also VEX prefixes, not implemented. */

This may bite us sooner or later, due to the VEX-encoded integer insns that there are. Of course as long as we don't use this function on compiled code, and as long as my "x86: allow Kconfig control over psABI level" doesn't come close to going in, that's merely a theoretical concern.

Actually perhaps sooner - we're meaning to use MSR-IMM insns after all, if I'm not mistaken.

Jan

#5 lore raw

Re: [PATCH v3 1/5] x86/emul: Introduce x86_decode_lite()

In reply to Jan Beulich
Quoted 27 lines · Jan Beulich
Quoted 27 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +24 -0
@@ -0,0 +1,330 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#ifdef __XEN__
+# include <xen/init.h>
+# include <xen/livepatch.h>
+#endif
+
+#include "private.h"
+
+#undef ModRM
+
+/*
+ * 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 direct branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:
+ *  - All code is 64bit, the instruction stream is well formed and safe to
+ *    read.
+ *  - Instruction groups and prefixes not used by Xen's current alternatives
+ *    are not implemented in order to reduce the decode complexity.
Quoted 8 lines

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

Quoted 6 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +6 -0
+ *  - Certain instructions are intentionally not recognised, when it is more
+ *    likely for their presence to be an error than intentional.
+ *
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.

Why do you mention replacement blocks here? Are we entirely set on this code not possibly gaining any purpose beyond the scanning of those?

It's just the end of the instruction stream wanting decoding.  I'll adjust the comment.

Quoted 37 lines
Quoted 37 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +37 -0
+{
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Moffs  (1 << 2)
+#define Branch (1 << 5) /* Near direct branches, which have a displacement */
+#define ModRM  (1 << 6)
+#define Known  (1 << 7)
+
+    static const uint8_t init_or_livepatch_const onebyte[256] = {
+
+#define ALU_OPS(x)                              \
+        [(x) + 0] = (Known|ModRM),              \
+        [(x) + 1] = (Known|ModRM),              \
+        [(x) + 2] = (Known|ModRM),              \
+        [(x) + 3] = (Known|ModRM),              \
+        [(x) + 4] = (Known|Imm8),               \
+        [(x) + 5] = (Known|Imm)
+
+        ALU_OPS(0x00) /* ADD */, ALU_OPS(0x08) /* OR  */,
+        ALU_OPS(0x10) /* ADC */, ALU_OPS(0x18) /* SBB */,
+        ALU_OPS(0x20) /* AND */, ALU_OPS(0x28) /* SUB */,
+        ALU_OPS(0x30) /* XOR */, ALU_OPS(0x38) /* CMP */,
+
+#undef ALU_OPS
+
+        [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+        [0x62]          = 0,                   /* BOUND, but also EVEX prefix, not implemented. */
+        [0x63]          = (Known|ModRM),       /* MOVSxd */
+
+        [0x68]          = (Known|Imm),         /* PUSH $imm */
+        [0x69]          = (Known|ModRM|Imm),   /* IMUL $imm */
+        [0x6a]          = (Known|Imm8),        /* PUSH $imm8 */
+        [0x6b]          = (Known|ModRM|Imm8),  /* PUSH $imm8 */
+        [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 79

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+        [0x81]          = (Known|ModRM|Imm),   /* Grp1 */
+
+        [0x83]          = (Known|ModRM|Imm8),  /* Grp1 */
+        [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA */
+        [0x8f]          = 0,                   /* Grp1A - POP but also XOP prefix, not implemented. */

POP doesn't look all that unlikely to be used in inline assembly, and hence in alternatives. That said, of course using it with a memory operand requires quite a bit of care.

We have no alternatives playing with the stack (beyond CALL instructions), and no alternatives which have any net %rsp delta.

PUSH/POP MEM are rare in general and Xen doesn't have any at all.

Quoted 3 lines

I don't see you excluding the
PUSH counterpart, though - being consistent for any such pairs would seem somewhat desirable.

It would be nice to be handled symmetrically, but this *is* an odd-instruction-out in the x86 encoding space.

It ought to live in Grp5 where the encoding would be 0xff /7 (and beside it's matching PUSH), except that's that's a rather important binary pattern and wants to not be considered a valid instruction.

The fact that the group is split like this shows that the mistake was a late discovery in the development of the 8086, where it was easier to move the one opcode than the whole group.  (It's likely to have been a metal-layer fix for the decode PAL, rather than adjusting the transistors, which is typically an order of magnitude cheaper fix.)

Quoted 21 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+        [0x90 ... 0x99] = (Known),             /* NOP/XCHG %rAX/CLTQ/CQTO */
+
+        [0x9b ... 0x9f] = (Known),             /* FWAIT/PUSHF/POPF/SAHF/LAHF */
+        [0xa0 ... 0xa3] = (Known|Moffs),       /* MOVABS */

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [0xa4 ... 0xa7] = (Known),             /* MOVS/CMPS */
+        [0xa8]          = (Known|Imm8),        /* TEST %al */
+        [0xa9]          = (Known|Imm),         /* TEST %rAX */
+        [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 */
+        [0xc4 ... 0xc5] = 0,                   /* LES/LDS but also VEX prefixes, not implemented. */

This may bite us sooner or later, due to the VEX-encoded integer insns that there are. Of course as long as we don't use this function on compiled code, and as long as my "x86: allow Kconfig control over psABI level" doesn't come close to going in, that's merely a theoretical concern.

Quoted 2 lines

Same goes for not supporting the 3-byte opcodes, which also encode certain integer insns.

I have no doubt that we're going to need to add support eventually.

But,
a) I don't have time right now
b) We have real bugs/limitations right now needing this functionality to address (patch 5, and the xsave fixes, and bus lock trap enablement)
c) GitlabCI will reliably notice any new alternative instructions that this can't decode (patch 3)
d) This function is a fastpath during the alternatives patching critical region (patch 4)

Option d alone is a good reason not to decode VEX prefixes yet.

Quoted 12 lines

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -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 */
+
+        [0xd0 ... 0xd3] = (Known|ModRM),       /* Grp2 (ROL..SAR {$1,%cl}, %reg) */
+
+        [0xd6]          = (Known),             /* UDB */

I guess you consider XLAT, LOOP*, and J*CXZ as too odd to use in alternatives? Decoding-wise they're rather easy to implement.

They are easy, but they also shouldn't appear anywhere in Xen.

I know we've got one J*CXZ in the emulator.  I tried quite hard to find an alternative before deciding it was an acceptable solution given the constraints, but it's in plain code.

Quoted 10 lines
Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+        [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 */
Quoted 8 lines

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

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        [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 */

Leaving out INVD is surely find, but WBINVD?

Given now expensive WBINVD is, what possible reason can you think for having it in an alternative ?

Quoted 21 lines
Quoted 21 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +20 -0
+        [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 */
+        [0xa4]          = (Known|ModRM|Imm8),  /* SHLD $imm8 */
+        [0xa5]          = (Known|ModRM),       /* SHLD %cl */
+
+        [0xa8 ... 0xa9] = (Known),             /* PUSH/POP %gs */
+
+        [0xab]          = (Known|ModRM),       /* BTS */
Quoted 8 lines

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

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        [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/UD1 */
+        [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+        [0xbb ... 0xbf] = (Known|ModRM),       /* BTC/BSF/BSR/MOVSX */
+        [0xc0 ... 0xc1] = (Known|ModRM),       /* XADD */

What about MOVNTI?

I judged that to be on the unlikely side to be needed.

Quoted 5 lines

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

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

What about UD0?

UD0 differs between vendors and product lines from Intel.

Quoted 94 lines
Quoted 74 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +73 -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) )
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */
+        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 */
+
+        case 0x40 ... 0x4f: /* REX */
+            rex = b;
+            continue;
+
+        default:
+            goto prefixes_done;
+        }
+        rex = 0; /* REX cancelled by subsequent legacy prefix. */
+    }
+ prefixes_done:
+
+    if ( rex & REX_W )
+        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);

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        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(int32_t);

FETCH() here but ...

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

Quoted 8 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +8 -0
+        }
+        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;
Quoted 1 line

... goto here?

Hmm.  That's an artefact of how it developed.  Swapping this goto for FETCH() does drop 20 bytes, but the function is rearranged so much that it's hard to tell if this is because real logic is getting dropped.

Quoted 10 lines

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+        }
+
+        if ( mod == 1 ) /* disp8 */
+            FETCH(int8_t);
+        else if ( mod == 2 ) /* disp32 */
+        {
+        disp32:
+            FETCH(int32_t);
+        }
Quoted 2 lines

In several cases the FETCH()ed value isn't used. Compilers as well as Eclair (and alike) are happy with that?

Yes.  The cover letter has a fully passing pipeline.

Quoted 1 line

And compilers also manage to eliminate the memory accesses then?

Yes.

Quoted 7 lines
Quoted 7 lines
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
@@ -835,4 +835,18 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};
 }
 
Quoted 11 lines

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 846

Quoted 9 lines
xen/arch/x86/x86_emulate/x86_emulate.h +9 -0
+/*
+ * 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 */

Perhaps use bitfields in favor of fixed-width integers, seeing what ./CODING_STYLE says?

No.  That destroys the code generation improvements gained by returning a pair like this in the first place.

~Andrew

#6 lore raw

Re: [PATCH v3 1/5] x86/emul: Introduce x86_decode_lite()

Quoted 22 lines · Andrew Cooper
Quoted 12 lines · Jan Beulich
Quoted 12 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +12 -0
+        [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+        [0x62]          = 0,                   /* BOUND, but also EVEX prefix, not implemented. */
+        [0x63]          = (Known|ModRM),       /* MOVSxd */
+
+        [0x68]          = (Known|Imm),         /* PUSH $imm */
+        [0x69]          = (Known|ModRM|Imm),   /* IMUL $imm */
+        [0x6a]          = (Known|Imm8),        /* PUSH $imm8 */
+        [0x6b]          = (Known|ModRM|Imm8),  /* PUSH $imm8 */
+        [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 79

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+        [0x81]          = (Known|ModRM|Imm),   /* Grp1 */
+
+        [0x83]          = (Known|ModRM|Imm8),  /* Grp1 */
+        [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA */
+        [0x8f]          = 0,                   /* Grp1A - POP but also XOP prefix, not implemented. */

POP doesn't look all that unlikely to be used in inline assembly, and hence in alternatives. That said, of course using it with a memory operand requires quite a bit of care.

Quoted 4 lines

We have no alternatives playing with the stack (beyond CALL instructions), and no alternatives which have any net %rsp delta.

PUSH/POP MEM are rare in general and Xen doesn't have any at all.

Well, okay then. Nevertheless I'd like to mention that the encoding can also be used for REG forms. If needed for size reasons, that may or may not be more efficient than adding a NOP or no-op prefix.

Quoted 34 lines
Quoted 20 lines
Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+        [0x90 ... 0x99] = (Known),             /* NOP/XCHG %rAX/CLTQ/CQTO */
+
+        [0x9b ... 0x9f] = (Known),             /* FWAIT/PUSHF/POPF/SAHF/LAHF */
+        [0xa0 ... 0xa3] = (Known|Moffs),       /* MOVABS */

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

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        [0xa4 ... 0xa7] = (Known),             /* MOVS/CMPS */
+        [0xa8]          = (Known|Imm8),        /* TEST %al */
+        [0xa9]          = (Known|Imm),         /* TEST %rAX */
+        [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 */
+        [0xc4 ... 0xc5] = 0,                   /* LES/LDS but also VEX prefixes, not implemented. */

This may bite us sooner or later, due to the VEX-encoded integer insns that there are. Of course as long as we don't use this function on compiled code, and as long as my "x86: allow Kconfig control over psABI level" doesn't come close to going in, that's merely a theoretical concern.

Quoted 2 lines

Same goes for not supporting the 3-byte opcodes, which also encode certain integer insns.

I have no doubt that we're going to need to add support eventually.

But,
a) I don't have time right now
b) We have real bugs/limitations right now needing this functionality to address (patch 5, and the xsave fixes, and bus lock trap enablement)
c) GitlabCI will reliably notice any new alternative instructions that this can't decode (patch 3)
d) This function is a fastpath during the alternatives patching critical region (patch 4)

Quoted 1 line

Option d alone is a good reason not to decode VEX prefixes yet.

Personally I think a is most relevant. As said in the later reply, once we start using MSR-IMM insns, at least VEX3 map 7 will need decoding anyway.

Quoted 18 lines
Quoted 9 lines
Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+        [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 */
Quoted 8 lines

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

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        [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 */

Leaving out INVD is surely find, but WBINVD?

Quoted 2 lines

Given now expensive WBINVD is, what possible reason can you think for having it in an alternative ?

It's more like e.g. WBNOINVD, which could appear in an alternative in principle, if its encoding didn't mean WBINVD anyway on older hardware.

Quoted 29 lines
Quoted 20 lines
Quoted 20 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +20 -0
+        [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 */
+        [0xa4]          = (Known|ModRM|Imm8),  /* SHLD $imm8 */
+        [0xa5]          = (Known|ModRM),       /* SHLD %cl */
+
+        [0xa8 ... 0xa9] = (Known),             /* PUSH/POP %gs */
+
+        [0xab]          = (Known|ModRM),       /* BTS */
Quoted 8 lines

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

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        [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/UD1 */
+        [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+        [0xbb ... 0xbf] = (Known|ModRM),       /* BTC/BSF/BSR/MOVSX */
+        [0xc0 ... 0xc1] = (Known|ModRM),       /* XADD */

What about MOVNTI?

Quoted 1 line

I judged that to be on the unlikely side to be needed.

Hmm, I'm not going to insist, but I think we'd better have it right away.

Quoted 6 lines
Quoted 4 lines

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

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

What about UD0?

UD0 differs between vendors and product lines from Intel.

Would you mind leaving a commented (to this effect) 0 entry?

Quoted 11 lines
Quoted 9 lines

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

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+        if ( mod == 1 ) /* disp8 */
+            FETCH(int8_t);
+        else if ( mod == 2 ) /* disp32 */
+        {
+        disp32:
+            FETCH(int32_t);
+        }

In several cases the FETCH()ed value isn't used. Compilers as well as Eclair (and alike) are happy with that?

Yes.  The cover letter has a fully passing pipeline.

Which you know as well as I do, says next to nothing, as we don't even come close to covering the complete version range. That said, it's likely good enough. I'm merely surprised no tool has to say anything about these unused "return" values of the macro.

Quoted 18 lines
Quoted 6 lines
Quoted 6 lines
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
@@ -835,4 +835,18 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};
 }
 
Quoted 11 lines

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 846

Quoted 9 lines
xen/arch/x86/x86_emulate/x86_emulate.h +9 -0
+/*
+ * 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 */

Perhaps use bitfields in favor of fixed-width integers, seeing what ./CODING_STYLE says?

Quoted 2 lines

No.  That destroys the code generation improvements gained by returning a pair like this in the first place.

I was under the pretty clear impression that halfway recent compilers treat 8-bit bitfields the same as uint8_t ordinary fields. (And no, I did by no means suggest to shrink the width of the fields.)

Jan

#7 lore raw

PATCH v3 2/5 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", and 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.

Clang IAS doesn't like the convience macro, and Binutils of around 2.30 don't like sysexitl or movsxd with a 32bit operand. As it's only Ubuntu 18.04 affected by this, skip building the harness in old environments.

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

v3:
* Force disable Clang IAS. It doesn't like the _ macro.
* Support 32bit builds

v2:
* New

---
 tools/tests/Makefile                      |   1 +
 tools/tests/x86-decode-lite/.gitignore    |   1 +
 tools/tests/x86-decode-lite/Makefile      |  56 ++
 tools/tests/x86-decode-lite/insns.S       | 703 ++++++++++++++++++++++
 tools/tests/x86-decode-lite/macro-magic.h |  62 ++
 tools/tests/x86-decode-lite/main.c        | 111 ++++
 tools/tests/x86-decode-lite/x86-emulate.h |  27 +
 7 files changed, 961 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 fc0ed8091510..ca4f0c707638 100644
@@ -14,6 +14,7 @@ SUBDIRS-y += xenstore
 
 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 +56 -0

56 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 +62 -0

62 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
#8 lore raw

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

Quoted 66 lines · Andrew Cooper
tools/tests/x86-decode-lite/insns.S new file +63 -0
@@ -0,0 +1,703 @@
+#include "macro-magic.h"
+
+        .code64
+
+        .allow_index_reg
+
+        .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 */
+        _ 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)
+
+        /* 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)

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+
+        /* 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

Perhaps also include %bpl, %sil, and %dil?

Quoted 6 lines
tools/tests/x86-decode-lite/insns.S new file +6 -0
+onebyte_row_9x:
+        _ nop
+        _ pause
+        _ xchg %ax, %ax
+        _ xchg %eax, %eax
+        _ xchg %rax, %rax

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ rex.w xchg %rax, %rax
+        _ cltq
+        _ cqto
+        _ wait
+        _ pushf
+        _ popf
+        _ sahf
+        _ lahf
+
+onebyte_row_ax:

May I suggest onebyte_row_Ax?

Quoted 30 lines
tools/tests/x86-decode-lite/insns.S new file +30 -0
+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

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ 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)

What's the idea behind the separate REX.W testing? It almost suggests that tests with an operand size prefix also may want adding. Except that's difficult, because of ...

Quoted 32 lines
tools/tests/x86-decode-lite/insns.S new file +32 -0
+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

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ 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

... vendor differences here. Perhaps the decoder itself would better reject handling of operand-size-prefixed branches.

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+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

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ 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

Oh, you even cover the case here. For XBEGIN, however, this can only be pure guesswork as to AMD behavior, I suppose.

I also don't see how you force which form you want.

Quoted 42 lines
tools/tests/x86-decode-lite/main.c new file +39 -0
@@ -0,0 +1,111 @@
+/*
+ * Userspace test harness for x86_decode_lite().
+ */
+#include <stdio.h>
+
+#include "x86-emulate.h"
+
+static unsigned int nr_failures;
+#define fail(t, fmt, ...)                                       \
+({                                                              \
+    const unsigned char *insn = (t)->ip;                        \
+                                                                \
+    nr_failures++;                                              \
+                                                                \
+    (void)printf("  Fail '%s' [%02x", (t)->name, *insn);        \
+    for ( unsigned int i = 1; i < (t)->len; i++ )               \
+        printf(" %02x", insn[i]);                               \
+    printf("]\n");                                              \
+                                                                \
+    (void)printf(fmt, ##__VA_ARGS__);                           \
+})
+
+struct test {
+    const char *name;
+    void *ip;
+    unsigned long len;
+};
+
+extern const struct test
+/* Defined in insns.S, ends with sentinel */
+    tests_rel0[], /* No relocatable entry */
+    tests_rel1[], /* disp8 */
+    tests_rel4[], /* disp32 or RIP-relative */
+    tests_unsup[]; /* Unsupported instructions */
+
+static inline void run_tests(const struct test *tests, unsigned int rel_sz)
+{
+    printf("Test rel%u\n", rel_sz);
+

tools/tests/x86-decode-lite/main.c line 49

Quoted 10 lines
tools/tests/x86-decode-lite/main.c new file +10 -0
+    for ( unsigned int i = 0; tests[i].name; ++i )
+    {
+        const struct test *t = &tests[i];
+        x86_decode_lite_t r;
+
+        /*
+         * Don't end strictly at t->len.  This provides better diagnostics if
+         * too many bytes end up getting consumed.
+         */
+        r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);

For the excess bytes to at least be legitimate to access (not causing UB), shouldn't finish_arr emit enough filler bytes?

Quoted 18 lines
tools/tests/x86-decode-lite/x86-emulate.h new file +15 -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

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

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

Why does this end up being needed?

Jan

#9 lore raw

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

Quoted 70 lines · Jan Beulich
Quoted 69 lines · Andrew Cooper
tools/tests/x86-decode-lite/insns.S new file +66 -0
@@ -0,0 +1,703 @@
+#include "macro-magic.h"
+
+        .code64
+
+        .allow_index_reg
+
+        .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 */
+        _ 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)
+
+        /* 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
Quoted 8 lines

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

Quoted 7 lines
tools/tests/x86-decode-lite/insns.S new file +7 -0
+        _ add %al, %cl
+        _ add %al, %dl
+        _ add %al, %bl
+        _ add %al, %ah
+        _ add %al, %ch
+        _ add %al, %dh
+        _ add %al, %dl

Perhaps also include %bpl, %sil, and %dil?

They're not relevant to this test, and interfere with the intentional pattern set up.

Quoted 10 lines
Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +9 -0
+onebyte_row_9x:
+        _ nop
+        _ pause
+        _ xchg %ax, %ax
+        _ xchg %eax, %eax
+        _ xchg %rax, %rax
+        _ rex.w xchg %rax, %rax
+        _ cltq
+        _ cqto
Quoted 8 lines

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

Quoted 7 lines
tools/tests/x86-decode-lite/insns.S new file +7 -0
+        _ wait
+        _ pushf
+        _ popf
+        _ sahf
+        _ lahf
+
+onebyte_row_ax:

May I suggest onebyte_row_Ax?

Ok.

Quoted 34 lines
Quoted 34 lines
tools/tests/x86-decode-lite/insns.S new file +33 -0
+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
Quoted 8 lines

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

Quoted 7 lines
tools/tests/x86-decode-lite/insns.S new file +7 -0
+        _ 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)

What's the idea behind the separate REX.W testing?

Testing osize handling vs Imm8/Imm.

Quoted 40 lines

It almost suggests that
tests with an operand size prefix also may want adding. Except that's difficult, because of ...

Quoted 36 lines
tools/tests/x86-decode-lite/insns.S new file +36 -0
+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
Quoted 8 lines

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

Quoted 6 lines
tools/tests/x86-decode-lite/insns.S new file +6 -0
+        _ 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

... vendor differences here. Perhaps the decoder itself would better reject handling of operand-size-prefixed branches.

Excluding 66-prefix is easy, but excluding rex.w on jumps is hard and would require extra logic.

Quoted 20 lines
Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+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

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ 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
Quoted 2 lines

Oh, you even cover the case here. For XBEGIN, however, this can only be pure guesswork as to AMD behavior, I suppose.

Remember that RTM is available on Zen2 if you know which chickenbits to clobber.

I've not tried.  I expect it's more likely that they behave consistently than differently.

Quoted 1 line

I also don't see how you force which form you want.

Binutils always produces AMD behaviour.  (As far as I can see.)

This is in the negative-tests section, which confirms that x86_decode_lite() rejects the byte pattern.

If Binutils changes behaviour, the test will start failing.

Quoted 47 lines
Quoted 47 lines
tools/tests/x86-decode-lite/main.c new file +43 -0
@@ -0,0 +1,111 @@
+/*
+ * Userspace test harness for x86_decode_lite().
+ */
+#include <stdio.h>
+
+#include "x86-emulate.h"
+
+static unsigned int nr_failures;
+#define fail(t, fmt, ...)                                       \
+({                                                              \
+    const unsigned char *insn = (t)->ip;                        \
+                                                                \
+    nr_failures++;                                              \
+                                                                \
+    (void)printf("  Fail '%s' [%02x", (t)->name, *insn);        \
+    for ( unsigned int i = 1; i < (t)->len; i++ )               \
+        printf(" %02x", insn[i]);                               \
+    printf("]\n");                                              \
+                                                                \
+    (void)printf(fmt, ##__VA_ARGS__);                           \
+})
+
+struct test {
+    const char *name;
+    void *ip;
+    unsigned long len;
+};
+
+extern const struct test
+/* Defined in insns.S, ends with sentinel */
+    tests_rel0[], /* No relocatable entry */
+    tests_rel1[], /* disp8 */
+    tests_rel4[], /* disp32 or RIP-relative */
+    tests_unsup[]; /* Unsupported instructions */
+
+static inline void run_tests(const struct test *tests, unsigned int rel_sz)
+{
+    printf("Test rel%u\n", rel_sz);
+
+    for ( unsigned int i = 0; tests[i].name; ++i )
+    {
+        const struct test *t = &tests[i];
+        x86_decode_lite_t r;
Quoted 8 lines

tools/tests/x86-decode-lite/main.c line 49

Quoted 6 lines
tools/tests/x86-decode-lite/main.c new file +6 -0
+
+        /*
+         * Don't end strictly at t->len.  This provides better diagnostics if
+         * too many bytes end up getting consumed.
+         */
+        r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);

For the excess bytes to at least be legitimate to access (not causing UB), shouldn't finish_arr emit enough filler bytes?

finish_arr is the wrong place, but I've folded in:

tools/tests/x86-decode-lite/insns.S +0 -0
index e52c2934c8d8..dc017016b2d2 100644
@@ -695,6 +695,13 @@ unsup_insn: /* Instructions that would complicated decode, or shouldn't be used


 END(tests_unsup)

+        /*
+         * For improved diagnostics, we allow some overreading of the +         * instruction under test.  Ensure there are good bytes to read. +         */
+overread_padding:
+        .skip 20
+
         /* This is here to cause jmps to use their disp32 form. */ .section .text.other_section, "ax", @progbits other_section:

Quoted 22 lines
Quoted 22 lines
tools/tests/x86-decode-lite/x86-emulate.h new file +18 -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(...)
+
Quoted 8 lines

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

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

Why does this end up being needed?

Well, this for starters:

main.c: In function ‘run_tests’:
main.c:43:9: error: unknown type name ‘x86_decode_lite_t’
   43 |         x86_decode_lite_t r;
      |         ^~~~~~~~~~~~~~~~~
main.c:49:13: error: implicit declaration of function ‘x86_decode_lite’ [-Werror=implicit-function-declaration] 49 |         r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);
      |             ^~~~~~~~~~~~~~~

~Andrew

#10 lore raw

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

Quoted 80 lines · Andrew Cooper
Quoted 70 lines · Jan Beulich
Quoted 69 lines · Andrew Cooper
tools/tests/x86-decode-lite/insns.S new file +66 -0
@@ -0,0 +1,703 @@
+#include "macro-magic.h"
+
+        .code64
+
+        .allow_index_reg
+
+        .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 */
+        _ 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)
+
+        /* 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
Quoted 8 lines

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

Quoted 7 lines
tools/tests/x86-decode-lite/insns.S new file +7 -0
+        _ add %al, %cl
+        _ add %al, %dl
+        _ add %al, %bl
+        _ add %al, %ah
+        _ add %al, %ch
+        _ add %al, %dh
+        _ add %al, %dl

Perhaps also include %bpl, %sil, and %dil?

Quoted 2 lines

They're not relevant to this test, and interfere with the intentional pattern set up.

Hmm, how does a particular pattern matter here? I don't think you test those cases (or more generally an empty REX prefix) anywhere else.

Quoted 42 lines
Quoted 33 lines
Quoted 33 lines
tools/tests/x86-decode-lite/insns.S new file +33 -0
+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
Quoted 8 lines

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

Quoted 7 lines
tools/tests/x86-decode-lite/insns.S new file +7 -0
+        _ 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)

What's the idea behind the separate REX.W testing?

Quoted 1 line

Testing osize handling vs Imm8/Imm.

I see, albeit I very much hope osize would never, ever have an effect on Imm8 encodings, as far as the size of the immediate goes.

Quoted 49 lines
Quoted 40 lines

It almost suggests that
tests with an operand size prefix also may want adding. Except that's difficult, because of ...

Quoted 36 lines
tools/tests/x86-decode-lite/insns.S new file +36 -0
+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
Quoted 8 lines

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

Quoted 6 lines
tools/tests/x86-decode-lite/insns.S new file +6 -0
+        _ 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

... vendor differences here. Perhaps the decoder itself would better reject handling of operand-size-prefixed branches.

Quoted 2 lines

Excluding 66-prefix is easy, but excluding rex.w on jumps is hard and would require extra logic.

To exclude 66 is all I was suggesting. REX.W isn't treated differently by the vendors, afaik, likely simply because it's meaningless altogether for these insns.

Quoted 26 lines
Quoted 20 lines
Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+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

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+        _ 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
Quoted 2 lines

Oh, you even cover the case here. For XBEGIN, however, this can only be pure guesswork as to AMD behavior, I suppose.

Remember that RTM is available on Zen2 if you know which chickenbits to clobber.

Quoted 6 lines

I've not tried.  I expect it's more likely that they behave consistently than differently.

Quoted 1 line

I also don't see how you force which form you want.

Binutils always produces AMD behaviour.  (As far as I can see.)

By default, yes. Quite some time ago CALL and JMP were covered more correctly, via the -mamd64 / -mintel64 cmdline options. Not very long ago I realized we had never extended that to Jcc.

Quoted 4 lines

This is in the negative-tests section, which confirms that x86_decode_lite() rejects the byte pattern.

If Binutils changes behaviour, the test will start failing.

Changing the default behavior seems extremely unlikely to me. Changing the non default behavior, otoh, has happened (and if need be could happen again).

Anyway, all of this is becoming moot if 66 was rejected on branches.

Quoted 72 lines
Quoted 46 lines
Quoted 46 lines
tools/tests/x86-decode-lite/main.c new file +43 -0
@@ -0,0 +1,111 @@
+/*
+ * Userspace test harness for x86_decode_lite().
+ */
+#include <stdio.h>
+
+#include "x86-emulate.h"
+
+static unsigned int nr_failures;
+#define fail(t, fmt, ...)                                       \
+({                                                              \
+    const unsigned char *insn = (t)->ip;                        \
+                                                                \
+    nr_failures++;                                              \
+                                                                \
+    (void)printf("  Fail '%s' [%02x", (t)->name, *insn);        \
+    for ( unsigned int i = 1; i < (t)->len; i++ )               \
+        printf(" %02x", insn[i]);                               \
+    printf("]\n");                                              \
+                                                                \
+    (void)printf(fmt, ##__VA_ARGS__);                           \
+})
+
+struct test {
+    const char *name;
+    void *ip;
+    unsigned long len;
+};
+
+extern const struct test
+/* Defined in insns.S, ends with sentinel */
+    tests_rel0[], /* No relocatable entry */
+    tests_rel1[], /* disp8 */
+    tests_rel4[], /* disp32 or RIP-relative */
+    tests_unsup[]; /* Unsupported instructions */
+
+static inline void run_tests(const struct test *tests, unsigned int rel_sz)
+{
+    printf("Test rel%u\n", rel_sz);
+
+    for ( unsigned int i = 0; tests[i].name; ++i )
+    {
+        const struct test *t = &tests[i];
+        x86_decode_lite_t r;
Quoted 8 lines

tools/tests/x86-decode-lite/main.c line 49

Quoted 6 lines
tools/tests/x86-decode-lite/main.c new file +6 -0
+
+        /*
+         * Don't end strictly at t->len.  This provides better diagnostics if
+         * too many bytes end up getting consumed.
+         */
+        r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);

For the excess bytes to at least be legitimate to access (not causing UB), shouldn't finish_arr emit enough filler bytes?

finish_arr is the wrong place, but I've folded in:

tools/tests/x86-decode-lite/insns.S +0 -0
index e52c2934c8d8..dc017016b2d2 100644
@@ -695,6 +695,13 @@ unsup_insn: /* Instructions that would complicated decode, or shouldn't be used


 END(tests_unsup)

+        /*
+         * For improved diagnostics, we allow some overreading of the +         * instruction under test.  Ensure there are good bytes to read. +         */

tools/tests/x86-decode-lite/insns.S +3 -0
+overread_padding:
+        .skip 20
+
Quoted 3 lines

         /* This is here to cause jmps to use their disp32 form. */ .section .text.other_section, "ax", @progbits other_section:

How would this help? run_tests() is never invoked with tests_unsup[] as argument. And run_tests_unsup() wants to only fetch up to t->len.

Quoted 32 lines
Quoted 21 lines
Quoted 21 lines
tools/tests/x86-decode-lite/x86-emulate.h new file +18 -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(...)
+
Quoted 8 lines

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

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

Why does this end up being needed?

Well, this for starters:

Quoted 7 lines

main.c: In function ‘run_tests’:
main.c:43:9: error: unknown type name ‘x86_decode_lite_t’
   43 |         x86_decode_lite_t r;
      |         ^~~~~~~~~~~~~~~~~
main.c:49:13: error: implicit declaration of function ‘x86_decode_lite’ [-Werror=implicit-function-declaration] 49 |         r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);
      |             ^~~~~~~~~~~~~~~

Hmm, yes, that should have been obvious, if only I didn't expect decode-lite to be largely (up to entirely) independent of the core emulator, irrespective of its placement in the same dir. x86_emulate/x86_emulate.h is a pretty involved header, which I think would be nice to avoid growing more dependencies on. Then again it looks as if about every object file already depends on it (which imo is bad).

Jan

#11 lore raw

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

Quoted 80 lines · Jan Beulich
Quoted 79 lines · Andrew Cooper
Quoted 78 lines · Jan Beulich
Quoted 66 lines · Andrew Cooper
tools/tests/x86-decode-lite/insns.S new file +63 -0
@@ -0,0 +1,703 @@
+#include "macro-magic.h"
+
+        .code64
+
+        .allow_index_reg
+
+        .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 */
+        _ 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)
+
+        /* 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)

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

Quoted 10 lines
tools/tests/x86-decode-lite/insns.S new file +10 -0
+
+        /* 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

Perhaps also include %bpl, %sil, and %dil?

Quoted 4 lines
Quoted 2 lines

They're not relevant to this test, and interfere with the intentional pattern set up.

Hmm, how does a particular pattern matter here? I don't think you test those cases (or more generally an empty REX prefix) anywhere else.

There's nothing structurally interesting about those; I'm not testing the assembler, and x86_decode_lite() doesn't decode registers.

The ModRM byte has multiple structurally interesting interactions with REX prefixes, hence the coverage of Mod and RM value.

The patten makes it trivial to look at the disassembled result and check the coverage.  (And spot the bug that's hiding in plain sight above.)

Quoted 68 lines
Quoted 68 lines
Quoted 46 lines
Quoted 46 lines
tools/tests/x86-decode-lite/main.c new file +43 -0
@@ -0,0 +1,111 @@
+/*
+ * Userspace test harness for x86_decode_lite().
+ */
+#include <stdio.h>
+
+#include "x86-emulate.h"
+
+static unsigned int nr_failures;
+#define fail(t, fmt, ...)                                       \
+({                                                              \
+    const unsigned char *insn = (t)->ip;                        \
+                                                                \
+    nr_failures++;                                              \
+                                                                \
+    (void)printf("  Fail '%s' [%02x", (t)->name, *insn);        \
+    for ( unsigned int i = 1; i < (t)->len; i++ )               \
+        printf(" %02x", insn[i]);                               \
+    printf("]\n");                                              \
+                                                                \
+    (void)printf(fmt, ##__VA_ARGS__);                           \
+})
+
+struct test {
+    const char *name;
+    void *ip;
+    unsigned long len;
+};
+
+extern const struct test
+/* Defined in insns.S, ends with sentinel */
+    tests_rel0[], /* No relocatable entry */
+    tests_rel1[], /* disp8 */
+    tests_rel4[], /* disp32 or RIP-relative */
+    tests_unsup[]; /* Unsupported instructions */
+
+static inline void run_tests(const struct test *tests, unsigned int rel_sz)
+{
+    printf("Test rel%u\n", rel_sz);
+
+    for ( unsigned int i = 0; tests[i].name; ++i )
+    {
+        const struct test *t = &tests[i];
+        x86_decode_lite_t r;
Quoted 8 lines

tools/tests/x86-decode-lite/main.c line 49

Quoted 6 lines
tools/tests/x86-decode-lite/main.c new file +6 -0
+
+        /*
+         * Don't end strictly at t->len.  This provides better diagnostics if
+         * too many bytes end up getting consumed.
+         */
+        r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);

For the excess bytes to at least be legitimate to access (not causing UB), shouldn't finish_arr emit enough filler bytes?

finish_arr is the wrong place, but I've folded in:

tools/tests/x86-decode-lite/insns.S +0 -0
index e52c2934c8d8..dc017016b2d2 100644
@@ -695,6 +695,13 @@ unsup_insn: /* Instructions that would complicated decode, or shouldn't be used


 END(tests_unsup)

+        /*
+         * For improved diagnostics, we allow some overreading of the +         * instruction under test.  Ensure there are good bytes to read. +         */

Quoted 8 lines
Quoted 6 lines
tools/tests/x86-decode-lite/insns.S +3 -0
+overread_padding:
+        .skip 20
+

         /* This is here to cause jmps to use their disp32 form. */ .section .text.other_section, "ax", @progbits other_section:

How would this help? run_tests() is never invoked with tests_unsup[] as argument. And run_tests_unsup() wants to only fetch up to t->len.

Oh, in which case nothing is needed at all.  I'll take it back out.

~Andrew

#12 lore raw

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

Quoted 83 lines · Andrew Cooper
Quoted 82 lines · Jan Beulich
Quoted 81 lines · Andrew Cooper
Quoted 70 lines · Jan Beulich
Quoted 69 lines · Andrew Cooper
tools/tests/x86-decode-lite/insns.S new file +66 -0
@@ -0,0 +1,703 @@
+#include "macro-magic.h"
+
+        .code64
+
+        .allow_index_reg
+
+        .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 */
+        _ 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)
+
+        /* 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
Quoted 8 lines

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

Quoted 7 lines
tools/tests/x86-decode-lite/insns.S new file +7 -0
+        _ add %al, %cl
+        _ add %al, %dl
+        _ add %al, %bl
+        _ add %al, %ah
+        _ add %al, %ch
+        _ add %al, %dh
+        _ add %al, %dl

Perhaps also include %bpl, %sil, and %dil?

They're not relevant to this test, and interfere with the intentional pattern set up.

Quoted 8 lines
Quoted 2 lines

Hmm, how does a particular pattern matter here? I don't think you test those cases (or more generally an empty REX prefix) anywhere else.

There's nothing structurally interesting about those; I'm not testing the assembler, and x86_decode_lite() doesn't decode registers.

The ModRM byte has multiple structurally interesting interactions with REX prefixes, hence the coverage of Mod and RM value.

If covering _every_ bit pattern of ModR/M.rm is of interest, I simply find I hard to see why also covering them empty-REX case should be of no interest at all.

Quoted 2 lines

The patten makes it trivial to look at the disassembled result and check the coverage.  (And spot the bug that's hiding in plain sight above.)

Oh, I see (now).

Quoted 75 lines
Quoted 66 lines
Quoted 66 lines
Quoted 46 lines
Quoted 46 lines
tools/tests/x86-decode-lite/main.c new file +43 -0
@@ -0,0 +1,111 @@
+/*
+ * Userspace test harness for x86_decode_lite().
+ */
+#include <stdio.h>
+
+#include "x86-emulate.h"
+
+static unsigned int nr_failures;
+#define fail(t, fmt, ...)                                       \
+({                                                              \
+    const unsigned char *insn = (t)->ip;                        \
+                                                                \
+    nr_failures++;                                              \
+                                                                \
+    (void)printf("  Fail '%s' [%02x", (t)->name, *insn);        \
+    for ( unsigned int i = 1; i < (t)->len; i++ )               \
+        printf(" %02x", insn[i]);                               \
+    printf("]\n");                                              \
+                                                                \
+    (void)printf(fmt, ##__VA_ARGS__);                           \
+})
+
+struct test {
+    const char *name;
+    void *ip;
+    unsigned long len;
+};
+
+extern const struct test
+/* Defined in insns.S, ends with sentinel */
+    tests_rel0[], /* No relocatable entry */
+    tests_rel1[], /* disp8 */
+    tests_rel4[], /* disp32 or RIP-relative */
+    tests_unsup[]; /* Unsupported instructions */
+
+static inline void run_tests(const struct test *tests, unsigned int rel_sz)
+{
+    printf("Test rel%u\n", rel_sz);
+
+    for ( unsigned int i = 0; tests[i].name; ++i )
+    {
+        const struct test *t = &tests[i];
+        x86_decode_lite_t r;
Quoted 8 lines

tools/tests/x86-decode-lite/main.c line 49

Quoted 6 lines
tools/tests/x86-decode-lite/main.c new file +6 -0
+
+        /*
+         * Don't end strictly at t->len.  This provides better diagnostics if
+         * too many bytes end up getting consumed.
+         */
+        r = x86_decode_lite(t->ip, t->ip + /* t->len */ 20);

For the excess bytes to at least be legitimate to access (not causing UB), shouldn't finish_arr emit enough filler bytes?

finish_arr is the wrong place, but I've folded in:

tools/tests/x86-decode-lite/insns.S +0 -0
@@ -695,6 +695,13 @@ unsup_insn: /* Instructions that would complicated decode, or shouldn't be used


 END(tests_unsup)

+        /*
+         * For improved diagnostics, we allow some overreading of the +         * instruction under test.  Ensure there are good bytes to read. +         */

Quoted 8 lines
Quoted 6 lines
tools/tests/x86-decode-lite/insns.S +3 -0
+overread_padding:
+        .skip 20
+

         /* This is here to cause jmps to use their disp32 form. */ .section .text.other_section, "ax", @progbits other_section:

How would this help? run_tests() is never invoked with tests_unsup[] as argument. And run_tests_unsup() wants to only fetch up to t->len.

Quoted 1 line

Oh, in which case nothing is needed at all.  I'll take it back out.

Yet then, as previously indicated, the possible overrun in run_tests()' fetching will want covering. Hence why I suggested the particular other place to put extra padding.

Jan

#13 lore raw

PATCH v3 3/5 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]>
CC: Teddy Astie <[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 5ed0c2672589..fd03147bdd12 100644
@@ -16,6 +16,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)
@@ -586,6 +587,57 @@ static void __init _alternative_instructions(unsigned int what)
 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(ALT_INSNS);
 }
 
Signature · 1 line
2.39.5
#14 lore raw

PATCH v3 4/5 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.

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

v3:
* Rebase over the split-out of altcall. Substantially simpler.

---
 xen/arch/x86/alternative.c | 50 +++++++++++++++++++++++++++++++-------
 1 file changed, 41 insertions(+), 9 deletions(-)
xen/arch/x86/alternative.c +41 -9
index fd03147bdd12..a4a65597b2fc 100644
@@ -349,15 +349,47 @@ 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 )
-            *(int32_t *)(buf + 1) += repl - orig;
-        else if ( IS_ENABLED(CONFIG_RETURN_THUNK) &&
-                  a->repl_len > 5 && buf[a->repl_len - 5] == 0xe9 &&
-                  ((long)repl + a->repl_len +
-                   *(int32_t *)(buf + a->repl_len - 4) ==
-                   (long)__x86_return_thunk) )
-            *(int32_t *)(buf + a->repl_len - 4) += repl - orig;
+        /*
+         * Walk buf[] and adjust any insn-relative operands which leave the
+         * replacement block.
+         */
+        if ( a->repl_len )
+        {
+            uint8_t *ip = buf, *repl_end = ip + a->repl_len;
+
+            for ( x86_decode_lite_t res; ip < repl_end; ip += res.len )
+            {
+                int32_t *d32;
+                const uint8_t *target;
+
+                res = x86_decode_lite(ip, repl_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;
+                target = ip + res.len + *d32;
+
+                if ( target >= buf && target <= repl_end )
+                {
+                    /*
+                     * Target doesn't leave the replacement block.  e.g. RSB
+                     * stuffing.  Leave it unmodified.
+                     */
+                    continue;
+                }
+
+                *d32 += repl - orig;
+            }
+        }
 
         a->priv = 1;
 
Signature · 1 line
2.39.5
#15 lore raw

PATCH v3 5/5 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]>
CC: Teddy Astie <[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 cebc70064048..76508c0de2f3 100644
@@ -59,12 +59,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