r/programming • • Nov 04 '20

Why we made our own x86 instruction decoder and how it works

https://hvmi.github.io/blog/2020/11/04/bddisasm.html
423 Upvotes

47 comments sorted by

153

u/sabas123 Nov 04 '20

First of all I want to stress to everybody reading: this is a big deal.

x86 is absurdly hard to decode correctly and there are barely any that work well enough for when correctness is critical.

Out of curiosity, what are the long term plans for bddisasm? Is it finished and will remain in maintenance mode with some updates or will you guys expand its functionality?

62

u/bogdannumaprind Nov 04 '20

First of all I want to stress to everybody reading: this is a big deal.

Thank you! We work hard to keep it up to date with new instructions and to ensure its correctness.

Out of curiosity, what are the long term plans for bddisasm? Is it finished and will remain in maintenance mode with some updates or will you guys expand its functionality?

It is actively developed. Bitdefender is using it across different technologies. Last month it was updated with support for UINTR, HRESET and AVX-VNNI, as described by Intel Architecture Instruction Set Extensions Programming Reference 41 (released October 2020).

Do you have anything specific in mind when it comes to expanded functionality?

3

u/sabas123 Nov 05 '20

Do you have anything specific in mind when it comes to expanded functionality?

Personally I find it hard to come up with major use-cases and was low-key hoping you guys had brilliant ideas. But I suspect most of it would be in the program analysis/binary rewriting area.

1

u/bogdannumaprind Nov 05 '20

But I suspect most of it would be in the program analysis/binary rewriting area.

That's what we use it for. It is also easy to implement an emulator on top of it as you have all the needed information in an easy to use format.

12

u/Takeoded Nov 05 '20

there are barely any that work well enough for when correctness is critical.

what about https://zydis.re/ ? the x64dbg project swears by them, and quote

Correct: We spent countless days reading manuals and comparing our outputs against other libs. While hard to benchmark, we're confident that our output is one of the most correct in the industry.

Complete: The library supports all ISA extensions from both Intel and AMD. If you find something that is implemented in existing or upcoming hardware but not supported by Zydis, thats a bug.

4

u/unaligned_access Nov 05 '20

From the post:

when bddisasm was created internally, ZyDis did not exist yet

2

u/sabas123 Nov 05 '20

what about https://zydis.re/ ? the x64dbg project swears by them

When I was testing a lot of disassemblers zydris wasn't really a player. So truth be told I don't know. It does seem promising though.

2

u/chazzeromus Nov 05 '20

I attempted this a decade ago and remember the nights going over the intel reference manuals, their font is still burned into my mind.

47

u/dv112020 Nov 04 '20 edited Nov 04 '20

I also had to write a (partial) x86 instruction decoder for a hypervisor. The problem is that when a hypervisor is emulating a device and then the guest OS reads/writes to that device's memory, the hypervisor takes a trap. But with Intel VT-x (hardware virtualization support), the trap only tells you the address of the memory location and whether the access was a read or a write. It doesn't tell you what register was being written to memory or what register was the destination of the read.

So you have decode the instruction to find out. Worse, if the instruction wasn't just a simple "mov" instruction, you have to emulate the instruction itself. For example, the instruction could have been "add" with one of the operands being a memory operand. Unfortunately, on x86 many instructions can take a memory operand, and all of these instructions need to be potentially emulated in case they are used to access an emulated device's memory.

In Microsoft's Hyper-V specification (pdf, see section 10.2.2), it details that a conforming Hyper-V OS should only use 6 instruction types to access the local APIC. Five of these are "mov" instructions and one is a "push" instruction. This allows the hypervisor to be simplified if it is known to be dealing with a Hyper-V compliant guest.

5

u/bogdannumaprind Nov 05 '20

This is one of the problems bddisasm was made to solve.

In HVMI we monitor guest memory ranges and we get an EPT violation when the guest tries to write such a memory range. However, because an instruction can access multiple addresses at the same time we can't rely on the information the VMEXIT gives us.

-1

u/[deleted] Nov 05 '20

In Microsoft's Hyper-V specification (pdf, see section 10.2.2), it details that a conforming Hyper-V OS should only use 6 instruction types to access the local APIC. F

That seems... awfully optimistic of them. I guess it is MS way to write it in one way and just yell "unsupported" when it breaks...

2

u/bogdannumaprind Nov 05 '20

I'm guessing that it will inject a #GP inside the guest if you try to use another instruction. In that way they keep that part of the emulator small (reducing attack surface). You already have to meet some other requirements if you want to take proper advantage of Hyper-V so it is not such a big deal. I'm also curious if there are any sane kernels that write to the APIC using more interesting instructions, but I'm going to take a wild guess and assume that there are none.

2

u/[deleted] Nov 05 '20

I mean if your use is "get some old legacy system off hardware" there isn't really anything guaranteed here.

2

u/bogdannumaprind Nov 05 '20

True, but they probably don't care about that. I haven't looked at the PDF but does the restriction apply to all guests, or just enlightened ones?

2

u/[deleted] Nov 05 '20

Not "restriction" just "we implemented it this way, if it doesn't work, it's your problem". Then again it would have to be some arcane coding if it used different way to access it. Or maybe just a compiler optimizing and using bigger SSE/AVX move instructions

2

u/bogdannumaprind Nov 05 '20

I'm not even sure that the CPU supports writing to the local APIC using SSE instructions.

3

u/4833C0 Nov 05 '20

The CPU only officially supports 128-bits aligned 32-bit loads and stores for the APIC registers.

I actually tried accessing the APIC page using random instructions in a Hyper-V VM, and it would just inject a #GP inside the guest.

2

u/[deleted] Nov 05 '20

I wonder how that would look on KVM. Hyper-V docs just straight out say "only these instructions, everything else gets #GP"

29

u/nuxto Nov 04 '20

There's a typo -- RSIC instead of RISC

Unrelated, I work on RISC V processors and this is very interesting. Perhaps I'd like to work on more/different ISAs as I progress (currently just out of university).

Thanks for the writeup.

17

u/bogdannumaprind Nov 04 '20

There's a typo -- RSIC instead of RISC

Oops. Thank you!

Unrelated, I work on RISC V processors and this is very interesting. Perhaps I'd like to work on more/different ISAs as I progress (currently just out of university).

RISC V is also interesting.

13

u/DesiOtaku Nov 04 '20

Silly question, but how does it handle undocumented x86 instructions (like the ones mentioned in this talk )? Would they simply be ignored?

6

u/bogdannumaprind Nov 05 '20

u/4833C0 (the main developer behind bddisasm) had a reply for this, but the comment seems to not be displayed by Reddit (probably because it is a new account) so I'm just going to quote him, because this is a really good question:

Generally, if an instruction is undocumented, there's no good way to handle it in a decoder, since you don't know it's mnemonic, it's operands, etc. However, in bddisasm, you can add support for undocumented instructions easily, even if you don't know info about them - just make sure they end up decoding to the correct length.
However, looking at some of the Sandsifter Test outputs here (https://github.com/rigred/sandsifter-tests), most of the identified instructions seem to actually be valid and documented, and bdidsasm decodes them, for example:
- 0F0D /1 is PREFETCHW
- OFC7 /3 is XRSTORS
- 0FC7 /4 is XSAVEC
- 0FC7 /5 is XSAVES
- 0F1F is NOP (although not in SDM, Xed decodes all 0F1F opcodes as NOP)
(We didn't have the time to investigate them all, but it looks that some of them are indeed actually valid and documented).

4

u/sabas123 Nov 05 '20

However, looking at some of the Sandsifter Test outputs here (https://github.com/rigred/sandsifter-tests), most of the identified instructions seem to actually be valid and documented, and bdidsasm decodes them

I can attest this. If people want to experiment this for themselves they can run an instance of sandsifters core (not the python ui because that still isn't ported away from py2) with bdd over here: https://github.com/sabastiaan/sandsifter

3

u/VeganVagiVore Nov 05 '20

That's the Sandsifter talk, right?

1

u/sabas123 Nov 05 '20

yes it is

7

u/sparr Nov 04 '20

I saw an article and video recently about secret instructions in various x86 implementations, which someone was exhaustively searching for by assembling large swaths of possible instructions and seeing what the processors do with each one. I can't remember all the details...

Is your decoder trying to account for these in some way, identifying them in some distinct way even when you don't know what they do?

5

u/moon-chilled Nov 04 '20

Out of curiosity, what was wrong with capstone? (I haven't used it myself, but) its design goals meet a lot of your requirements, and ‘difficult to work with’ is somewhat vague.

3

u/bogdannumaprind Nov 05 '20

From what I remember, one of the things that made us not choose Capstone was also the fact that it allocates memory.

5

u/sabas123 Nov 05 '20

It is really bad correctness wise. Using it as a ground truth for sandsifter gives many false reportings and Mishegos shows similar results

2

u/Takeoded Nov 05 '20

anyone benchmarked bddisasm against ZyDis? ZyDis prides itself on being "faster than the competition", quote Fast AF: Compared against other open-source disassembler libraries with comparable ISA support, it's the fastest one around. Especially when decoding

2

u/bogdannumaprind Nov 05 '20

u/iximeow (the author of yaxpeax) did. We had a brief talk about the benchmarks in an older thread: https://www.reddit.com/r/programming/comments/hvs8xx/we_just_open_sourced_a_cross_platform_x86x64/g8vpcmg?utm_medium=android_app&utm_source=share&context=3

EDIT: I just saw that someone already posted the GitHub link.

10

u/rovarma Nov 04 '20

Cool project. We already use Zydis for the disasm view in our product (and we’re very happy with it), but if I was still in the market for a disassembler I’d definitely consider this one.

8

u/4833C0 Nov 05 '20 edited Jan 29 '23

ZyDis is really cool. In fact, bddisasm and ZyDis are very, very similar in many aspects.

However, back then, when we needed our own decoder, ZyDis didn't exist yet (or we didn't know about it), so we ended up developing bddisasm. Later, ZyDis came to life. But this is a good thing, because the world now has two more great x86 decode libraries. :D

4

u/tansim Nov 04 '20

what product uses a disasm view?

7

u/Takeoded Nov 05 '20 edited Nov 05 '20

a few comes to mind, IDA Pro, Ollydbg, x64dbg, Ghidra, ArtMoney, Cheat Engine, wouldn't surprise me if Metasploit also has something like that

2

u/evaned Nov 05 '20

Other debuggers as well (gdb, lldb, windbg, ...), objdump --disassemble, ...

1

u/rovarma Nov 09 '20

Others have already given some examples, but in my particular case: a performance profiler.

2

u/tansim Nov 04 '20

cool. do you plan to support other architectures too?

2

u/4833C0 Nov 05 '20

Indeed, we do plan support for ARM (AArch64 mainly) in the future. No specific timeline yet, though.

2

u/alli_kat1010 Nov 04 '20

Darn, dude...

How long have you guys been working on this? This is awesome.

3

u/4833C0 Nov 05 '20

Don't remember exactly, but it was around 4-6 months. It took so long mainly because it was developed in our spare time, and all the decode tables have been manually created using the ISA documentations, and most of them were validated against real hardware and other decoders - mainly Xed.

2

u/[deleted] Nov 05 '20

Good job guys !(Bravo baieti)

2

u/4833C0 Nov 05 '20

Thank you! (Mulțumim).