<?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 Dchampz on Medium]]></title>
        <description><![CDATA[Stories by Dchampz on Medium]]></description>
        <link>https://medium.com/@davewritescode?source=rss-360abb95e17a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*09RSuctEOl5BAUYfRY5xHA.png</url>
            <title>Stories by Dchampz on Medium</title>
            <link>https://medium.com/@davewritescode?source=rss-360abb95e17a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:58:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davewritescode/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[Let’s Have Fun With Interpreters and Bytecode VMs — Chapter 3]]></title>
            <link>https://medium.com/@davewritescode/lets-have-fun-with-interpreters-and-bytecode-vms-chapter-3-f2392de2e269?source=rss-360abb95e17a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2392de2e269</guid>
            <category><![CDATA[emulator]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[emulation]]></category>
            <dc:creator><![CDATA[Dchampz]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 01:56:37 GMT</pubDate>
            <atom:updated>2019-01-15T16:53:13.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Have Fun With Interpreters and Bytecode VMs — Chapter 3</h3><p>Our First VM</p><p><a href="https://medium.com/@davewritescode/lets-have-fun-with-interpreters-and-bytecode-vms-chapter-1-7876ade6bb5c">Part 1 — Prelude, Chip8 Intro, Opcodes</a></p><p><a href="https://medium.com/@davewritescode/lets-have-fun-with-interpreters-and-bytecode-vms-chapter-2-1f6849bb1b55">Part 2 — Disassembly, Disassembler</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G4L5yB-YLs4-eFAK" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s start today by going over some terms.</p><p>In the previous articles, as we’ve explored the building blocks of the Chip8, we’ve referred to interpreters and virtual machines, bytecode and opcodes. Before proceeding, it will be good to get a solid understanding of what it is exactly that we’re building. This will require wading through some history of computing, but I am going to keep this <em>brief </em>and a bit cavalier<em>.</em> The goal is to get to a place of confidence when we use the above terms instead of arriving at hand-wavy definitions and moving on.</p><h4>Run Time</h4><p>Perhaps you’ve heard this term before in reference to compiled languages or in OS-specific terms (such as Windows RunTime Library). Our story starts with the Run Time.</p><blockquote>So what the heck is a Run Time anyway?</blockquote><p>In the first part of this series I casually touched upon the pros and cons of bytecode interpreters saying,</p><blockquote>Bytecode interpreters will never be as performant as machine code…</blockquote><p>But let’s actually explore this concept for a minute or two.</p><p>In 2019, almost no one is writing assembly, especially for the common applications we know and love — <a href="http://flint.cs.yale.edu/cs421/papers/x86-asm/asm.html">though it’s certainly possible</a>. There are still use-cases for getting your hands dirty and writing some assembly, but they’re not important right now.</p><p>Of course, that doesn’t mean that every program written in the last decade takes a similar performance hit. Standing apart from the languages we mentioned before (and others, such as C#) that compile programs to bytecode, are the languages that are compiled directly to native machine code.</p><p>Take for example: Rust. When we write and compile a program in Rust, we target some machine and compile it into code that is compatible with the target. The job of the Rust Compiler is to take the source code that we’ve written and translate it to machine code that can be mainlined straight into the target machine’s CPU.</p><p>That’s not exactly the whole story though. There are many concepts in higher-level languages that simply have no one-to-one machine code representation. The compiler knows about these operations, and takes the necessary steps to produce the machine code from these higher-level concepts. But like every other thing in life: convenience costs someting. We pay for expressiveness with the volume of machine code generated.</p><p>Let’s imagine a new language that compiles to a target machine which has no single operation to perform division. When our high-level language uses something like let a = b / c we would ideally want to produce some single machine operation such as DIV B, C — but we can’t, because our target machine doesn’t have the raw capability to do that. Instead, we would need to generate a sequence of machine code instructions to perform the resulting division call. Imagine now, that our program (though short in the source) performs division operations all over the place. The resulting machine code balloons as we pile on more and more division operations.</p><p>Compiler developers for our imaginary language take notice of these gargantuan binaries and start to wonder how to fix this problem. Then one day, some engineer wonders to herself, “what if I were to write a subroutine in assembly that performed this division operation? Then we could include this subroutine in any program that uses division and reference it any time a division operation is performed.”</p><p>She cracks her knuckles, busts out some assembly, alters the compiler to reference this subroutine and <em>BAM — </em>you’ve got your first Run Time Library.</p><blockquote>Note: this is obviously an extreme over-simplification to illustrate the fundamentals of the process.</blockquote><p>Now, when we compile our division-heavy program instead of getting a bunch of machine-code division sequences that produces the resulting high-level division concept, we get JSR Divide. Introducing these few extra bytes in the form of a subroutine, we are able to cut out all of the extra bytes of the division sequence generated in the machine code.</p><h4>Interpreter</h4><p>Let’s now imagine a new generation of the same compiler engineers from earlier.</p><p>As time has progressed, they’ve fallen in love with this concept of the run time. They start to expand it in many directions to allow for even more expressive higher-level operations to be condensed into terse machine code. This continues on and on until one day, another engineer starts pondering the original division problem.</p><p>This problem is derived from intrinsic limitations that exist in the hardware. The target machine had no hardware capable of performing division. It had a means to get to the resulting expression, but no direct one-to-one corollary. So what this especially clever engineer had done way back in the day was to create a subroutine that <em>simulated</em> an operation that the target hardware lacked.</p><p>Our present day engineer has of-late been preoccupied with what the run-time library has become and the resulting size and complexity of it all. Particularly attractive is this idea of hardware simulation. “Since the runtime has become so complex, why not simulate <em>all</em> of the hardware,” she thinks. “I can write a subroutine for each instruction and then call it whenever I encounter the corresponding code in the source.”</p><p>What this engineer has done is take the concept of a runtime library and enhanced it to full-blown software — which is known as an interpreter. When I want to run the program written in the source code, I run the interpreter and feed it the source code. Now, no machine code is generated at all. Instead, the interpreter encounters instructions and calls corresponding subroutines.</p><p>This is where the concept we opened with in Chapter 1 was born. Why would we want to do this in the first place? Portability. Instead of compiling source code for distribution, we compile interpreters. One interpreter compiled for specific hardware runs <strong>any</strong> source-code without the end user or programmer having to worry much at all.</p><h4>Virtual Machine</h4><p>Our compiler engineers have thus far devised two ways of running the same program: one in which source code is compiled down into machine code for some specified hardware and another where some source <em>is</em> the machine code for some specified software.</p><p>The software in this sense is a computer in of itself, performing operations defined in the source by calling subroutines.</p><p>But as we’ve already experienced first hand, we can take this a step further. Now that we have an interpreter that can run any high-level source on a target hardware, we can imagine an intermediate representation. What if we were to devise something more compact when compared to the high-level source, but still more abstract than when compared to machine code.</p><p>We’ve now arrived now at Byte Code. When an interpreter is consuming this intermediate representation, we typically refer to this as a Virtual Machine.</p><p>The virtual machine takes the best of both worlds: we approach similar levels of efficiency and speed that we get from machine code, with the portability we get from interpreted languages.</p><h3>The Chip8</h3><p>So — with all of this in mind — what is it <em>exactly</em> that we are creating when we create a Chip8 emulator?</p><p>In short, a Virtual Machine that interprets bytecode defined as the Chip8 Programming Language. This means that there is no higher-level source code to compile down to bytecode, the bytecode itself is the abstraction. <strong>Do note, however, that this is not to say <em>there can be no higher-level source code</em>. Just that none is defined.</strong></p><p>Our task is to write some software that takes the Chip8 bytecode and produces expected results — or a Chip8 bytecode interpreter. But at the same time we’ll need to simulate the environment in which the Chip8 bytecode expects to be run, which is defined in the specifications. This includes memory, registers, input, display and sound.</p><p>Let’s start out with a demo today:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fdpchamps%2Fembed%2Fpreview%2FBvvRmr%3Fheight%3D600%26slug-hash%3DBvvRmr%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fdpchamps%2Ffull%2FBvvRmr&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/a70c4c2a2a16da9d5d3461f1bcc3d908/href">https://medium.com/media/a70c4c2a2a16da9d5d3461f1bcc3d908/href</a></iframe><pre>Controls:<br>q - move left<br>w - fire<br>e - move right</pre><pre>esc - reset<br>p - pause / resume program, show assembly info<br>space - (while paused) step through program.</pre><h4>Memory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*qREUB9dY7VcBFGIu6B7U2w.png" /></figure><p>The Chip8 VM has commands 4,096 bytes of addressable memory.</p><p>Of which, the first 512 bytes are reserved for the interpreter.The remaining 3,583 bytes is considered valid program space.</p><p>Additionally, the Chip8 has access to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*C5LjUO0DllrUkUm2Gjs-wQ.png" /></figure><ul><li>A 16-bit Program Counter</li><li>An 8-bit Stack Pointer</li><li>A 32-byte stack ( sixteen 2-byte values)</li><li>Sixteen 8-bit registers</li><li>Two 8-bit timers (sound, delay)</li><li>A 16-bit index register</li><li>A 256-byte frame buffer</li></ul><p>In order to implement a Chip8 VM to specification, we will need to account for all of these properties in a semi accurate way.</p><p><em>A note on accuracy: since we’re implementing this in Javascript, there’s a limit to how close we can get to this specification. We can take advantage of typed arrays and create data structures to represent these ideas in spirit, but we are ultimately at the mercy of the Javascript VM. For instance, Javascript is dynamically typed — the variables we use are not directly associated with the values they represent. There’s also only one type of number: double-precision 64-bit binary. We’re about as far away from the metal as we can get.</em></p><p><strong>Overview of parts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4glf3y1gqvOyMLSme06g3g.gif" /><figcaption>So what do all of these things do anyway?</figcaption></figure><p>We will be creating a very rudimentary implementation of the <a href="https://en.wikipedia.org/wiki/Instruction_cycle">fetch-decode-execute cycle</a>, of which the above parts are closely related.</p><ol><li>The program counter contains the the address of the instruction that will be executed next.</li><li>The index register contains the address of some block of memory (for drawing sprites, for instance).</li><li>The stack is an array of sixteen 2-byte values and contains addresses for the interpreter to refer to. This is used for subroutines.</li><li>The stack pointer determines the current level of the stack.</li><li>Registers 0 — E are general purpose 8-bit storage registers, used for storing values immediately available to the CPU.</li><li>Register F is special in that it is specifically used as a flag for some instructions, for determining borrows or collision for example.</li><li>The frame buffer directly translates to a 64×32 display where each bit represents 1 monochrome pixel.</li></ol><blockquote>�👏👏�Excitement Intensifies</blockquote><p>In addition to the above: there are two flags: draw and sound. When set, the chip signals that it’s time to draw or make a sound.</p><p>With all of that info, we are READY to start our Chip8.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b46c37ffb977e65bd8cc8e94b1b625b/href">https://medium.com/media/7b46c37ffb977e65bd8cc8e94b1b625b/href</a></iframe><blockquote>What about the opcodes?</blockquote><p>Remember before, when our second clever engineer said,</p><blockquote>“I can write a subroutine for each instruction and then call it whenever I encounter the corresponding code in the source.”</blockquote><p>Well, this is our job. For each opcode, we need to implement a method. There are many ways to do this. For example, because there’s so few opcodes for the Chip8, we could organize them under one giant switch statement. But I would discourage you from doing so.</p><p>Instead, a cleaner technique involves (loosely) organizing the methods under their parent operations (math, display, flow etc..). We may then associate them through either an array, or (for maximum ease) an object.</p><p>The method names can either be a direct corollary to their opcode (mvi, draw etc…) or more descriptive (e.g, jumpToSubroutine).</p><p>I use both depending on the operation, here’s a cohesive example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb572e6321752a9ca5d7410e99762ab/href">https://medium.com/media/ffb572e6321752a9ca5d7410e99762ab/href</a></iframe><p>We do this for every single opcode.</p><h3>The draw method</h3><p>Probably the number one pain point for Chip8 implementations is the draw method so let’s actually dig into it.</p><p>DXYN — DRAW Register X, Register Y, N <br>When the interpreter encounters the Draw subroutine, it will read the values stored in Register X and Register Y and draw a sprite to the screen at that location with N-height.</p><p>Recall that: The index register contains the address of some block of memory.</p><p>Index Register to Index Register + N defines the sprite we want to draw. Each byte in memory in this range is a <strong><em>ROW</em></strong>, Each bit in every byte is a <strong><em>COLUMN.</em></strong></p><p>That means all sprites are 8 columns wide, and can be at most 16 rows high.</p><p>Let’s take a look at our fontset:</p><pre>0xF0, 0x90, 0x90, 0x90, 0xF0, // 0<br>0x20, 0x60, 0x20, 0x20, 0x70, // 1<br>0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2<br>0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3<br>0x90, 0x90, 0xF0, 0x10, 0x10, // 4<br>0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5<br>0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6<br>0xF0, 0x10, 0x20, 0x40, 0x40, // 7<br>0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8<br>0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9<br>0xF0, 0x90, 0xF0, 0x90, 0x90, // A<br>0xE0, 0x90, 0xE0, 0x90, 0xE0, // B<br>0xF0, 0x80, 0x80, 0x80, 0xF0, // C<br>0xE0, 0x90, 0x90, 0x90, 0xE0, // D<br>0xF0, 0x80, 0xF0, 0x80, 0xF0, // E<br>0xF0, 0x80, 0xF0, 0x80, 0x80  // F</pre><p>A font sprite is 5-bytes long, meaning 5 a character is rows high. Fonts, like all sprites are 8 columns wide. Let’s visualize a couple through their binary representation:</p><pre>//&quot;0&quot;<strong><br>1111</strong>0000 //0xF0<br><strong>1</strong>00<strong>1</strong>0000 //0x90 <br><strong>1</strong>00<strong>1</strong>0000 //0x90<br><strong>1</strong>00<strong>1</strong>0000 //0x90<br><strong>1111</strong>0000 //0xF0</pre><pre>//&quot;E&quot;<strong><br>1111</strong>0000 //0xF0<br><strong>1</strong>0000000 //0x80<br><strong>1111</strong>0000 //0xF0<br><strong>1</strong>0000000 //0x80<br><strong>1111</strong>0000 //0xF0</pre><p>Here’s two helpful equations for working with 1d / 2d arrays:</p><pre>//x,y to index<br>i = x + width*y; </pre><pre>//index to x, y<br>x = i % width;   <br>y = floor(i / width);</pre><p>And here’s what an outline of the draw method might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d81e185d105fc13f0324a52d311f64/href">https://medium.com/media/82d81e185d105fc13f0324a52d311f64/href</a></iframe><p>Finally, <strong>and importantly:</strong> if a pixel is going from 1 to 0, set Register F to 1 otherwise set it to zero. This is how we will perform collision detection.</p><h4>Pro tip: take this slow, reference multiple sources (there’s plenty out there). Write unit tests for each opcode method.</h4><p>Though writing unit tests for each method might seem gruelling, it will force you to pay attention to the rules you’re implementing. You will almost certainly not implement every opcode correctly on your first go. When the inevitable bugs do arise, look at your unit tests and compare them to the specification.</p><p>With this knowledge, I send you on your way to write the Chip8 Emulator in full.</p><blockquote>Wait… that’s it?!</blockquote><p>This is, essentially, all we need to know. We’ve diagrammed and dug into the specifications, talked about the theory and the instruction set, talked through some example opcodes. Now it’s just time to build it.</p><p>I’ve intentionally left some information out (such as cycle timing and peripheral specifications). This is a learning process, the more you can do through discovery, the better you will learn for yourself. I implore you to get through as much of it on your own as you can, <a href="https://github.com/dpchamps/chip8Emulator/tree/Chapter3/src/emulator">but feel free to cross reference this repo here.</a></p><h3>Up Next</h3><p>Now that we have a working disassembler and fully functioning emulator, the next logical step is be to craft an assembler.</p><p>We will begin by discussing the very basics of lexing and parsing, move on to assembling the disassembly we already have and discuss strategies to represent variables in a more rich form of disassembly.</p><p>At the end of next chapter, we’ll write our very own Chip8 Program.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2392de2e269" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Have Fun With Interpreters and Bytecode VMs — Chapter 2]]></title>
            <link>https://medium.com/@davewritescode/lets-have-fun-with-interpreters-and-bytecode-vms-chapter-2-1f6849bb1b55?source=rss-360abb95e17a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f6849bb1b55</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[emulation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Dchampz]]></dc:creator>
            <pubDate>Fri, 28 Dec 2018 18:05:49 GMT</pubDate>
            <atom:updated>2018-12-28T18:07:29.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Have Fun With Interpreters and Bytecode VMs — Chapter 2</h3><p><a href="https://medium.com/@davewritescode/lets-have-fun-with-interpreters-and-bytecode-vms-chapter-1-7876ade6bb5c">Part 1 — Prelude, Chip8 Intro, Opcodes</a></p><p><a href="https://github.com/dpchamps/chip8Emulator/tree/Chapter2">Tagged repo with the complete code from this chapter</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltWat_C0M_9jYjflSCShiw.jpeg" /></figure><p>Previously, we went over the what and why of interpreters, met the Chip-8 virtual machine and learned about opcodes.</p><p>We started by coming up with a solution to a straightforward question: How can I translate any given opcode into a more readable representation of what it does? This process of translating opcode (or machine code) into a very low-level, human-readable representation is known as <em>disassembly.</em></p><p>What we’re looking at when we see something like MOV $3 FFh is known as <a href="https://en.wikipedia.org/wiki/Assembly_language">assembly language</a>, and a program that translates all or part of another program written in bytecode is called a <em>disassembler.</em></p><p><strong>Our next goal then is to write a disassembler.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dbLyf5k9swHlk22QyDfkBQ.gif" /></figure><p>You might be thinking to yourself, “well we <em>already have</em> the disassembler.” Because we already have the ability to translate arbitrary bytecode into assembly.</p><p>Given some program as input, all we need to do is walk the buffer and disassemble the opcodes, right?</p><h3>The Naive Approach</h3><pre>const <em>getOpcode </em>= (high: number, low: number = 0): number =&gt; {<br>    return (high &lt;&lt; 8) | low;<br>};<br><br>const <em>disassemble </em>= (program: Uint8Array): string =&gt; {<br>    const output = [];<br><br>    for (let i = 0; i &lt; program.length; i += 1) {<br>        const Opcode = new Opcode(<br>            <em>getOpcode</em>(program[i], program[i + 1])<br>        );<br>        output.push(Opcode.toString());<br>    }<br><br>    return output.join(&#39;\n&#39;);<br>};</pre><p>This code will definitely produce something readable, and may even be runnable. But before we get to the output of <em>disassemble</em>, let’s modify our Opcode class to include labels.</p><blockquote>Labels, you say?</blockquote><p>The idea here is that when we perform jumps, via JSR or JMP, we’ll be specifying some address space to jump to. Something like JSR 3ADh , which says, <strong>set the program counter to memory location 0x3AD.</strong></p><p>Instead of specifying a location in memory, it would be much cleaner to write and read something like,</p><pre>JSR :my-subroutine<br>XOR $0, $1 <br>JMP :my-jump<br>:my-subroutine<br>MOV $0, 1h<br>MOV $1, 2h<br>DRAW 0h, 1h, 6h<br>RET<br>:my-jump</pre><p>So what’s the bare minimum we need to be able to add this feature to our opcode class? Let’s revisit the idea of tokens for a moment: we’ve seen so far the Instruction, Integer and Register types.</p><p>What is a register or integer token?</p><pre>const regToken = new Token(TokenType.REGISTER, 0xB);<br>const intToken = new Token(TokenType.INTEGER, 0x10);</pre><pre>console.log(regToken) // $B<br>console.log(intToken) // 10h</pre><p>The token class represents values dependant on what type of token in passed in. The register token has the <strong>$</strong> character prepended, while the integer token has the <strong>h</strong> character appended. Both are represented in hexadecimal.</p><p>If we want to add labels to our disassembly, we’ll need to create a new token type, called LABEL. <em>(You may remember from the code last time that we already have this type, along with EOF, COMMENT and VOID).</em></p><p>Associated with a label will be the <strong>: </strong>character:</p><pre>const labelToken = new Token(TokenType.LABEL, &#39;my-label&#39;);</pre><pre>console.log(labelToken) //:my-label</pre><p>These are the necessary changes we’ll need to make to our Opcode class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20de6ac7b6c63eb9ec2b953d5c2d63d0/href">https://medium.com/media/20de6ac7b6c63eb9ec2b953d5c2d63d0/href</a></iframe><p>Seeing as we’re disassembling bytecode, we don’t have the luxury of knowing what labels used to exist. So the best we can do is is create a generic label-&lt;address being branched&gt;. While we’re at it, let’s add the concept of a ‘strict’ opcode. This will help us with testing, and compilation further down the road. If passed false as a second constructor argument, any invalid opcode will be interpreted as a NOOP — or no-operation — instruction.</p><p>The Chip-8 specification states that most programs start at address space 0x200. We’ll be designing our emulator to this specification: anything sub 0x200 will be reserved for the interpreter. Knowing this, we can add an address to our above <em>disassemble</em> method by offsetting the current opcode index by 0x200:</p><p>Finally, we’ll need to keep track of opcodes with labels and the addresses to which these labels belong. We can achieve this by keeping a map of addresses to labels, and then looping through the entries after we’ve disassembled the entire program:</p><pre>const <em>disassemble </em>= (program: Uint8Array): string =&gt; {<br>    const output: Map&lt;string, string&gt; = new <strong><em>Map</em></strong>();<br>    let labels: Map&lt;string, Token&gt; = new <strong><em>Map</em></strong>();<br><br>    for (let i = 0; i &lt; program.length; i += 2) {<br>        const address = i + 0x200;<br>        const opcode = new Opcode(<br>            <em>getOpcode</em>(program[i], program[i + 1]),<br>            false<br>        );<br>        if (opcode.label)<br>            labels.set(opcode.bytes.nnn.toString(), opcode.label);<br><br>        output.set(<br>            address.toString(), <br>            `${opcode.toString()} ;${address.toString(16)}`<br>        );<br>    }<br><br>    <strong><em>Array</em></strong>.from(labels)<br>        .forEach(([address, labelToken]: [string, Token]) =&gt; {<br>            const disassembly = output.get(address);<br>            output.set(address, `${labelToken}\n${disassembly}`);<br>        });<br><br>    return <strong><em>Array</em></strong>.from(output.values()).join(&#39;\n&#39;);<br>};</pre><p>Let’s examine some portions of the pong2 rom:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd4edb9a55d2456798fcac12c8ce9af7/href">https://medium.com/media/cd4edb9a55d2456798fcac12c8ce9af7/href</a></iframe><p><strong><em>Awesome</em></strong>! Let’s take a moment to congratulate ourselves and look through the pong disassembly. We can see subroutines and branches in (relative) action. We’ve also got the addresses where the opcodes occur to further help us break down what’s going on inside the program.</p><p>If we were to reassemble the above program as is, we would get a playable pong.</p><blockquote>🤔 What’s the catch.</blockquote><p>Yeah, we’re not finished. Because our disassembler works… but only sometimes and by accident. Let’s take a look at the first few lines of disassembly from another program we’ve seen before, missile.c8:</p><pre>JMP   :label-0x0219        ;200<br>SKNE  $D, 49h              ;202<br>SKEQ  $3, $5               ;204<br>SKNE  $9, 4Ch              ;206<br>SKNE  $5, 20h              ;208<br>MOV   $2, 79h              ;20a<br>JSR   :label-0x0044        ;20c<br>MOV   $1, 76h              ;20e<br>MOV   $9, 64h              ;210<br>JSR   :label-0x0057        ;212</pre><p>Uh oh. This first jump takes us to a non-even address space. What follows isn’t very pretty either, we apparently have two more jumps taking us into sub 0x200 memory space and an unusual four skip branches in a row. That can’t be right. Finally, towards the end of the output we have a bunch of empty labels:</p><pre>:label-0x0219</pre><pre>:label-0x0044</pre><pre>:label-0x0057</pre><pre>... and so on ...</pre><p>There’s no way that this program would work if we reassembled and ran it on our emulator (that we haven’t built yet).</p><blockquote>But why? Where did we go wrong?</blockquote><p>In taking our naive approach, we made some assumptions about programs that aren’t very accurate:</p><ol><li>That all opcodes will occur within even memory space. (By starting from zero and progressing by two).</li><li>That all regions of the program are valid opcodes. (By disassembling every instruction and producing a NOOP when it’s invalid).</li></ol><p>When in reality, we have no control over what address a program will jump to and there’s no reason that a program <em>shouldn’t </em>jump to an uneven address. They’re all the same contiguous bytes in memory: 0x13 0x34 0x42 produces two different (JMP, SKEQ) but valid opcodes depending on where you start.</p><p>Further, just because there are bytes in a program, it doesn’t mean that they are intended to be consumed as opcodes. Some may just be non-reachable, but others can be data used for drawing sprites or loading registers.</p><p>Consider the 0xFX65 opcode for a moment, which we’ve given the mnemonic LDR (short for LoaD Registers). This opcode will load registers 0 to X from memory starting at where the index register is currently plus 0 to X. You can imagine a scenario where we’ve stored some constant data at the end of our program (unreachable from the main loop), and want to load it into registers with this command.</p><p>Another use is for storing sprites. Let’s go way up and look at the pong2 opcode at address 0x208: MVI 2EAh ; 208. If we scan down to address 0x2EAH, we can see</p><pre>MOV   $0, $8               ;2ea<br>MOV   $0, $8               ;2ec<br>MOV   $0, $8               ;2ee<br>MOV   $0, $0               ;2f0<br>NOOP                       ;2f2<br>NOOP                       ;2f4</pre><p>This is — in fact — unreachable address space from the normal program. Meaning, the program counter of the Chip-8 VM will never land on these addresses. It’s purely coincidental that they resemble the MOV $0, $8 opcode, and thus purely coincidental that our reassembled program works at all.</p><p>These bytes actually exist for drawing the paddles. Looking at the hexdump from the original program, we’ll see:</p><pre>80 80 80 80 80 80 80 00 00 00 00 00<br>^ - The MVI command sets index register here.</pre><pre>//where 0x80 = 0b10000000</pre><p>Notice that the two statements following the initial MVI are DRAW statements. When the Chip-8 receives a DRAW command, it will draw a sprite at the screen positions stored in registers X and Y with Z height. Sprites are always 8 pixels wide and represented as the bits of a byte in memory. The Chip-8 loads the sprite data from memory starting at the index register. If we’re drawing a sprite with the height of six, we start from index register I+0 and end at index register I+6.</p><pre>A paddle:</pre><pre>0b<strong>1</strong>0000000 ; 0x2ea<br>0b<strong>1</strong>0000000 ; 0x2eb<br>0b<strong>1</strong>0000000 ; 0x2ec<br>0b<strong>1</strong>0000000 ; 0x2ed<br>0b<strong>1</strong>0000000 ; 0x2ee<br>0b<strong>1</strong>0000000 ; 0x2ef </pre><p>If we were to change these numbers to 0xC0 (0b<strong>11</strong>000000), our paddles would be one extra pixel wide.</p><h3>A Nuanced Approach</h3><p>So we’ve seen the reasons for which the naive approach does not produce consistent results. What we need is a strategy to explore all reachable addresses, mark them as reachable and then output any non-reachable data.</p><p>Instead of seeing these opcodes as a sequential list of instructions, let’s imagine them more as a dynamic program. Consider the following:</p><pre>MOV $1, $3<br>SKEQ $1, $2<br>JSR :take-damage<br>JSR :check-input</pre><pre>:take-damage<br>MOV $6, 0x2h<br>SUB $4, $5<br>RET</pre><pre>:check-input<br>MOV $1, 0xA<br>SKUP $1<br>ADD $5, 0x2<br>RET</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*JTHk9eulMGPQBzDDHsjsDQ.png" /><figcaption>Looks like a job for DFS</figcaption></figure><p>A surprising amount of problems can be solved with Breadth-First and Depth-First Search.</p><p>Looking at the above tree, we definitely don’t want to be using BFS. That would get us close to doing exactly what we’re trying to avoid: visiting opcodes in sequence.</p><p>Depth-First search is what we want — and if we want DFS, we’ll need a stack.</p><p>Here’s what our new strategy will be:</p><p><strong>Iterate through the program, marking each visited address as reachable. When a branch statement is encountered, push the next address onto the stack and follow the branch.</strong></p><p><strong>When the stack is empty, iterate through all potential address space up to the size of the program. If the potential address is reachable, disassemble it.</strong></p><p><strong>Finally, account for all unreachable, non-null address space.</strong></p><p>Whew, that was a mouthful. Really though, we’re <em>super</em> close.</p><p>This takes a little bit more thought than disassembling the opcode, but once that’s over implementing it is a cinch. We can even reuse some ideas from the previous naive solution: output will become reachableAddresses, program will become buffer and we’ll keep the labels map just the same.</p><p>With a class that takes a UInt8Array as it’s only constructor argument, we can implement something that looks like this, <a href="https://github.com/dpchamps/chip8Emulator/blob/Chapter2/src/Disassembler.ts">full code here</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8867e9d32332bfac9afd6d81e44de1d3/href">https://medium.com/media/8867e9d32332bfac9afd6d81e44de1d3/href</a></iframe><p>The one fiddly bit of code occurs inside of the generateProgram method. We have to decide whether or not to increment the current address by one or two. We make this decision by checking to see if the current address is reachable.</p><p>If it is, it means whatever exists at it will be a two-byte-long opcode and the next address to check will be two bytes away. Otherwise, it’s data and the next byte needs to be checked for a valid opcode.</p><p>We’re left with one dilemma though: what do we do with the unreachable addresses?</p><p>We might think to simply output the raw bytes in place, something like:</p><pre>FONT  $2                   ;2e4<br>DRAW  4h, 5h, 5h           ;2e6<br>RET                        ;2e8<br>80h                        ;2ea<br>80h                        ;2eb<br>80h                        ;2ec<br>80h                        ;2ed<br>80h                        ;2ee<br>80h                        ;2ef<br>0h                         ;2f0<br>0h                         ;2f1<br>0h                         ;2f2<br>0h                         ;2f3<br>0h                         ;2f4<br>0h                         ;2f5<br>:label-0x02F6<br>MOV   $B, 20h              ;2f6<br>MOV   $C, 0h               ;2f8</pre><p>First of all, this doesn’t look great. The point is to produce something we can understand. Having large chunks of unexplained numbers brings us in the opposite direction.</p><p>More importantly though, this lacks some critical information: where to put these numbers when we’re reassembling the program. The assembler will not have access to comments, and no other tokens provide any context for memory location.</p><p>This is by design. Memory locations should (as much a possible) be the domain of the assembler. With the addition of labels, we managed to (almost completely) abstract them out of the equation.</p><p>We could try to recycle this concept by marking unreachable regions with labels, but that may end up being more trouble than it’s worth: unlike jumps and subroutines, mvi’s ldr’s and sdr’s may access different pieces of the same contiguous block of unreachable memory.</p><p>Imagine the following scenario:</p><pre>80h                        ;2ea &lt;- mvi accesses this<br>80h                        ;2eb<br>80h                        ;2ec &lt;- ldr accesses this<br>80h                        ;2ed<br>80h                        ;2ee &lt;- sdr accesses thi<br>80h                        ;2ef</pre><pre>//would become...</pre><pre>:label-0x2ea<br>80h                        ;2ea &lt;- mvi accesses this<br>80h                        ;2eb<br>:label-0x2ec<br>80h                        ;2ec &lt;- ldr accesses this<br>80h                        ;2ed <br>:label-0x2ee<br>80h                        ;2ee &lt;- sdr accesses this<br>80h                        ;2ef</pre><p>To our assembler, this looks like three different regions of memory. But it’s crucial that all of this remains in the same block. If a DRAW $0, $1, 6h statement follows that mvi and I have these regions split up, the assembled program will produce unexpected results.</p><p>Unfortunately, there’s no pretty way around this. Later, when we’re writing our assembler, we can start thinking about ways to declare variables inside of the disassembly. But as far as disassembling the program is concerned, we’ll have to provide the assembler (and the human) some specific context.</p><p>What I’ve chosen to do is add an additional instruction called DATA. This is not exactly conventional… But there’s a method to my madness.</p><h3>Total Control</h3><p>We’re implementing the Chip-8 to a specification. This specification allows us to take any valid Chip-8 bytecode and run it. If we implemented this VM on an Arduino, the same Chip-8 program that runs on my PC will run on the Arduino in the same way no matter what. Every time.</p><p>When we disassemble some Chip-8 bytecode, we start to get into <em>murkier</em> territory. We can borrow from other assembly languages, we can follow some conventions, we can see what some other people did… but there’s not specification for it.</p><p>Because the Chip-8 is so simple, and no disassembly specification exists, we’re pretty much on our own. What we say when we write a disassembler and assembler for our Chip-8 is: <strong><em>these programs will disassemble and assemble valid bytecode . If you want to use them yourself, you have to follow our specification.</em></strong></p><p>In short, we’re stepping ever so gently into the realm of language creation — however crude or minimalist that language happens to be.</p><h3>DATA Instruction</h3><p>So we’re going to add a data instruction.</p><p>This instruction has no opcode analog, it’s purely syntactic. It has the following rules:</p><ol><li>The DATA instruction takes as its first argument a location in memory.</li><li>The DATA instruction takes as its second argument a single byte, which is the data to store at the previously defined memory location.</li><li>The DATA instruction must have two arguments, but may have up to n additional arguments, which define data to store at initial memory location + nth additional argument.</li></ol><p>The following disassembly is equivalent:</p><pre>DATA 2EAh, 80h<br>DATA 2EBh, 80h<br>DATA 2ECh, 80h<br>DATA 2EDh, 80h<br>DATA 2EEh, 80h<br>DATA 2EFh, 80h</pre><pre>//is equivalent to</pre><pre>DATA 2EAh, 80h, 80h, 80h, 80h, 80h, 80h</pre><pre>//is equivalent to</pre><pre>DATA 2EAh, 80h, 80h, 80h<br>DATA 2EDh, 80h, 80h, 80h</pre><p>For maximum clarity, our disassembler will produce the first option from the above three. We’ll do this because there’s no way to determine what order is the most readable for the intention of the program. As far as we know, it’s just one single chunk and it’s best not to get clever about it.</p><p>Implementing this is a cake walk though. We can add a DataCode class, and augment our generateProgram method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d31bc8d303f7cf78b409cf3fe858165/href">https://medium.com/media/9d31bc8d303f7cf78b409cf3fe858165/href</a></iframe><p>Placing all data instructions after the disassembled program is a stylistic choice. We could just as easily put them in place. The assembler will know what to do with them immediately no matter what, but I find it to be more readable to have a reference declared at the bottom.</p><p>Let’s look at the first couple of lines of missile.c8 to see if we get better results <a href="https://gist.github.com/dpchamps/15953fd41172bcac8454602c203d42a6">(see the full output here)</a>:</p><pre>JMP   :label-0x0219       ; addr : 200; opcode : 0x1219<br>:label-0x0219<br>MOV   $C, Ch              ; addr : 219; opcode : 0x6C0C<br>MOV   $0, 0h              ; addr : 21B; opcode : 0x6000<br>MOV   $1, 0h              ; addr : 21D; opcode : 0x6100<br>MOV   $5, 8h              ; addr : 21F; opcode : 0x6508<br>MOV   $6, Ah              ; addr : 221; opcode : 0x660A<br>MOV   $7, 0h              ; addr : 223; opcode : 0x6700<br>MOV   $E, 1h              ; addr : 225; opcode : 0x6E01<br>MVI   2ADh                ; addr : 227; opcode : 0xA2AD<br>:label-0x0229</pre><p>Much better! I’ve added some comments to the disassembly, you’ll find the implementation of which on github.</p><h3>What’s Next</h3><p>Ok, I lied last time when I said that we’d start implementing the Chip8. Creating a robust disassembler and really understanding the nuts and bolts is an important first step.</p><p>Remember: we’re not learning how to write a Chip-8 emulator, we’re learning about broader concepts <em>illustrated</em> by the creation of a Chip-8. We’re just tracing the outlines right now.</p><p>Next time, we’re actually going to go over <strong>all</strong> of the specifications for the Chip-8 and cobble together a bare-bones implementation. In the process, we’re going to create a CLI program debugger. This will bring everything together, we’ll see how opcodes relate to our disassembly, and be able to step through the bytecode one instruction at a time and watch it affect VM at large.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f6849bb1b55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Have Fun With Interpreters and Bytecode VMs— Chapter 1]]></title>
            <link>https://medium.com/@davewritescode/lets-have-fun-with-interpreters-and-bytecode-vms-chapter-1-7876ade6bb5c?source=rss-360abb95e17a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7876ade6bb5c</guid>
            <category><![CDATA[emulator]]></category>
            <category><![CDATA[emulation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[fun]]></category>
            <dc:creator><![CDATA[Dchampz]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 01:50:21 GMT</pubDate>
            <atom:updated>2018-12-24T02:39:08.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zket5XJrn3NVOvdzsx2QVA.jpeg" /></figure><h3>Prelude</h3><p>This is the first in a series of articles about writing and implementing interpreters and bytecode vms. You may have some immediate thoughts:</p><blockquote>What the hell is an interpreter and Why would I want to write one?</blockquote><p>Through this series I hope to dig into and touch upon both of them in great detail. But in short,</p><ol><li>An interpreter reads instructions and does <em>things </em>with with them.</li><li>Knowledge, fun… and maybe profit (though I doubt it).</li></ol><p>This series is going to mostly revolve around the concept of a <strong>Stack-Based Virtual Machine — </strong>but we’ll be exploring the avenues to-and-from this concept as well. Along the way, we’ll write a handful of interpreters and learn about lexing, parsing and AST’s (<em>and more!)</em> in the process.</p><p>Though being terse for brevity’s sake is nice, it really does help to have a little bit of context. So let’s start with a kernel of (potential) motivators:</p><p>Have you ever thought to yourself,</p><blockquote>🤔 How can I produce my indie game in such a way that allows other people to mod it — how can I release patches or updates without distributing a recompiled binary?</blockquote><p>Or perhaps,</p><blockquote>What does wikipedia mean when is says, “<a href="https://en.wikipedia.org/wiki/JavaScript">[javascript] is a high-level, interpreted programming language</a>”</blockquote><p>Or maybe even</p><blockquote>How do all of these video game emulators work anyways?</blockquote><p>If so, then <strong>great!</strong></p><p>We’re eventually going to visit all of these concepts in-depth… but we’ll have to start small.</p><h3>Prerequisites</h3><p>These articles are geared towards programmers. So you should be able to write and understand code, though it doesn’t really matter what language. I’ll be giving examples in Typescript to start, but later we might need to get closer to the metal with C.</p><p>The other pretty major knowledge requirement is that you should feel comfortable with bitwise operations. We’re going to be talking in the language of machines, so we’ll need to have a concept of numbers outside of base 10 (namely, binary and hexadecimal).</p><p>If you see something like this: (0xF00 &amp; opcode) &gt;&gt; 8 and it scares you — or you find yourself struggling to understand what is being expressed — take a few minutes to brush up on <a href="https://en.wikipedia.org/wiki/Bitwise_operation">bitwise operations</a>. These concepts are straightforward, and you’ll pick up on them quickly.</p><p>As a disclaimer: these topics are <strong><em>yuge.</em></strong><em> </em>There are tons of books written on these subjects. This is not a substitute for them, but a supplement to them. Reading theory doesn’t get you anywhere without practice, and these articles are kind of like training wheels.</p><h3>Introducing the Chip-8</h3><p>Over the next few installments, we are going write a Chip-8 virtual machine and beat it to death. When it’s finally time to move on, we’ll know the Chip-8 back to front and be pushing it’s capabilities past what it was ever initially designed for.</p><blockquote>But… why</blockquote><p>The Chip-8 is an incredibly straightforward Stack-based Virtual machine. It’s easy to implement but still has a moderate level of complexity. Enough to keep our interest while we dive into some dense topics.</p><p>It’s also the major jumping-off point for aspiring emulator developers. Ask anyone in the EmuDev scene where to start, and you’ll most likely get Chip-8.</p><p>This is going to be different from a <em>how-to-write-a-chip8-emulator</em> tutorial though. There are plenty of those out there in the wild. The Chip-8 is so simple that we could sit down with Sunday morning’s coffee and conclude with a finished product a little after lunch.</p><p><em>Note: this is a generalization. Don’t let this get you down if you’ve written (or attempted to write) a Chip-8 emulator and it took longer. You only get better by doing.</em></p><p>In short, the Chip8 is a toy. But it’s an interesting toy, and one we can learn from.</p><p>As mentioned above, there are probably hundreds of tutorials on how to create a Chip-8 emulator.</p><p>We’re going to breeze through a lot of the code, it will be up to you to implement it. However, all of the ideas we talk about will be fully implemented in a Github repo so you can pull it down and play around with it, though I strongly suggest that you try to write this stuff on your own. It doesn’t matter if it takes you longer to get something up and running, that struggle is like doing pushups with your brain.</p><blockquote>So what is the Chip-8 anyway?</blockquote><p>Chip-8 is an interpreted programming language that is run by a virtual machine to produce things that look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-_dT2apyTR0Y-V5T4GjmA.png" /><figcaption>😲Such graphics, very wow.</figcaption></figure><p>Though you may also be familiar with this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZ5Z2aQy44jtUnIaTWFjHw.png" /></figure><p>Now, we could re-create better versions of these two games in a shorter period of time with vanilla JS. But part of the novelty of what we’re doing is turning this:</p><pre>missile.c8 hexdump</pre><pre>12 19 4d 49 53 53 49 4c 45 20 62 79 20 44 61 76</pre><pre>69 64 20 57 49 4e 54 45 52 6c 0c 60 00 61 00 65</pre><pre>08 66 0a 67 00 6e 01 a2 ad d0 14 70 08 30 40 12</pre><pre>29 60 00 61 1c a2 b0 d0 14 a2 b0 d0 14 3e 01 12</pre><pre>49 70 04 40 38 6e 00 12 4f 70 fc 40 00 6e 01 d0</pre><pre>14 fc 15 fb 07 3b 00 12 53 62 08 e2 9e 12 95 3c</pre><pre>00 7c fe 63 1b 82 00 a2 b0 d2 31 64 00 d2 31 73</pre><pre>ff d2 31 3f 00 64 01 33 03 12 6d d2 31 34 01 12</pre><pre>91 77 05 75 ff 82 00 63 00 a2 ad d2 34 45 00 12</pre><pre>97 76 ff 36 00 12 39 a2 b4 f7 33 f2 65 63 1b 64</pre><pre>0d f1 29 d3 45 73 05 f2 29 d3 45 12 ab 10 38 38</pre><pre>10 38 7c fe</pre><p>into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1kXKtzpJGl0H-l5a0QFhg.gif" /><figcaption>If this idea doesn’t get you going, now would be a good time to stop reading.</figcaption></figure><h3>Opcodes</h3><p>We’ll worry about the Chip-8 specifications later. Instead of jumping right into coding a Chip-8 emulator, let’s really understand what’s going on during the process that takes the above stream of numbers and produces those top-tier graphics.</p><p>I said before that “Interpreters read instructions and do things with them.” In other words, interpreters… interpret.</p><p>Seeing as instructions can be interpreted from one thing to another thing, how we represent them can be <em>flexible</em>. What matters more than the <em>representation</em> are the <em>rules</em> that define the transformation from abstract representation into concrete results.</p><p>In fact — through this series, we’ll be pulling some sources through various representations before landing on the final one.</p><p>But what we’re looking at above is called <strong><em>Bytecode</em></strong>.</p><p>Bytecode is an <a href="https://en.wikipedia.org/wiki/Intermediate_representation">intermediate representation</a> of some higher-order logic, source code or instruction set. It says: <strong>this number means do this rule</strong>.</p><p>Our Chip-8 emulator reads the bytecode and follows those rules. One benefit of bytecode is that it’s portable. Rather than being read by the hardware of the computer it’s being run on, it’s read by an intermediary (our emulator). If the host computer can run the virtual machine, it can run any valid program written in bytecode for that virtual machine. This is essentially how languages like Java and Python work (<em>though </em><strong><em>NOT</em></strong><em> Javascript)</em>.</p><p>If the benefit of bytecode interpreters is portability, we pay for that portability with performance. Bytecode interpreters will never be as performant as machine code because of this intermediate step. Portability vs performance is another lorge topic, and one I’m not going to talk about in greater detail right now. Just know that nothing in this series will be impacted by this performance price.</p><p>The hexdump of missile.c8 from way on up is a collection of opcodes.</p><p>Chip-8 defines the rules as an instruction set made up of two-byte numbers also known as “Opcodes”, of which there are 36. Opcodes are defined as such ( <a href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#3.1">a condensed version borrowed from cowgod</a>):</p><pre><strong>00E0 - </strong>Clear the display.<br><br><strong>00EE - </strong>Return from a subroutine.<br><br><strong>1<em>nnn</em> - </strong>Jump to location <em>nnn</em>.<br><br><strong>2<em>nnn</em> - </strong>Call subroutine at <em>nnn</em>.<br><br><strong>3<em>xkk</em> - </strong>Skip next instruction if V<em>x</em> = <em>kk</em>.<br><br><strong>4<em>xkk</em> - </strong>Skip next instruction if V<em>x</em> != <em>kk</em>.<br><br><strong>5<em>xy</em>0 - </strong>Skip next instruction if V<em>x</em> = V<em>y</em>.<br><br><strong>6<em>xkk</em> - </strong>Set V<em>x</em> = <em>kk</em>.<br><br><strong>7<em>xkk</em> - </strong>Set V<em>x</em> = V<em>x</em> + <em>kk</em>.<br><br><strong>8<em>xy</em>0 - S</strong>et V<em>x</em> = V<em>y</em>.<br><br><strong>8<em>xy</em>1 - </strong>Set Vx = V<em>x</em> OR V<em>y</em>.<br><br><strong>8<em>xy</em>2 - </strong>Set V<em>x</em> = V<em>x</em> AND V<em>y</em>.<br><br><strong>8<em>xy</em>3 - </strong>Set V<em>x</em> = V<em>x</em> XOR V<em>y</em>.<br><br><strong>8<em>xy</em>4 - </strong>Set V<em>x</em> = V<em>x</em> + Vy, set VF = carry.<br><br><strong>8<em>xy</em>5 - </strong>Set V<em>x</em> = V<em>x</em> - V<em>y</em>, set VF = NOT borrow.<br><br><strong>8<em>xy</em>6 - </strong>Set V<em>x</em> = V<em>x</em> SHR 1.<br><br><strong>8<em>xy</em>7 - </strong>Set V<em>x</em> = V<em>y</em> - V<em>x</em>, set VF = NOT borrow.<br><br><strong>8<em>xy</em>E - </strong>Set V<em>x</em> = V<em>x</em> SHL 1.<br><br><strong>9<em>xy</em>0 - </strong>Skip next instruction if V<em>x</em> != V<em>y</em>.<br><br><strong>A<em>nnn</em> - </strong>Set I = <em>nnn</em>.<br><br><strong>B<em>nnn</em> - </strong>Jump to location <em>nnn</em> + V0.<br><br><strong>C<em>xkk</em> - </strong>Set V<em>x</em> = random <em>byte</em> AND <em>kk</em>.<br><br><strong>D<em>xyn</em> - DRW V<em>x</em>, V<em>y</em>, <em>nibble</em></strong><br><br><strong>E<em>x</em>9E - </strong>Skip next instruction if key with the value of V<em>x</em> is pressed.<br><br><strong>E<em>x</em>A1 - </strong>Skip next instruction if key with the value of V<em>x</em> is not pressed.<br><br><strong>F<em>x</em>07 - </strong>Set V<em>x</em> = delay timer value.<br><br><strong>F<em>x</em>0A - </strong>Wait for a key press, store the value of the key in V<em>x</em>.<br><br><strong>F<em>x</em>15 - </strong>Set delay timer = V<em>x</em>.<br><br><strong>F<em>x</em>18 - </strong>Set sound timer = V<em>x</em>.<br><br><strong>F<em>x</em>1E - </strong>Set I = I + V<em>x</em>.<br><br><strong>F<em>x</em>29 - </strong>Set I = location of sprite for digit V<em>x</em>.<br><br><strong>F<em>x</em>33 - </strong>Store BCD representation of V<em>x</em> in memory locations I, I+1, and I+2.<br><br><strong>F<em>x</em>55 - </strong>Store registers V0 through V<em>x</em> in memory starting at location I.<br><br><strong>F<em>x</em>65 - </strong>Read registers V0 through V<em>x</em> from memory starting at location I.</pre><blockquote>But wait… those aren’t all numbers… X, Y, NNN?!</blockquote><p>Opcodes are two bytes long, thus the domain of an opcode is 0x0000–0xFFFF. If we were to use one rule per opcode we would have 65535 opcodes on our hands(which is too many damn opcodes).</p><p>Instead, we can encode some metadata into the opcodes at various levels. Take for example, opcode 0x1nnn. What this rule says is, <em>“for all numbers 0x1000 to 0x1FFF, preform a jump.” </em>The metadata exists in the first three bytes: 0x0 —0xFFF, which defines an address location in memory to jump to.</p><p>There are four different variables encoded into chip-8 opcodes:</p><pre>X - the third nibble<br>Y - the second nibble<br>KK - the lower byte<br>NNN - the first three bytes</pre><pre>//and we can also define for some help down the road</pre><pre>MSB - The most significant byte<br>LSB - The least significant byte</pre><p>Here’s a concrete example:</p><pre>0x8123:</pre><pre>MSB : 0x8<br>X   : 0x1<br>Y   : 0x2<br>KK  : 0x23<br>NNN : 0x123<br>LSB : 0x3</pre><p>A general algorithm is:</p><ol><li>Find rules starting with the MSB</li><li>Iff there’s only one rule for this MSB return rule</li><li>Iff there’s more than one rule, refine by the LSB or KK and then return rule.</li></ol><p>In the above example: We start with 0x8 (the MSB) and find that there are 9 rules defined for the 0x8 MSB. We then move on to 0x3 (the LSB) and see that we’ve found only one candidate, which says: set register X to the value of register X ^ register Y.</p><p>Therefore, 0x8123 to our emulator means:</p><p><strong><em>Set Register 1 to the value stored in Register 1 XORed with the value stored in Register 2.</em></strong></p><p>Let’s look at the first 10 bytes (5 opcodes) from<strong> pong2.c8</strong>:</p><pre>22f6 6b0c 6c3f 6d0c a2ea dab6 dcd6</pre><ol><li>Jump to a subroutine located at address 0x2f6.</li><li>Set register 0xb to contain the value 0x0c</li><li>Set register 0xc to contain the value 0x3f</li><li>Set register 0xd to contain the value of 0x0c</li><li>Set register I to 0x2ae</li><li>Draw sprite to screen location (0x0, 0xC) with a height of 0x6</li><li>Draw sprite to screen location (0x3F, 0c) with a height of 0x6</li></ol><blockquote>What has a height of 6 and exists at screen positions (0, 12) and (63, 12)…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7JNDsy7RRMRZX8Mn1LfwA.png" /><figcaption>😱 The paddles!</figcaption></figure><p>With this knowledge we’re about a paragraph away from having everything we need to write a fully-functional Chip8 emulator.</p><p>Actually, we don’t need to understand the programs at all to be able to write the emulator. But if we know how to read the programs, we can learn how to write the programs. And if we know how to write BOTH the VM and the programs it consumes, we can start to do some really interesting things.</p><p>Of course, we could xxd the whole pong program and byte-by-byte cross reference the opcode table to understand what’s happening. But we’re engineers, and that’s absurd. 22f6 6b0c 6c3f<strong> means nothing to our mushy human brains.</strong></p><p>What we need to do is <em>disassemble</em> the bytecode into a less terse, more readable representation that we can more readily understand. This is what I mean when I say representations are <em>flexible. </em>Bytecode is the target representation for our emulator, but it is not the only representation.</p><h3>Let’s write some code</h3><p>Starting with the low-hanging fruit, some data structures to represent our opcodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d98d33325cbb53dae0b8e1d25c49f7ae/href">https://medium.com/media/d98d33325cbb53dae0b8e1d25c49f7ae/href</a></iframe><p>Instead of converting opcodes to plain english (i.e “draw sprite to…”) we’re going to use something called a mnemonic.</p><p>To use the example from earlier,</p><p><strong><em>Set Register 1 to the value stored in Register 1 XORed with the value stored in Register 2</em></strong></p><p>Now becomes:</p><p><strong><em>XOR $1, $2</em></strong></p><pre>0x8123 -&gt; XOR $1, $2 <br>0x1234 -&gt; JMP 234h<br>//much easier to comprehend</pre><p><em>Note: we’re going to use h suffixes to indicate that a number is in hexadecimal and $ prefixes for registers. This doesn’t matter now, but it will later.</em></p><p>We should also implement some structures to encapsulate this data as tokens. This will come in handy for reasons explained later, but in short: Tokens are units of strings. Given some raw input, we <em>lex</em> it into tokens and then <em>parse</em> it into some other intermediate abstraction (eventually byte code).</p><p><strong>Remember: how we represent this data is flexible, as long as it represents the rules in a complete way.</strong></p><p>We could use any Mnemonic in the world. For example, we could use SPRITE instead of DRAW (or even PINECONE for whatever reason).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0232ad5f708ace4876a3c878448674/href">https://medium.com/media/ba0232ad5f708ace4876a3c878448674/href</a></iframe><p>Finally, we’ll want to organize these structures together in a single class, we can call it Opcode.</p><p>Our class Opcode will take a number as it’s only constructor argument and parse the opcode into an OpcodeBytes object. It will look up and store the Mnemonic instruction associated with the opcode as an Instruction Token, and then extract the encoded variables based on the instruction as Integer or Register tokens.</p><p>In order to elegantly extract these variables, we’ll have to look at the structure of the instruction set. We already know that there can be variables x, y, kk, nnn but if you look carefully at the above instruction set, you’ll see that we can abstract all instructions into the following categories:</p><pre>Args x, y, z:  DRAW<br>Args x, KK  :  SKEQ, SKNE, MOV, RAND<br>Args x, y   :  SKEQ, SKNE, MOV, OR, AND XOR, ADD, SUB, RSB<br>Args nnn    :  JMP, JSR, MVI, JMI</pre><p>Finally, we’ll need to define a toString method that will output the opcode in it’s disassembled form.</p><p>With this knowledge, we’re two switch statements and some organization away from a complete implementation. The switch statements make the class a bit long and not the most pretty, <a href="https://github.com/dpchamps/chip8Emulator/blob/master/src/Opcode.ts">you can see the full code here</a>. But the most salient parts are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c84634a5a3b29e826fa4c419856f4564/href">https://medium.com/media/c84634a5a3b29e826fa4c419856f4564/href</a></iframe><p>We now have a nice (somewhat compact) class to disassemble any valid Chip8 opcode. No more cross-referencing!</p><pre>const opcode = new Opcode(0xD123);<br>console.log(opcode.toString()); <br>// DRAW 1h, 2h, 3h<br>const opcode2 = new Opcode(0x1ABC);<br>console.log(opcode2.toString()); <br>// JMP ABCh</pre><p>That’s it for today.</p><p>Next time, we’ll look at what we need to disassemble an entire Chip-8 program. We’ll explore a naive solution first, look at why that solution doesn’t exactly fit the bill and then move on to a more comprehensive solution. We’ll also go over the Chip-8 Specifications in greater detail and begin writing the emulator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7876ade6bb5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>