Skip to contentSkip to conversation

: port of embedded x86-mini disassembler to QEMU

RFC Paolo Bonzini 2 participants 5 messages Jan 10, 2025 – Jan 11, 2025 1 message not in the archive

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

#1 lore raw

Il ven 10 gen 2025, 10:52 Michael Clark <[email protected]> ha scritto:

Quoted 3 lines

a note to announce a port of the x86-mini disassembler to QEMU.

- https://github.com/michaeljclark/qemu/tree/x86-mini

I assume the huge .h files are autogenerated? If so, QEMU cannot use them without including the human-readable sources in the tree.

I can see how that might be interesting for x86 virtualization where you have only one target and therefore you can get rid of the capstone dependency. At the same time, other virtualization targets like arm64 and RISC-V are going to become more and more important—not less—and not having to maintain a disassembler ourselves as part of QEMU is also a big plus...

Paolo

Quoted 93 lines

- https://github.com/michaeljclark/x86/tree/x86-mini

# x86-mini

the x86-mini library is a lightweight x86 encoder, decoder, and disassembler that uses extensions to the Intel instruction set metadata format to encode modern VEX/EVEX instructions and legacy instructions using a parameterized LEX (legacy extension) format.

- metadata-driven disassembler with Intel format output.
- written in C11 for compatibility with projects written in C.
- low-level instruction encoder and decoder uses <= 32-bytes.
- python tablegen program to generate C tables from CSV metadata.
- metadata table tool to inspect operand encode and decode tables.
- carefully checked machine-readable instruction set metadata.
- support for REX/VEX/EVEX and preliminary support for REX2.

the x86-mini x86 encoder and decoder library has been written from scratch to be modern and as simple as possible while also covering recent additions to the Intel and AMD 64-bit instruction sets such as the EVEX encodings for recent AVX-512 extensions and soon REX2/ EVEX encodings for Intel APX, as it is written with that in mind.

## interest to the QEMU community

- x86-mini is fast. raw decode performance is ~100-200MiB/sec.
- x86-mini is small. 5 files, ~5 KLOC or ~13 KLOC including tables.
- x86-mini is complete and includes the latest AVX-512 extensions.
- x86-mini is easy to extend and uses extended Intel format metadata.
- x86-mini is documented with detailed info on the metadata format.
- x86-mini has CLI tools for searching x86 instruction set metadata.

## techinical notes

- the decoder is table-based and uses a metadata interpreter.
- the decode table is ~66KiB with a ~150KiB acceleration trie.
- there are currently 3658 opcode entries active on x86-64 which expands to 4775 table entries due to parameterization.
- it could be made faster by vectorizing the prefix decoder and generating decode templates from the metadata to consteval metadata interpretation to eliminate some L1 D$ traffic.

after cherry-picking the commit, one can test host and target disassembly support. e.g. for an x86-64 target on an x86-64 host:

$ echo aaa | qemu-x86_64 -d in_asm,out_asm /usr/bin/openssl sha256

## caveats and limitations

- supports 32-bit and 64-bit disassembly, and theoretically 16-bit.
- designed to support 16-bit but base index formats are not done yet.
- x86-64 is exhaustively fuzz-tested against the LLVM disassembler.
- but x86-mini is new and hasn't been battle-tested in production.

if you already link with capstone then it doesn't provide very many immediate benefits, however, I think it is potentially useful as a small embeddable disassembler to evaluate for potential inclusion.

## rationale

I worked on the QEMU disassembler while working on the QEMU RISC-V target back in 2017/2018 and I was curious about vector support. it seemed at the time that TCG vector support was piecemeal, plus the old x86 disassembler seemed messy and incomplete. I also needed an MIT-licensed disassembler to enable use in a commercial product. basically, I was looking for a lightweight symmetric x86 instruction encoder and decoder library in pure C with simple build requirements. that is what prompted this initiative.

it would be nice to have an x86 disassembler building out-of-the-box as I find QEMU's built-in tracing extremely useful and given x86 is a popular target, a small embedded disassembler might be practical.

## summary and conclusion

at minimum, the metedata may be useful for x86 EVEX support. note I see tests/tcg/i386/x86.csv in the source tree. the metadata is also based on x86-csv but has had numerous inaccuracies fixed as well as conversion of legacy instructions to the new LEX format. in effect the metadata has been fuzz-tested against LLVM for x86-64 and ISA coverage is in the order of ~99.7%. the main branch of the linked repo has a procedural fuzzer for metadata-based instruction synthesis that could be useful for generating test cases for QEMU.

I am kind of throwing this over the fence, although the code is quite self-contained and my stress and mental health is now under control. also I have not yet run checkpatch.pl on this code. it is a preview.

x86-mini submaintainer.
Michael Clark.
--

#2 lore raw
Quoted 8 lines · Paolo Bonzini

Il ven 10 gen 2025, 10:52 Michael Clark <[email protected]> ha scritto:

Quoted 3 lines

a note to announce a port of the x86-mini disassembler to QEMU.

- https://github.com/michaeljclark/qemu/tree/x86-mini

I assume the huge .h files are autogenerated? If so, QEMU cannot use them without including the human-readable sources in the tree.

yes indeed. there is an x86_tablegen.py python script in the other repo but it is not in the current patch. it would be somewhat easy to read the tables from CSV files directly into arrays at the expense of several more milliseconds during startup. the revised operand formats maps relatively strictly to enum definitions with string tables in the source so a reader in C would not be impossible. it needs a Lisp interpreter so that it could unexec the compiled tables into a translation cache :-).

Quoted 5 lines

I can see how that might be interesting for x86 virtualization where you have only one target and therefore you can get rid of the capstone dependency. At the same time, other virtualization targets like arm64 and RISC-V are going to become more and more important—not less—and not having to maintain a disassembler ourselves as part of QEMU is also a big plus...

yes indeed. but in an ideal world the encoders and decoders are matched pairs. I would like to work on a translator or interpreter that uses the same codec as the disassembler that it uses. although I guess there is a point to having different codecs and disassemblers for differential fuzzing. but there is also a point to having a matched encoder and decoder. it just seems to me that if you write a machine lowering rule you should write a machine lifting rule.

anyway, in fact it is just yet another disassembler at this point, but the codec emitter works. it doesn't yet have an arch-neutral TCG-like API and IR to drive it yet. but if I wrote an interpreter it would be the exact same data structures. now I need to write an assembler. e.g.

// VMOVD xmm,xmm/m32 [rm: evex.128.66.0f.w0 6e /r] // asm: vmovd xmm31,DWORD PTR [r14+r13*8-8]

x86_buffer buf;
x86_codec codec;

  x86_buffer_init_ex(&buf, mem_addr, 0, mem_length);
  memset(&codec, 0, sizeof(codec));

  codec.opc[0] = 0x6e;
  codec.opclen = 1;
  codec.flags |= x86_cf_amd64;
  codec.flags |= x86_cf_modrm;
  codec.flags |= x86_ce_evex;
  codec.evex = x86_enc_evex(
    x86_map_0f, x86_pfx_66, x86_vex_l128, x86_vex_w0,
    /*r*/ x86_xmm31, /*x*/ x86_r13, /*b*/ x86_r14, /*v*/ 0,
    /*k*/ 0, /*brd*/ 0, /*z*/ 0
  );
  codec.modrm = x86_enc_modrm(x86_mod_disp8, x86_xmm31, x86_rm_sp_sib);
  codec.sib = x86_enc_sib(x86_scale_8, x86_r13, x86_r14);
  codec.disp32 = -2;

x86_codec_write(&buf, codec, &nbytes)

the trunk branch in the repo has examples for a disassembler with the LLVM C-API and C++API. it would be a tiny piece of glue to link in an LLVM based disassembler too. but this code is faster than LLVM. :-D

Michael

Quoted 97 lines

Paolo

Quoted 93 lines

- https://github.com/michaeljclark/x86/tree/x86-mini

# x86-mini

the x86-mini library is a lightweight x86 encoder, decoder, and disassembler that uses extensions to the Intel instruction set metadata format to encode modern VEX/EVEX instructions and legacy instructions using a parameterized LEX (legacy extension) format.

- metadata-driven disassembler with Intel format output.
- written in C11 for compatibility with projects written in C.
- low-level instruction encoder and decoder uses <= 32-bytes.
- python tablegen program to generate C tables from CSV metadata.
- metadata table tool to inspect operand encode and decode tables.
- carefully checked machine-readable instruction set metadata.
- support for REX/VEX/EVEX and preliminary support for REX2.

the x86-mini x86 encoder and decoder library has been written from scratch to be modern and as simple as possible while also covering recent additions to the Intel and AMD 64-bit instruction sets such as the EVEX encodings for recent AVX-512 extensions and soon REX2/ EVEX encodings for Intel APX, as it is written with that in mind.

## interest to the QEMU community

- x86-mini is fast. raw decode performance is ~100-200MiB/sec.
- x86-mini is small. 5 files, ~5 KLOC or ~13 KLOC including tables.
- x86-mini is complete and includes the latest AVX-512 extensions.
- x86-mini is easy to extend and uses extended Intel format metadata.
- x86-mini is documented with detailed info on the metadata format.
- x86-mini has CLI tools for searching x86 instruction set metadata.

## techinical notes

- the decoder is table-based and uses a metadata interpreter.
- the decode table is ~66KiB with a ~150KiB acceleration trie.
- there are currently 3658 opcode entries active on x86-64 which expands to 4775 table entries due to parameterization.
- it could be made faster by vectorizing the prefix decoder and generating decode templates from the metadata to consteval metadata interpretation to eliminate some L1 D$ traffic.

after cherry-picking the commit, one can test host and target disassembly support. e.g. for an x86-64 target on an x86-64 host:

$ echo aaa | qemu-x86_64 -d in_asm,out_asm /usr/bin/openssl sha256

## caveats and limitations

- supports 32-bit and 64-bit disassembly, and theoretically 16-bit.
- designed to support 16-bit but base index formats are not done yet.
- x86-64 is exhaustively fuzz-tested against the LLVM disassembler.
- but x86-mini is new and hasn't been battle-tested in production.

if you already link with capstone then it doesn't provide very many immediate benefits, however, I think it is potentially useful as a small embeddable disassembler to evaluate for potential inclusion.

## rationale

I worked on the QEMU disassembler while working on the QEMU RISC-V target back in 2017/2018 and I was curious about vector support. it seemed at the time that TCG vector support was piecemeal, plus the old x86 disassembler seemed messy and incomplete. I also needed an MIT-licensed disassembler to enable use in a commercial product. basically, I was looking for a lightweight symmetric x86 instruction encoder and decoder library in pure C with simple build requirements. that is what prompted this initiative.

it would be nice to have an x86 disassembler building out-of-the-box as I find QEMU's built-in tracing extremely useful and given x86 is a popular target, a small embedded disassembler might be practical.

## summary and conclusion

at minimum, the metedata may be useful for x86 EVEX support. note I see tests/tcg/i386/x86.csv in the source tree. the metadata is also based on x86-csv but has had numerous inaccuracies fixed as well as conversion of legacy instructions to the new LEX format. in effect the metadata has been fuzz-tested against LLVM for x86-64 and ISA coverage is in the order of ~99.7%. the main branch of the linked repo has a procedural fuzzer for metadata-based instruction synthesis that could be useful for generating test cases for QEMU.

I am kind of throwing this over the fence, although the code is quite self-contained and my stress and mental health is now under control. also I have not yet run checkpatch.pl on this code. it is a preview.

x86-mini submaintainer.
Michael Clark.
--

#3 lore raw

Il ven 10 gen 2025, 14:03 Michael Clark <[email protected]> ha scritto:

Quoted 11 lines · Paolo Bonzini
Quoted 1 line

Il ven 10 gen 2025, 10:52 Michael Clark <[email protected]> ha

scritto:

Quoted 7 lines
Quoted 4 lines

a note to announce a port of the x86-mini disassembler to QEMU.

- https://github.com/michaeljclark/qemu/tree/x86-mini

I assume the huge .h files are autogenerated? If so, QEMU cannot use them without including the human-readable sources in the tree.

Quoted 6 lines

yes indeed. there is an x86_tablegen.py python script in the other repo but it is not in the current patch. it would be somewhat easy to read the tables from CSV files directly into arrays at the expense of several more milliseconds during startup. the revised operand formats maps relatively strictly to enum definitions with string tables in the source so a reader in C would not be impossible

Building the tables at compile time is fine, only leaving out the script is not.

Quoted 11 lines

I can see how that might be interesting for x86 virtualization where you

Quoted 3 lines

have only one target and therefore you can get rid of the capstone dependency. At the same time, other virtualization targets like arm64 and RISC-V are going to become more and more important—not less—and not

having

Quoted 1 line

to maintain a disassembler ourselves as part of QEMU is also a big

plus...

yes indeed. but in an ideal world the encoders and decoders are matched pairs. I would like to work on a translator or interpreter that uses the same codec as the disassembler

Ok, that makes sense. QEMU already has a decoder that is very table-based though the tables are hand written. I am not wed to it though—as long as the code generators remain more or less unmodified, I would love to only keep "these is how the operands are prepared for use in the IR emitters" and make the details of x86 decoding Someone Else's Problem. So if you can kill most (certainly not all) of the tables in target/i386/tcg/decode-new.c.inc that would be interesting.

(I am sure you'd find some underspecified and/or wrong parts of the x86 spec, too :) For example many VEX classes are bollocks, plus some more examples hinted at at the top of that file).

Paolo

anyway, in fact it is just yet another disassembler at this point, but

Quoted 3 lines

the codec emitter works. it doesn't yet have an arch-neutral TCG-like API and IR to drive it yet.

#4 lore raw
Quoted 21 lines · Paolo Bonzini

Il ven 10 gen 2025, 14:03 Michael Clark <[email protected]> ha scritto:

Quoted 11 lines · Paolo Bonzini
Quoted 1 line

Il ven 10 gen 2025, 10:52 Michael Clark <[email protected]> ha

scritto:

Quoted 7 lines
Quoted 4 lines

a note to announce a port of the x86-mini disassembler to QEMU.

- https://github.com/michaeljclark/qemu/tree/x86-mini

I assume the huge .h files are autogenerated? If so, QEMU cannot use them without including the human-readable sources in the tree.

Quoted 6 lines

yes indeed. there is an x86_tablegen.py python script in the other repo but it is not in the current patch. it would be somewhat easy to read the tables from CSV files directly into arrays at the expense of several more milliseconds during startup. the revised operand formats maps relatively strictly to enum definitions with string tables in the source so a reader in C would not be impossible

Quoted 2 lines

Building the tables at compile time is fine, only leaving out the script is not.

fair enough. I wanted to test the disassembler and I figured out how to do that with both QEMU host and target. I haven't learned how to create generative dependencies in meson yet but it can't be as bad as CMake.

QEMU running openssl is a pretty good torture test. I am going to spend time analyzing the -d in_asm,out_asm logs for openssl. I don't yet have a pseudo alias translation step so NOP still shows as XCHG eax,eax.

and fuzzing x86_64 was extremely interesting as it uncovered some hardware bugs that led to historic findings inside the QEMU translator. so I know that the level of accuracy is somewhat good. for example:

NOP -> XCHG eax,eax
REX.B XCHG eax,eax -> XCHG eax,r8d
PAUSE -> REP NOP -> REP XCHG eax,eax
REX.B PAUSE -> REP REX.B XCHG eax,eax -> REP XCHG eax,r8d

it seems Intel filters out REX.B for NOP but not REP NOP. and I know what QEMU does. it does what one expects. unused REP is undefined but typically is ignored for non string instructions with the exception of 0F, 0F38, 0F3A where REP/F3 is interpreted as part of the opcode. but Intel has made REP XCHG eax,r8d act like REP NOP. I haven't tested this out on AMD hardware but I consider it a silicon bug on Intel. there is a test case on this binutils issue. in any case, this is in QEMU history.

- https://sourceware.org/bugzilla/show_bug.cgi?id=32462
- https://www.blackhat.com/docs/us-17/thursday/us-17-Domas-Breaking-The-x86-ISA.pdf

Quoted 21 lines
Quoted 11 lines

I can see how that might be interesting for x86 virtualization where you

Quoted 3 lines

have only one target and therefore you can get rid of the capstone dependency. At the same time, other virtualization targets like arm64 and RISC-V are going to become more and more important—not less—and not

having

Quoted 1 line

to maintain a disassembler ourselves as part of QEMU is also a big

plus...

yes indeed. but in an ideal world the encoders and decoders are matched pairs. I would like to work on a translator or interpreter that uses the same codec as the disassembler

Ok, that makes sense. QEMU already has a decoder that is very table-based though the tables are hand written. I am not wed to it though—as long as the code generators remain more or less unmodified, I would love to only keep "these is how the operands are prepared for use in the IR emitters" and make the details of x86 decoding Someone Else's Problem. So if you can kill most (certainly not all) of the tables in target/i386/tcg/decode-new.c.inc that would be interesting.

Quoted 3 lines

(I am sure you'd find some underspecified and/or wrong parts of the x86 spec, too :) For example many VEX classes are bollocks, plus some more examples hinted at at the top of that file).

yes indeed. the metadata in the Intel SDM is littered with mistakes such as field transpositions, typos and missing data. I would hazard a guess that maybe ~71% of the metadata is usable in a machine readable manner. given that LLVM tablegen has its own format, I consider x86-mini the source of truth for metadata derived from the Intel format. although I haven't fuzz tested again NASM yet, but I found a small number of errors in LLVM. albeit mostly in instructions that are not used in anger.

Michael.

Quoted 7 lines

Paolo

anyway, in fact it is just yet another disassembler at this point, but

Quoted 3 lines

the codec emitter works. it doesn't yet have an arch-neutral TCG-like API and IR to drive it yet.

#5 lore raw
In reply to Paolo Bonzini
Quoted 17 lines · Paolo Bonzini

Il ven 10 gen 2025, 14:03 Michael Clark<[email protected]> ha scritto:

Quoted 6 lines · Paolo Bonzini
Quoted 1 line

Il ven 10 gen 2025, 10:52 Michael Clark<[email protected]> ha

scritto:

Quoted 3 lines
Quoted 3 lines

a note to announce a port of the x86-mini disassembler to QEMU.

-https://github.com/michaeljclark/qemu/tree/x86-mini

Quoted 8 lines
Quoted 2 lines

I assume the huge .h files are autogenerated? If so, QEMU cannot use them without including the human-readable sources in the tree.

yes indeed. there is an x86_tablegen.py python script in the other repo but it is not in the current patch. it would be somewhat easy to read the tables from CSV files directly into arrays at the expense of several more milliseconds during startup. the revised operand formats maps relatively strictly to enum definitions with string tables in the source so a reader in C would not be impossible

Quoted 2 lines

Building the tables at compile time is fine, only leaving out the script is not.

okay. now it's even smaller. I don't mind if folks kick the tyres on the code but I'm not asking for it to be merged. I'd want it to be in better shape if folks decide they like it. and I don't want to expose anyone including myself to metadata format changes. so maybe 6-18 months time.

$ git show | diffstat
 b/disas/meson.build       |   93
 b/disas/x86-core.c        |    5
 b/disas/x86.h             |    2
 b/scripts/x86-tablegen.py |  540 +++
 disas/x86-enums.inc       | 1883 -----------
 disas/x86-tables.inc      | 6218 --------------------------------------
 6 files changed, 636 insertions(+), 8105 deletions(-)
$ wc -l disas/x86*[ch] scripts/x86-tablegen.py
  2846 disas/x86-core.c
    92 disas/x86-disas.c
  1758 disas/x86.h
   540 scripts/x86-tablegen.py
  5236 total
$ wc -l disas/x86-data/*.csv | tail -5
     4 disas/x86-data/x86_waitpkg.csv
     2 disas/x86-data/x86_wbnoinvd.csv
   145 disas/x86-data/x86_x87.csv
     3 disas/x86-data/x86_xsaveopt.csv
  3731 total

x86_fuzzer.c in the other repo might be interesting. ~900 LOC showing instruction set metadata reflection for generative fuzzing. it has a tiny combinatorial expansion algorithm with constraints for conditional domain reduction to prune the graph. like I vary imm when we have RAX as the base register and various other pruning heuristics such as riz. it needs some random synthesis but I will get to that at some point.

https://github.com/michaeljclark/x86/blob/trunk/tests/x86_fuzzer.c

it exposes some of the internals of the codec. the tables exclusively have a maximum of two opcode bytes with one conditionally being ModRM. the codec converts REX.W/VEX/EVEX/prefix/map into trie page selectors. it also expands out ModRM masks if multiple instructions straddle the same opcode byte with different mod values. like this curiosity where the same opcode is used for two instructions, one as reg, one as mem.

  f3 0f c7 f7          senduipi    edi
  f3 0f c7 77 01       vmxon       qword ptr [rdi + 1]

so I spent time on instrumentation (output is snipped due to width).

$ ./build/x86_opcodes -o -g | egrep '(senduipi|vmxon|cmpxchg8b)'
| cmpxchg8b m64     | c7 08 | ff f8 | .lex.0f.w0 c7 /1 .lock   |
| cmpxchg8b m64     | c7 48 | ff f8 | .lex.0f.w0 c7 /1 .lock   |
| cmpxchg8b m64     | c7 88 | ff f8 | .lex.0f.w0 c7 /1 .lock   |
| vmxon m64         | c7 30 | ff f8 | .lex.f3.0f.w0 c7 /6      |
| vmxon m64         | c7 70 | ff f8 | .lex.f3.0f.w0 c7 /6      |
| vmxon m64         | c7 b0 | ff f8 | .lex.f3.0f.w0 c7 /6      |
| senduipi rw       | c7 f0 | ff f8 | .lex.f3.0f.w0 c7 /6      |

this shows you the LEX format which has new suffixes like 'wx' and 'ww' for default 32 or default 64 operand sizes. looks a lot like VEX/EVEX. and all legacy instructions have been converted to use this form so it is much easier to reason about decoding them. in any case, folks might be curious and decide they want to experiment with it.

$ echo aaa | qemu-x86_64 -d in_asm,out_asm /usr/bin/openssl sha256

I see SSE2/AVX instructions in the output and it doesn't crash. :D it's quite eye-opening to see the codegen. it would be nice to get qemu-system to use the MMU by running the translator with the HV on.

btw Intel XED is pretty neat but its build system is totally alien.

Michael.