8 ms·
Things I learned while writing an x86 emulator (2023)
- deleted 2y ago[deleted]
- pm2222 2y agoPrior discussion here https://news.ycombinator.com/item?id=34636699 https://news.ycombinator.com/item?id=34636699 Cannot believe it’s been 16months. How time flies.
- AstroJetson 2y agoCheck out Justine Tunney and her emulator. https://justine.lol/blinkenlights/ https://justine.lol/blinkenlights/ The docs are an amazing tour of how the cpu works.
- trallnag 2y agoThat name, Tunney. Remember it from around 2014, being homeless, bumming around, and shit posting on Twitter about Occupy lol
- zarathustreal 2y agoAstonishing.. they never cease to amaze me
- sdsd 2y agoWhat a cool person. I really enjoy writing assembly, it feels so simple and I really enjoy the vertical aesthetic quality. The closest I've ever come to something like OP (which is to say, not close at all) was when I was trying to help my JS friend understand the stack, and we ended up writing a mini vm with its own little ISA: https://gist.github.com/darighost/2d880fe27510e0c90f75680bfee86b29 https://gist.github.com/darighost/2d880fe27510e0c90f75680bfe... This could have gone much deeper - i'd have enjoyed that, but doing so would have detracted from the original educational goal lol. I should contact that friend and see if he still wants to study with me. it's hard since he's making so much money doing fancy web dev, he has no time to go deep into stuff. whereas my unemployed ass is basically an infinite ocean of time and energy.
- changexd 2y agothank you for this, even though I took some time to understand what's going on which lead me to a series of cool(and very challenging) assembly journey, as a non CS major myself, this code here is a really nice entry for me to start understand how things work, I will definitely dig deeper.
- actionfromafar 2y agoYou should leverage that into your friend teaching you JS, maybe.
- djaouen 2y agoIt’s like my friend 0x86 always said: “Stay away from JavaScript. But stay away from TypeScript harder.”
- dmitrygr 2y agoI've written fast emulators for a dozen non-toy architectures and a few JIT translators for a few as well. x86 still gives me PTSD. I have never seen a messier architecture. There is history, and a reason for it, but still ... damn
- Arech 2y agoHaha, man, I feel you :DD You probably should have started with it from the very beginning :D
- jcranmer 2y ago> I have never seen a messier architecture. Itanium. Pretty much every time I open up the manual, I find a new thing that makes me go "what the hell were you guys thinking!?" without even trying to.
- snazz 2y agoWhat sorts of projects are you working on that use Itanium?
- jcranmer 2y agoNone, really. I just happened to get a copy of the manual and start idly reading it when my computer got stuck in a very long update-reboot cycle and I couldn't do anything other than read a physical book.
- deleted 2y ago[deleted]
- trealira 2y agoStudying the x86 architecture is kind of like studying languages with lots of irregularities and vestigial bits, and with competing grammatical paradigms, e.g. French. Other architectures, like RISC-V and ARMv8, are much more consistent.
- SunlitCat 2y agoHaha! Writing an x86 emulator! I still remember writing a toy emulator which was able to execute something around the first 1000-ish lines of a real bios (and then it stuck or looped when it started to access ports or so, can't remember it was too long ago and I didn't continue it as I started to get into DirectX and modern c++ more).
- aengelke 2y agoBonus quirk: there's BSF/BSR, for which the Intel SDM states that on zero input, the destination has an undefined value. (AMD documents that the destination is not modified in that case.) And then there's glibc, which happily uses the undocumented fact that the destination is also unmodified on Intel [1]. It took me quite some time to track down the issue in my binary translator. (There's also TZCNT/LZCNT, which is BSF/BSR encoded with F3-prefix -- which is silently ignored on older processors not supporting the extension. So the same code will behave differently on different CPUs. At least, that's documented.) Encoding: People often complain about prefixes, but IMHO, that's by far not the worst thing. It is well known and somewhat well documented. There are worse quirks: For example, REX/VEX/EVEX.RXB extension bits are ignored when they do not apply (e.g., MMX registers); except for mask registers (k0-k7), where they trigger #UD -- also fine -- except if the register is encoded in ModRM.rm, in which case the extension bit is ignored again. APX takes the number of quirks to a different level: the REX2 prefix can encode general-purpose registers r16-r31, but not xmm16-xmm31; the EVEX prefix has several opcode-dependent layouts; and the extension bits for a register used depend on the register type (XMM registers use X3:B3:rm and V4:X3:idx; GP registers use B4:B3:rm, X4:X3:idx). I can't give a complete list yet, I still haven't finished my APX decoder after a year... [1]: https://sourceware.org/bugzilla/show_bug.cgi?id=31748 https://sourceware.org/bugzilla/show_bug.cgi?id=31748
- __turbobrew__ 2y agoI know nothing about this space, but it would be interesting to hook up a jtag interface to a x86 CPU and them step instruction by instruction and record all the register values. You could then use this data to test whether or not your emulator perfectly emulates the hardware by running the same program through the emulated CPU and validate the state is the same at every instruction.
- saagarjha 2y agoNo need to JTAG; you can test most of the processor in virtualization. The only part you can’t check is the interface for that itself if you’re aiming to emulate it (most don’t). (Also I’m pretty sure the debugging interface is either fused off or locked out on modern Intel processors.)
- deleted 2y ago[deleted]
- mmm3 2y ago[flagged]
- was_a_dev 2y agoOff topic, but I like this blog style/layout. I can imagine it isn't everyones taste, but it just works for me
- timmisiak 2y agoGlad you like it. I used m10c, with a few tweaks: https://github.com/vaga/hugo-theme-m10c https://github.com/vaga/hugo-theme-m10c
- waynecochran 2y agoIntel architecture is loaded with historical artifacts. The switch in how segment registers were used as you went from real mode to protected mode was an incredible hardware hack to keep older software working. I blame Intel for why so many folks avoid assembly language. I programmed in assembly for years using TI's 84010 graphics chips and the design was gorgeous -- simple RISC instruction set, flat address space, and bit addressable! If during the earlier decades folks were programming using chips with more elegant designs, far more folks would be programming in assembly language (or at least would know how to).
- hajile 2y ago> I blame Intel for why so many folks avoid assembly language. x86 (the worst assembly of any of the top 50 most popular ISAs by a massive margin) and tricky MIPS branch delay slots trivia questions at university have done more to turn off programmers from learning assembly than anything else and it's not even close. This is one reason I'm hoping that RISC-V kills off x86. It actually has a chance of once again allowing your average programmer to learn useful assembly.
- tengwar2 2y agoPersonally I found 80286 and 80386 much easier than Z80.
- LegionMammal978 2y agoWhat do you find particularly problematic about x86 assembly, from a pedagogical standpoint? I've never noticed any glaring issues with it, except for the weird suffixes and sigils if you use AT&T syntax (which I generally avoid).
- deleted 2y ago[deleted]
- timmisiak 2y agoI suspect the biggest issue is that courses like to talk about how instructions are encoded, and that can be difficult with x86 considering how complex the encoding scheme is. Personally, I don't think x86 is all that bad as long as you look at a small useful subset of instructions and ignore legacy and encoding.
- trollied 2y ago> Writing a CPU emulator is, in my opinion, the best way to REALLY understand how a CPU works Hard disagree. The best way is to create a CPU from gate level, like you do on a decent CS course. (I really enjoyed making a cut down ARM from scratch)
- whobre 2y agoReading Petzold’s “Code” comes pretty close to, though and is easier.
- commandlinefan 2y agoOTOH, are you really going to be implementing memory segmenting in your gate-level CPU? I'd say actually creating a working CPU and _then_ emulating a real CPU (warts and all) are both necessary steps to real understanding.
- trollied 2y agoI agree.
- monocasa 2y ago> OTOH, are you really going to be implementing memory segmenting in your gate-level CPU? I have, but it was a PDP-8 which I'll be the first to admit is kind of cheating.
- mrspuratic 2y agoThis. I mean, why not start with wave theory and material science if you really want a good understanding :) In my CS course I learned a hell of a lot from creating a 6800 emulator; though it wasn't on the course, building a working 6800 system was. The development involved running an assembler on a commercial *nix system and then typing the hex object code into an EPROM programmer. You get a lot of time to think about where your bugs are when you have to wait for a UV erase cycle...
- commandlinefan 2y ago
- fjfaase 2y agoInteresting read. I have a lot of respect for people who develop emulator for x86 processors. It is a complicated processor and from first hand experience I know that developing and debugging emulators for CPU's can be very challenging. In the past year, I spend some time developing a very limited i386 emulator [1] including some system calls for executing the first steps of live-bootstrap [2], primarily to figure out how it is working. I learned a lot about system calls and ELF. [1] https://github.com/FransFaase/Emulator/ https://github.com/FransFaase/Emulator/ [2] https://github.com/fosslinux/live-bootstrap/ https://github.com/fosslinux/live-bootstrap/
- banish-m4 2y agoMost of the complexities lie in managing the various configurations of total system compatibility emulation, especially for timing, analog oddities, and whether to include bugs or not and for which steppings. If you want precise and accurate emulation, you have to have real hardware to validate behavior against. Then there are the cases of what not to emulate and offering better-than-original alternatives.
- Quekid5 2y agoJust as an adjacent aside from a random about learning by doing: Implementing a ThingDoer is a huge learning experience. I remember doing co-op "write-a-compiler" coursework with another person. We were doing great, everything was working and then we got to the oral exam... "Why is your Stack Pointer growing upwards"? ... I was kinda stunned. I'd never thought about that. We understood most of the things, but sometimes we kind of just bashed at things until they worked... and it turned out upward-growing SP did work (up to a point) on the architecture our toy compiler was targeting.
- boricj 2y agoIt's funny to me how much grief x86 assembly generates when compared to RISC here, because I have the opposite problem when delinking code back into object files. For this use-case, x86 is really easy to analyze whereas MIPS has been a nightmare to pull off. This is because all I mostly care about are references to code and data. x86 has pointer-sized immediate constants and MIPS has split HI16/LO16 relocation pairs, which leads to all sorts of trouble with register usage graphs, code flow and branch delay instructions. That should not be constructed as praise on my end for x86.
- astrange 2y agoYes, x86 is weird but the variable-length instructions are actually nice and easy to understand, once they're unpacked to text form anyway. The problem with them is they're insecure, because you can hide instructions in the middle of other instructions. I think the biggest thing you learn in x86 assembly vs C is that signed/unsignedness becomes a property of the operation instead of the type. It would be cool if you could use flags, which is easy/easier on some architectures like PPC/armv7, but x86 overwrites them too easily so it's too hard to use their values.
- jmspring 2y agoApparently my memory is false, I thought originally the salsa20 variants and machine code were on cryp.to in my memory, but Dan Berstein's site is - https://cr.yp.to/ https://cr.yp.to/ While at a startup when we were looking at data at rest encryption, streaming encryption and other such things. Dan had a page with different implementations (cross compiled from his assembler representation) to target chipsets and instruction sets. Using VMs (this was the early/mid 2000s) and such, it was interesting to see what of those instruction sets were supported. In testing, there would be occasional hiccups where an implementation wasn't fully supported though the VM claimed such.
- saagarjha 2y agoYou mean Dan Berstain’s site…wait.
- djaouen 2y ago“I don’t believe in emulatores.” - 0x86
- t_sea 2y ago> Writing a CPU emulator is, in my opinion, the best way to REALLY understand how a CPU works. The 68k disassembler we wrote in college was such a Neo “I know kung fu” moment for me. It was the missing link that let me reason about code from high-level language down to transistors and back. I can only imagine writing a full emulator is an order of magnitude more effective. Great article!
- astrange 2y agoI would say writing an ISA emulator is actually not helpful for understanding how a modern superscalar CPU works, because almost all of it is optimizations that are hidden from you.
- deleted 2y ago[deleted]
- lifthrasiir 2y agoI recently implemented a good portion of x86(-64) decoder for some side project [1] and kinda surprised how it got even more complicated in recent days. Sandpile.org [2] was really useful for my purpose. [1] Namely, a version of Fabian Giesen's disfilter for x86-64, for yet another side project which is still not in public: https://gist.github.com/lifthrasiir/df47509caac2f065032ef72e70f2ec05 https://gist.github.com/lifthrasiir/df47509caac2f065032ef72e... [2] https://sandpile.org/ https://sandpile.org/
- ale42 2y agoShouldn't it be (2023) rather than (2013)?
- saagarjha 2y agoYes. Should be fixed now
- Sparkyte 2y agoThe footnotes are glorious. "He was convinced that using a shift would work and didn’t believe me when I said it wasn’t possible."