<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Imm on Medium]]></title>
        <description><![CDATA[Stories by Andrew Imm on Medium]]></description>
        <link>https://medium.com/@andrewimm?source=rss-efa93207beac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FRY6qdpg0O8WFoVBKNEI_g.jpeg</url>
            <title>Stories by Andrew Imm on Medium</title>
            <link>https://medium.com/@andrewimm?source=rss-efa93207beac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:18:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewimm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing a DOS Clone in 2019, Part 2: The Kernel]]></title>
            <link>https://medium.com/@andrewimm/writing-a-dos-clone-in-2019-part-2-the-kernel-e9cc6a12f4de?source=rss-efa93207beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9cc6a12f4de</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Imm]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 17:45:10 GMT</pubDate>
            <atom:updated>2019-08-13T17:45:10.954Z</atom:updated>
            <content:encoded><![CDATA[<p>Following up <a href="https://medium.com/@andrewimm/writing-a-dos-clone-in-2019-70eac97ec3e1">on my first post</a>, this will be a deeper exploration of how the kernel of my DOS-compatible OS has been constructed.</p><p>A modern OS kernel needs to handle many things: memory paging, execution permissions, multitasking. Not DOS, though. It’s pretty much a file system implementation that can juggle multiple disks, with a few other bells and whistles bolted on. Instead, many of the challenges I’ve encountered involved understanding how the less-documented APIs should operate, and how to implement some of the more freewheeling data handling procedures in a safer, modern programming language.</p><h4>Code Structure</h4><p>My DOS kernel is divided into two distinct sections. First, there’s a block of setup code that runs at boot time. This initializes the hardware, drivers and file systems, and starts printing to the console. It then uses its own file system methods to find the command-prompt program, load it into memory, and begin executing it. The kernel will never return to this method. Child programs can trigger syscalls to get back into the kernel, but this entry function is now unreachable.</p><p>The majority of the kernel is the second section, which handles calls to the DOS API through <strong>int 21h</strong>, the software interrupt at 0x21. Programs that call into the API set different values into CPU registers to determine which system call is executed, and retrieve the response from DOS in other CPU registers.</p><h4>INT 21h</h4><p>Because high-level programming languages were invented to make code portable across different systems and architectures, they hide the raw CPU registers from you. You also can’t predict how an optimizing compiler will use registers to implement the code you’ve written. This presents some interesting challenges for entering and exiting the syscall handler.</p><p>The interrupt handler is implemented as a “naked” function. Normally, functions start with some manipulation of the system stack to consume arguments and prepare values that will be returned. A naked function has none of this, and guarantees that the registers are in the same state they were before we entered the interrupt.</p><pre>#[naked]<br>pub extern &quot;C&quot; fn dos_interrupt_handler() -&gt; ! {<br>  // declaring the function as #[naked] avoids any changes to<br>  // CPU registers when we enter<br>}</pre><p>The first thing we do in the interrupt handler is read every segment and register into a statically-addressable struct. It uses the asm! inline assembly macro to directly reference each of the registers. Stashing these values lets us restore all registers we might have touched before we return from the interrupt handler, so that the calling program can continue executing where it left off. It also allows us to reference these values from within Rust and determine which method to run, and which arguments to execute.</p><p>Actually doing this work requires a bit of juggling. As mentioned in the previous post, there are segment registers which change the starting point for the instruction pointer, stack, or data pointer. The kernel runs in a different segment from any calling program, so we can’t reference our register storage struct until we modify the data segment, DS. However, we also need to know what the data segment is so that we can use it to construct pointers coming from the caller. A bit of stack manipulation helps here, as long as we ensure that the stack pointer is restored before we return to the caller.</p><p>Here’s a simple example of one of the system calls. Function 0x1a takes the address stored in the DS and DX registers, and stores it as the pointer for the system’s Disk Transfer Area, a buffer used by certain file access methods. Accessing the REGISTERS object is considered unsafe because it’s a static mutable. In reality, this is a single-threaded environment that can read/write the variable without concern.</p><pre>0x1a =&gt; {<br>  // set DTA<br>  let segment = unsafe { REGISTERS.ds } as u32;<br>  let offset = unsafe { REGISTERS.edx &amp; 0xffff };<br>  globals::set_dta(Address::from_segmented(segment, offset));<br>},</pre><p>Its functional pair, method 0x2f, retrieves the DTA and puts it in the ES and BX registers:</p><pre>0x2f =&gt; {<br>  // get DTA<br>  let dta = globals::get_dta();<br>  let (segment, offset) = dta.as_segmented();<br>  // fetch the current register state<br>  let ebx = unsafe { REGISTERS.ebx };<br>  // store the segment and offset in ES:BX<br>  unsafe {<br>    REGISTERS.ebx = (ebx &amp; 0xffff0000) | offset;<br>    REGISTERS.es = segment;<br>  }<br>},</pre><p>At the end of the method, we use some more inline assembly to restore each of the registers and call the return-from-interrupt command.</p><h4>Drivers</h4><p>Whenever the system calls need to talk to hardware — like the console or a disk drive — they use a driver that knows how to talk to the device.</p><p>Early in its life, DOS was reorganized to support external drivers, since not all devices worked the same way. Your CONFIG.SYS file would declare which drivers to use with which physical devices, and how they should be configured.</p><p>DOS drivers are divided into two groups: block drivers that read or write chunks of data to devices like disks, and character drivers that read or write individual bytes to devices like the console or the printer. Even though they have different operation modes, they share many of the same read/write methods. Drivers provided one of the first levels of abstraction in DOS, allowing you to maintain a single API for a variety of devices.</p><h4>Polymorphism in Rust</h4><p>Rust doesn’t implement Object Oriented-style inheritance. Instead, structs can implement one or more interfaces, called Traits. Rather than inheriting from a single superclass, behaviors can be composed by implementing multiple Traits.</p><p>Traits are perfect for exposing a standard Driver interface. We cannot just write a method that accepts the Driver trait, though, since the implementation cannot be determined at runtime. In fact, I once managed to trick the compiler into letting me do this by unsafely casting a pointer, and my program ran off to some unintended location. We need something extra to implement polymorphism.</p><p>A common way to handle this in Rust is to pass a Box containing the object, but we can’t use Boxes because we don’t have a heap. An alternative is to annotate the type of our driver using an Enum, and disambiguate it at runtime using a match statement.</p><pre>enum Device {<br>  Block(&amp;mut BlockDriver),<br>  Clock(&amp;mut ClockDriver),<br>  Console(&amp;mut ConDriver),<br>  RAMDisk(&amp;mut RamDiskDriver),<br>}</pre><p>Calling a method on an ambiguous Device this way can get a bit repetitive, but it’s just explicitly annotating what some other languages implicitly do.</p><pre>fn read(dev: Device, bytes: u8) -&gt; u8 {<br>  match dev {<br>    Block(b) =&gt; b.read(bytes),<br>    Clock(c) =&gt; c.read(bytes),<br>    Console(c) =&gt; c.read(bytes),<br>    RAMDisk(r) =&gt; r.read(bytes),<br>  }<br>}</pre><p>Looking to the future, I’ll be able to support legacy DOS drivers by creating a bridge that maps my interface methods to their callsites using inline assembly.</p><h4>File Systems</h4><p>The file systems have been implemented in the same modular manner as device drivers. Right now there’s only a FAT-12 implementation, but this could be easily augmented with FAT-16 or EXT. Any time a file system call is made, the kernel checks the current disk to determine which file system and driver to use. This is implemented with a convenient method that takes a closure and passes the drive-specific data to it:</p><pre>io::with_drive_data(<br>  drive_number,<br>  |fs, device, disk_params| {<br>    // fs is the file system implementation<br>    // device is the disk driver<br>    // disk_params contains drive-specific data like sector size,<br>    // layout, volume name, etc<br>  }<br>);</pre><h4>File APIs</h4><p>On top of all these components, DOS is able to implement APIs for creating, opening, reading, and writing files.</p><p>Even a simple action like reading a file might touch three or four different locations on disk: drive parameters to locate sections of the disk, the parent directory to know how big the file is, the File Access Table to know where the file data is stored, and the actual location of the file content. Hiding this complexity from the running program is most of what DOS does.</p><p>There are actually two sets of DOS file APIs. The original APIs were designed for compatibility with other programs of the time, and used structures called <a href="https://en.wikipedia.org/wiki/File_Control_Block">File Control Blocks</a>. When the next version of DOS was released, it added support for Unix-like <a href="https://en.wikipedia.org/wiki/File_descriptor">file handles</a>. This means there are two complete sets of APIs for accessing files. This duplication of functionality, where an early API was introduced and later amended with a “better” alternative, is common throughout the DOS APIs.</p><h4>Halfway There</h4><p>With the ability to access hardware and navigate the file system, you could build out a command line to explore the file system, or something more complex like <a href="https://en.wikipedia.org/wiki/Norton_Commander">Norton Commander</a>. To take the kernel from being a utility to a full-fledged OS, we still need the ability to run other programs. The final post will cover how DOS divides up memory and executes programs, and how you can build DOS-style COM executables in Rust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9cc6a12f4de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a DOS Clone in 2019]]></title>
            <link>https://medium.com/@andrewimm/writing-a-dos-clone-in-2019-70eac97ec3e1?source=rss-efa93207beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/70eac97ec3e1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[retrocomputing]]></category>
            <dc:creator><![CDATA[Andrew Imm]]></dc:creator>
            <pubDate>Mon, 12 Aug 2019 15:45:49 GMT</pubDate>
            <atom:updated>2019-08-13T17:47:12.868Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was lucky enough to take a one-month sabbatical away from work. While I spent much of that time traveling and staying away from a computer, it’s hard for an engineer to turn off completely. If I was going to create something for amusement, it needed to be distinctly different from my day job. I ended up building a DOS-compatible OS straight out of the 80s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQPKvVBHBclhGyk9wOW6yg.gif" /></figure><p>Uh, what? Why?</p><p>I’ve always been a huge retro-computing nerd. After I began playing with writing emulators last year, I resurrected some of that fanaticism by building a series of MOS 65XX emulators — C64, Atari 2600, NES… Thinking about the internals of these systems led to reading about how early IBM PCs operated. Rather than taking on the significant task of building a PC emulator (I’ll admit, implementing processor instructions gets pretty sleepy after a while), I decided to write a DOS-compatible OS.</p><p>Here’s a quick primer/refresher on what DOS-compatible means. Back in the 80s, Microsoft had the most popular PC operating system: MS-DOS. While companies like Compaq built PC clones that were hardware-compatible with IBM’s computers, other companies built operating systems that were code-compatible with MS-DOS. Some added new competitive features, others were released with specific hardware in mind. As long as you implemented the same APIs as MS-DOS, software written for Microsoft’s OS would run on yours as well. This was important when folks in your office needed to run Lotus 1–2–3 on your off-brand system.</p><p>My first computer was a 486 PC that eventually ran DOS 6-point-something. While I wrote QBasic programs on that thing, I certainly didn’t write any assembly on it, let alone know what a syscall was. Implementing the DOS API was a deep learning experience through documentation often found in the older corners of the internet.</p><h4>So What’d I Build?</h4><p>After a month of off-and-on coding, here’s what I have at the time of writing: a kernel that implements about half of the extended DOS API; basic driver support for disk drives, the console, and the system clock; a FAT-12 filesystem implementation; a COMMAND.COM command prompt that leverages the DOS APIs to run basic internal commands, list directories, and execute other COM programs. Much of it is hacky and half-finished, but it achieves the initial goal of being able to run some made-for-DOS programs.</p><p>There’s still a LOT of work I hope to do: better directory support, handling multiple drives at once, piping and redirection, support for FAT-16 and maybe other filesystems, and a text editor. The good news is that after my initial experiments, I went back and restructured the core of the kernel to make it easier to switch between disks, drivers, and filesystems, so many of these things should be possible.</p><h4>Getting Real</h4><p>Pretty much every operating system tutorial today starts by getting your CPU out of <a href="https://wiki.osdev.org/Real_Mode">Real Mode</a>. Before processors implemented modern OS features like virtual memory and hardware protection, running code was a mad free-for-all where any program could overwrite anything in memory — this is known as Real Mode, and every processor in the x86 family starts off this way. You need to tell the processor to jump into Protected Mode before you can access more than 1 MB of memory or leverage any sort of memory safety.</p><p>The first versions of DOS were written for the Intel 8086, when Real Mode was the only mode. Through the entire life of MS-DOS, every version was implemented in Real Mode in order to maintain compatibility. As a result, my DOS was also going to need to be a Real Mode program, which flies in the face of all OS guides written in the last 30 years. There’s no paging, GDT, or rings where we’re headed.</p><p>One of the weirdest quirks of Real Mode is memory segmentation. Real Mode only uses 16-bit registers for memory addresses, but lets you access a lot more than 64 KB of RAM. This was achieved with a second set of registers called segments: one for code, one for data, and one for the stack. A full 1 MB of memory was addressable using a combination of a <strong>segment </strong>and an <strong>offset</strong>. The segment was shifted four bits and added to the offset to create a 20-bit address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vPjQaeYDJYXIWprH39-PbA.png" /></figure><p>Segmented addresses are represented using four hex digits for the segment, and four hex digits for the offset, separated by a colon: <strong>0x2020:4300</strong>. Since each segment is a 16-byte offset, there are many different ways to represent the same location. I’ll talk more about this when talking about executing programs within DOS, but for now I’ll say that dealing with segments is a huge pain when switching contexts. Unfortunately, the DOS APIs rely heavily on segments, so they’re unavoidable at certain points.</p><p>Once 32-bit processors were introduced, a full 4 GB was addressable without segmentation, and segments have pretty much been ignored since then.</p><h4>Booting Up</h4><p>Booting a PC started with a program called BIOS, which set up the processor and provided basic access to hardware. Nowadays most Intel-based computers use <a href="https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface">UEFI</a>, but it’s chronologically appropriate for our DOS to rely on BIOS. Before I picked up this project, I underestimated just how much functionality is provided by BIOS. When you’re in Real Mode, you can access a wide range of disk and video functionality through software interrupts.</p><p>When BIOS finds a bootable disk, it copies a small chunk of code from the first section of the disk to memory at the address <strong>0x7c00</strong> and begins running it. Ideally this code — the bootloader — will copy your operating system from disk into memory and jump to it.</p><p>My bootloader tries to copy much of what the original DOS systems did. They would load the first few chunks of the hardware drivers, <strong>IO.SYS</strong>, into memory. That first bit of <strong>IO.SYS</strong> would then load the rest of itself from disk, configure the system, load the OS kernel from another file, and finally start the command prompt. For the sake of simplicity, I’ve combined the drivers and kernel into a single executable, and just load the whole thing at once from the bootloader.</p><h4>The Kernel</h4><p>The main function of the kernel is to set up a system call API, which programs can call into and trigger some effect. There’s a lot of complexity under the hood to implement these system calls, but on the surface that’s basically all the kernel does. These system calls are triggered by calling software interrupt <strong>0x21</strong>, or as it was often written in code, <strong>int 21h</strong>. Depending on the values of other CPU registers at the time of the system call, DOS will determine which method to run.</p><p>Most of these system calls allow managed access to hardware, like displaying text, reading/writing from the filesystem, or allocating memory. A filesystem call may touch global kernel state, a filesystem implementation, and a physical device driver before it can do something like reading a file.</p><p>My kernel is implemented as a simple setup method that initializes all drivers and launches the command line, and a huge interrupt handler that forks depending on which method is called. It saves the state of all registers, runs the syscall, and restores the register state before returning control to the caller. Each interrupt call runs in isolation, so any shared state needs to be in a predictable memory location — no stack is shared between syscalls.</p><h4>Doing it with Rust</h4><p>My emulators have all been written in Rust, and it seemed like a good systems programming language for this project. For modern operating systems, Rust is a fantastic choice given its modern feature set and memory safety, but targeting the behavior of DOS is a different story. I would quickly discover that a lot of DOS functionality relies on unsafe behavior, and some standard functions can’t be made to work in a Real-Mode, static executable. Still, it ended up being a fun challenge to minimize the unsafe surface of the kernel and leverage as much idiomatic Rust as possible during this project.</p><p>My kernel started like many of the fantastic Rust OS tutorials out there: an executable built with no stdlib, no main, and an externally-located entry point:</p><pre>#![no_std]<br>#![no_main]</pre><pre>#[no_mangle]<br>pub extern &quot;C&quot; fn _start() {<br>  // kernel code here<br>}</pre><pre>// Also, we need to override panic behavior<br>#[no_mangle]<br>#[panic_handler]<br>fn panic(_info: &amp;PanicInfo) -&gt; ! {<br>  loop {}<br>}</pre><p>Much of the scaffolding for building a static target came from the first section of <a href="https://os.phil-opp.com/freestanding-rust-binary/">Philipp Oppermann’s thorough guide</a>, with some other pieces pulled in to make the executable run in Real Mode. I wrote a brief entry point in assembly that sets up the segment registers and stack before calling into the _start function.</p><p>The kernel and all sub-programs are built as static programs with no relocation. When a program is compiled down to assembly, the addresses of static data or functions need to be known at runtime. Modern executable programs can usually be run in any memory location because the host operating system performs extra setup or rewrites these addresses, but my kernel running with zero scaffolding needs to be static. This did leave to some unexpected challenges, chief among these being that I can’t use the built-in string formatting methods. I actually don’t want to use them — I’m trying to keep my kernel slim since there’s only 1 MB of total memory — but it means that code that might panic will not compile. This usually boils down to two different cases: indexing arrays/slices by a variable that might be out of bounds, or dividing by a variable that might be zero. This is addressed by adding bounds checks around such code, though, which isn’t such a bad thing. In the end, it’s like having a compile-time check for unsafe code, and who can complain about that?</p><p>During the development process, I also encountered a weird issue where code past a certain size was having trouble being statically linked — the linker refused to compute certain offsets. This ultimately derived from how the kernel was being built as an executable. Because everything is static, and I don’t rely on anything specific to executable formats, I actually don’t need the kernel to be an “executable.” I rejiggered the build scripts, compile the kernel as a static library, and everything works fine. I honestly don’t know enough about the LLVM linker to debug this further, but my current solution unblocked me for the moment.</p><h4>Stacks, Heaps, and Statics</h4><p>Much of Rust’s memory safety focuses on variables allocated on the stack, where they can be cleaned up when they move out of scope, and their ownership can be tracked. My kernel doesn’t use heap space or an allocator, because all objects I deal with are either “stack”-based objects that live for the entire lifetime of the kernel, or static objects with locations known at compile time.</p><p>Around the time DOS was written, assembly programs would outline areas of static memory that they would use to store variables. These could be initialized or uninitialized, but they needed to be known at compile time. This meant they couldn’t be variable-sized, but you could still do a lot with static objects and arrays. Between system calls the kernel needs to maintain some state, such as the current directory. In order to address them at predictable locations, I use a few static mut variables, the equivalent of the static memory areas from those original DOS versions. These are considered unsafe in Rust because they can’t be shared between threads, but in a single-threaded kernel they can be used without fear.</p><h4>Building the OS</h4><p>I’ve already mentioned a bit about how the kernel gets compiled from the Rust source, but I’ll explain it in more detail. The Rust code is compiled down to a static program, and combined with a simple assembly entry point using a linker script that throws out all the unneeded extras. The helper programs like the command line are also compiled and combined with their own assembly headers. A FAT-12 floppy disk image is initialized, and the bootloader is copied to part of the first sector of the disk. Finally, each of the system files are copied to the disk image using <a href="https://www.gnu.org/software/mtools/">GNU mtools</a>.</p><p>The floppy image is loaded up in QEMU, where the bootloader kicks off loading the kernel, drivers, and command prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HASHMAB-4FfWL_0EYqAkNQ.png" /></figure><h4>Up Next</h4><p>UPDATE: I’ve continued this post with <a href="https://medium.com/@andrewimm/writing-a-dos-clone-in-2019-part-2-the-kernel-e9cc6a12f4de">an exploration of the internals of the kernel</a>. Another post will discuss COM files, how they can be written in Rust, and how they’re able to call back into the DOS API.</p><p>Once I return to work and get approval to open up the source code, I’ll make the repo public as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70eac97ec3e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Game Boy Emulator in WASM, Part 1]]></title>
            <link>https://medium.com/@andrewimm/writing-a-game-boy-emulator-in-wasm-part-1-1ba023eb2c7c?source=rss-efa93207beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba023eb2c7c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Imm]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 18:35:59 GMT</pubDate>
            <atom:updated>2018-04-12T18:35:59.115Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, did you see that <a href="https://twitter.com/immediatedelay/status/979379609954222080">Game Boy emulator I wrote in WebAssembly and WebGL2</a>? That project was the result of my desire to build a non-trivial program with WebAssembly, and get an early understanding of the challenges that pop up when integrating with existing web tools. Now that the emulator has grown to the point where I can actually play games, I figure it’s time to share a bit about what I learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*7NtFM3EGYzZXtpvuRG-Azg.png" /></figure><p>This is the start of what I’m expecting will be four or five blog posts on the development process (including some WebVR stuff). While we’ll be discussing concepts in the context of an emulator, I’m hoping to be as general as possible when talking about things like interfacing between WASM and JS. Eventually I’ll cover how I implemented specific pieces like the Game Boy’s CPU, graphics unit, and audio by gluing together raw WASM code and modern web APIs.</p><p>In this first piece, though, let’s talk about why I thought this was a good application of WebAssembly, different ways to share data between WebAssembly and JS, and places where the WebAssembly development process still shows its immaturity.</p><p>Kicking things off, I want to make some clarifications about WebAssembly:</p><p><strong>WebAssembly isn’t magic unicorn glitter that makes everything fast.</strong></p><p>You can’t just sprinkle WebAssembly over your project to automatically make it faster. There are some applications where WebAssembly will be faster than JS might have been; there are also places where it might perform far worse.</p><p>One place where WebAssembly excels today is implementing routines that don’t allocate new memory. Consider an app that has a processing loop that runs once per frame, where you want to reduce the occurrence of garbage collection. If you want to do this in JS, you have to be clever about preallocating the right types of objects. Due to the nature of WebAssembly, you get this side-effect without thinking about it. This need comes up frequently in my WebVR work, which is why I’m excited about the potential for these new tools.</p><p><strong>WebAssembly isn’t a harbinger of the “closed web.”</strong></p><p>I sometimes see people worried that compiled source code will hurt the open nature of the web. But to be frank, I can’t remember the last time I clicked “View Source” on a web page and was presented with something readable. We’ve been uglifying the web for a long time, and it’s not borne out of anything sinister — it’s just the natural result of optimizing for performance.</p><p>If anything, WebAssembly opens up the web to more use cases. It’s a true compilation target for the web, allowing developers who don’t want to learn JS to take advantage of the web’s distribution power. Here’s a comment I made a few months ago at work during a discussion on the subject:</p><blockquote>The best magic about wasm is that it takes what makes the web great (being able to instantly download an “application” on demand) and improves it (reducing parse time, opening up the channels to more developers). A web-style on-demand experience is always going to beat something you have to intentionally download and keep around. It’s Netflix Streaming vs Blockbuster.</blockquote><p>As a side note, to maintain readability I wrote the JS parts of my emulator to not use any sort of compilation. Sure, it’s modern ES6, but it’s designed to run as-is. No transform step, no bundling, just a bunch of boring script tags containing IIFEs, like the good ol’ days.</p><p>Okay, with that out of the way, let’s talk about emulators!</p><h3><strong>Why I chose WebAssembly to build a Game Boy</strong></h3><p>An emulator is often simulating physical hardware and electronics in software, and in the case of the Game Boy most of the work involves dealing with 8-bit buses around (a variant of) <a href="https://en.wikipedia.org/wiki/Zilog_Z80">the Z80 CPU</a>. That means manipulating a lot of individual bytes, especially while navigating through huge banks of ROM and RAM. The Game Boy is a pretty simple architecture — getting button input requires reading specific memory addresses, writing pixels to the screen involves pushing bytes to specific places in VRAM.</p><p>Conceptually, this is exactly what WebAssembly does. It runs through a large ArrayBuffer, manipulating individual bytes as it executes. I could pre-define sections of this buffer to be my ROM and RAM, and easily read or write to them from both JS and WASM. In fact, any scenario that involves lots of byte manipulation or math (say, a video decoder) is a great use case for WebAssembly!</p><h3><strong>Why I chose Rust as a starting point</strong></h3><p>It’s not because Rust is new and hip, or even because I wanted to learn a new language. Actually, it’s as simple as the fact that Rust is one of the few languages that is currently capable of (easily) compiling straight to WASM through LLVM. As someone who used to write C for embedded systems, I’d be more than happy to have done everything in C99, but it seems like we’re still a few months away from that being an easy toolchain to set up.</p><p>When it comes to setting up Rust for compilation to WASM, the web has a number of conflicting guides that may have worked at one point but no longer do. That’s the risk of diving into something so new, the rules change quickly. As for my personal setup, I owe a huge debt of gratitude to Jan-Erik Rediger and his guides on <a href="https://www.hellorust.com/">hellorust.com</a>. I was able to install the nightly build of Rust, and compile a quick-and-dirty WebAssembly project. The next hurdle would be figuring out how to get it to play nicely with JS.</p><h3>JS &lt;-&gt; WASM Interop</h3><p>One of the challenges of building with WebAssembly is sharing data between your JS and your WASM code. Due to the nature of WebAssembly at this point in time, you can’t pass arbitrary JS objects to it. Instead, you’re basically limited to passing numbers back and forth. While this sounds incredibly constraining, this is more-or-less how all high-level programming languages, including JS, are implemented deep down. Those numbers can be pointers into a block of memory where you have encoded some higher-level data structure. JS can send a complex object by writing it to a location in the buffer, and transferring that location to some WASM code that knows how to read that object back out. Projects like <a href="https://github.com/rustwasm/wasm-bindgen">wasm-bindgen</a> have been started to simplify a lot of that work for developers.</p><p>I didn’t use any object-embedding logic, though. Nearly all of my execution is done on the WASM side. I really just rely on JS to call my code at a pre-defined pace using a requestAnimationFrame loop, and occasionally listen for input events. Even so, I still had to solve some architectural challenges on the WASM side.</p><p>The simplest way to write the behavior I described is to have WASM expose an init() method to allocate global state, and a frame() method to update it. However, given the way Rust works, it’s difficult to maintain that global state between different external method calls. Instead, my solution was to return a pointer to that state from the init() call, and pass it to every method like frame(). That way, those methods know where to find the object to operate on, while keeping Rust’s memory checker happy.</p><p><strong>Example from the JS side:</strong></p><pre>// WASM init logic, abridged<br>fetch(&#39;path/to/gb.wasm&#39;)<br>  .then(res =&gt; res.arrayBuffer())<br>  .then(bytes =&gt; WebAssembly.instantiate(bytes, { /* imports /* }))<br>  .then(result =&gt; {<br>    const exports = result.instance.exports;<br>    return {<br>      memory: exports.memory,<br>      createVM: exports.create_vm,<br>      frame: exports.frame,<br>      // ...<br>    };<br>  })<br>  .then(wasm =&gt; {<br>    // create a pointer to an allocated VM object<br>    const vm = wasm.createVM();<br>    // update the instance, ideally once per frame<br>    wasm.frame(vm);<br>  });</pre><p><strong>Example from the Rust side:</strong></p><pre>#[no_mangle]<br>pub fn create_vm() -&gt; *mut VM {<br>  let vm = VM {<br>    // init the struct<br>  };<br>  // allocate the object on the heap, and get a raw pointer to it<br>  let b = Box::new(vm);<br>  return Box::into_raw(b);<br>}</pre><pre>#[no_mangle]<br>pub fn frame(raw: *mut VM) {<br>  unsafe {<br>    let mut vm = Box::from_raw(raw);<br>    // update the vm<br>    // ...<br>    // forget this, to ensure our object isn&#39;t deallocated<br>    mem::forget(vm);<br>  }<br>}</pre><p>This method of passing back pointers to JS is also useful for debugging, and necessary for some I/O behavior implemented on the JS side. For instance, when the emulator boots up, I export a pointer to the location of the ROM memory that has been allocated by Rust/WASM. When a user uploads a Game Boy ROM file, I copy the data byte-by-byte into that buffer, so that the WASM code can execute it. When I was debugging the emulator, I found it necessary to inspect the emulator’s memory after each instruction. By exporting the pointer to the RAM table, I could create a Uint8Array at that location and inspect it byte-by-byte.</p><pre>const ramPtr = wasm.getRamPointer(vm);<br>const buffer = wasm.memory.buffer;<br>const ram = new Uint8Array(buffer, ramPtr, RAM_SIZE);<br>// Inspect or modify individual byte elements</pre><h3>Growing pains</h3><p>Once the pointer sharing was sorted out, I pretty much stopped fighting Rust and everything Just Worked™. However, I did uncover one major challenge of developing with Rust and WASM: the debugging story. On the WebAssembly side of things, if something goes wrong, you can often encounter a vague memory error. Chrome and FireFox both provide handy debuggers that display your WebAssembly in its human-readable format, but there’s no way to determine which piece of your Rust code was compiled into that particular bit of WASM.</p><p>There are <a href="https://github.com/WebAssembly/design/blob/master/FutureFeatures.md#source-maps-integration">future plans to implement source maps</a>, which would be a huge development boost, but in the meantime you’re left finding another way around this. My strategy was a mix of unit tests (probably a good thing) and a secondary build target that ran my emulator natively (definitely some extra work, but fun to have). With the second, I was able to run line-by-line debugging with lldb to track down most issues.</p><p>I’m a bit ashamed to admit that another recurring cause of these inscrutable error messages was simply forgetting to pass the VM pointer to my WASM methods. There’s a market out there for someone who wants to build a tool that generates Typescript/Flow bindings out of Rust code, and keep developers like me from making dumb mistakes.</p><h3>Architecture of the emulator</h3><p>As I mentioned earlier, I wanted to keep as much logic in the WASM side as possible. The two exceptions are the graphics logic, which was implemented as a series of WebGL shaders that read raw bytes from VRAM, and the audio system, which uses a JS AudioContext.</p><p>Within a given frame, here’s everything that occurs:</p><ul><li>The JS code copies the current button state to locations where the WASM code can read them.</li><li>JS calls into WASM to execute one full frame, which runs as many CPU instructions as it can before the VSync event occurs (screen has finished drawing, in the original GB hardware).</li><li>If, during the execution of those instructions, any audio changes are triggered, the WASM code calls back to JS to manipulate the AudioContext.</li><li>Finally, the raw video memory is fed to the WebGL program, which draws the screen for that frame.</li></ul><p>From there, it’s easy to layer on a bunch of extra features, such as periodically copying Save RAM to IndexedDB so you can save your progress, enabling VR mode, or simply pausing the audio when the tab loses focus. All in all, it’s about 7K lines of Rust which compile to a 70Kb WASM bundle. Not bad, considering most Game Boy games are bigger than that.</p><p><strong>Coming soon:</strong> posts on simulating the Game Boy’s CPU in Rust, implementing the graphics unit with a series of WebGL 2.0 shaders, and how to add a WebVR mode to any project that already renders to a canvas.</p><p>I’ll have the code up on GitHub in the next few days. Just a few i’s to dot and t’s to cross before it’s good to go, keep an eye out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba023eb2c7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>