<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Posts on Rodrigo Araujo</title><link>/posts/</link><description>Recent content in Posts on Rodrigo Araujo</description><generator>Hugo -- gohugo.io</generator><language>en-us</language><lastBuildDate>Wed, 04 May 2022 00:00:00 +0000</lastBuildDate><atom:link href="/posts/index.xml" rel="self" type="application/rss+xml"/><item><title>Coding the Byzantine Generals Problem</title><link>/posts/coding-the-byzantine-generals-problem/</link><pubDate>Wed, 04 May 2022 00:00:00 +0000</pubDate><guid>/posts/coding-the-byzantine-generals-problem/</guid><description>Leslie Lamport is one of my all-time favorite computer scientists. That said, something about most of his classical papers, such as Paxos and the Byzantine Generals Problem (BGP), makes it complicated to understand the details.
In addition, there&amp;rsquo;s a flood of non-technical takes on the BGP due to many people being interested in the non-technical parts of Bitcoin and other cryptocurrencies. It makes it hard to research the details of the problem from a Computer Science perspective.</description><content type="html"><![CDATA[<p>Leslie Lamport is one of my all-time favorite computer scientists. That said, something about most of his classical papers, such as Paxos and the Byzantine Generals Problem (BGP), makes it complicated to understand the details.</p>
<p>In addition, there&rsquo;s a flood of non-technical takes on the BGP due to many people being interested in the non-technical parts of Bitcoin and other cryptocurrencies. It makes it hard to research the details of the problem from a Computer Science perspective.</p>
<p>At this point, I believe we all know, at a very high level, what the BGP is and its main conclusion: An analogy between software processes/nodes and the Byzantine generals trying to reach a consensus about something. Consensus is a hard problem, but it&rsquo;s especially hard when the nodes, or the generals, can act adversarially. In other words, the other participant nodes of the network can stop responding due to a crash, but, worse, they can respond with wrong information (think bit flipping or other bugs) or with maliciously crafted information, as an adversary of a protocol would.</p>
<p>And then, after a <em>lot</em> of details in the paper, Leslie concludes that a Byzantine fault-tolerant system needs at least $3m + 1$ nodes to support at most $m$ faulty, or traitor/adversarial, nodes. Easy to work with the conclusion: if you have 4 nodes, you can only support 1 bad guy. If you have 2 bad guys in the system, then you&rsquo;re gonna need 7 nodes, where 5 are honest. And so on. It&rsquo;s important to note that this result is specifically for <em>synchronous</em> networks. This is a pretty important assumption. It changes <em>a lot</em> once we move to an <em>asynchronous</em> network model, which was solved in later works such as Practical Byzantine Fault-Tolerance by Miguel Castro and Barbara Liskov.</p>
<p>However, this post isn&rsquo;t only about going over these results. I would like to dive into the <em>details</em>. Not only that, but we&rsquo;re gonna write code to test some of the ideas on Leslie&rsquo;s paper. I&rsquo;m a big fan of building something to truly understand that thing. So let&rsquo;s get started.</p>
<hr>
<h2 id="context-and-goals-are-everything">Context and goals are everything</h2>
<p>One thing that helped me understand the proposed algorithm was to constantly go back and remember the main goals of the solution proposed by Leslie.</p>
<p>This snippet of the paper captures the high level perfectly:</p>
<blockquote>
<p>We imagine that several divisions of the Byzantine army are camped outside an enemy city, each division commanded by its own general. The generals can communicate with one another only by messenger. After observing the enemy, they must decide upon a common plan of action. However, some of the generals may be traitors, trying to prevent the loyal generals from reaching agreement. The generals must have an algorithm to guarantee that</p>
<p>A. All loyal generals decide upon the same plan of action.  The loyal generals will all do what the algorithm says they should, but the traitors may do anything they wish. The algorithm must guarantee condition A regardless of what the traitors do. The loyal generals should not only reach agreement, but should agree upon a reasonable plan. We therefore also want to insure that</p>
<p>B. A small number of traitors cannot cause the loyal generals to adopt a bad<br>
plan.</p>
</blockquote>
<p>After some discourse around those two points, he lays down a very important piece for us, the interactive consistencies:</p>
<blockquote>
<p>Byzantine Generals Problem. A commanding general must send an order to<br>
his $n - 1$ lieutenant generals such that:</p>
<p>IC1. All loyal lieutenants obey the same order.
IC2. If the commanding general is loyal, then every loyal lieutenant obeys the<br>
order he sends.</p>
<p>Conditions IC1 and IC2 are called the interactive consistency conditions. Note<br>
that if the commander is loyal, then IC1 follows from IC2. However, the commander need not be loyal.</p>
<p>To solve our original problem, the i-th general sends his value of <code>v(i)</code> by using a solution to the Byzantine Generals Problem to send the order &ldquo;use <code>v(i)</code> as my  value&rdquo;, with the other generals acting as the lieutenants.</p>
</blockquote>
<p>There&rsquo;s so much packed in this single passage. Personally, while writing the code to solve the BGP, I found myself very confused about many things, most of which were answered by referring back to the passage above.</p>
<p>First, Leslie introduces the concept of <em>commanding general</em>. If we have 4 generals, <em>at the beginning of the algorithm</em> we&rsquo;ll promote one of them to be the commanding general, sending orders to the other 3 generals, now called <em>lieutenants</em>.</p>
<p>Second, as the IC1 says, we care about all <em>loyal</em> (or non-faulty) generals (<em>not</em> the commanding general) following the same order. If we have 4 generals, 1 being a loyal commanding general, 2 loyal generals, and 1 traitor general, <strong>it doesn&rsquo;t matter what the one traitor does; we care that the 2 loyal generals follow the order given by the loyal commander.</strong> Eventually, one can realize that&rsquo;s the goal of most distributed consensus mechanisms.</p>
<p>Third, <em>if</em> the commanding general is loyal, then the order that all <em>loyal</em> generals are following is the same order given by the <em>loyal</em> commanding general. In the case of a traitor <em>commanding</em> general, all hope is lost.</p>
<p>Now, here&rsquo;s one of the most, if not the most, important parts of this whole thing:</p>
<blockquote>
<p>To solve our original problem, the i-th general sends his value of <code>v(i)</code> by using a solution to the Byzantine Generals Problem to send the order &ldquo;use <code>v(i)</code> as my  value&rdquo;, with the other generals acting as the lieutenants.</p>
</blockquote>
<p>This is a <em>recursive</em> solution. Here&rsquo;s a concrete example: If we have 4 generals, 1 being the commanding general, once the commander sends their value $i$ to the other 3 <em>lieutenants</em>, each <em>lieutenant</em> will act as a <em>commander</em> in the next iteration of the algorithm, but considering only $n-1$ generals.</p>
<p>On the first step of the algorithm, this is what we have:
<img src="/images/images/byzantine1.png" alt="First"></p>
<p>Then, once the commanding general sends their order, there will be 3 more steps. Each of the 3 lieutenants will act as commander and send the message they received from the commanding general to the other 2 lieutenants. Meaning that the original commanding general is out of the picture for now:</p>
<p><img src="/images/images/byzantine2.png" alt="Second"></p>
<p>At the end, we have something like this:</p>
<p><img src="/images/images/byzantine3.png" alt="Third"></p>
<p>And by doing this, something magical emerges: if you have $3m +1$ generals, you can tolerate $m$ traitors. Meaning:</p>
<ol>
<li>All loyal generals will follow the same order (IC1)</li>
<li>If the commanding general is loyal, then every loyal lieutenant obeys the order he sends.</li>
</ol>
<p>We haven&rsquo;t seen the proper specs of the algorithm, but that paints the picture of what we want to achieve and the overall idea of <em>how</em> we want to achieve it.</p>
<h2 id="the-oral-message-algorithm">The oral message algorithm</h2>
<p>The first solution to this problem, as Leslie named it, is the Oral Message (OM) algorithm. Which will do what we described above.</p>
<p>A few relatively easy to understand assumptions are then made:</p>
<ol>
<li>Every message is delivered correctly;</li>
<li>The receiver of the message knows who sent it;</li>
<li>The absence of a message can be detected (can be a simple timeout).</li>
</ol>
<p>The OM algorithm is defined as $OM(m)$, and that&rsquo;s something that confused me, probably for silly reasons. It wasn&rsquo;t clear the correlation between $m$ the number of traitors in the system and, as it is in the case of the algorithm, $m$ the level of recursion in the OM algorithm. So, just to clarify, the number of traitors that the algorithm can tolerate is the same as the recursion level in this algorithm. They&rsquo;re the same $m$.</p>
<p>Leslie then formally describes the OM algorithm very succinctly:</p>
<ol>
<li>Algorithm $OM(0)$:
<ol>
<li>(1) The commander sends his value to every lieutenant.</li>
<li>(2) Each lieutenant uses the value he receives from the commander or uses the value RETREAT if he gets no value.</li>
</ol>
</li>
<li>Algorithm $OM(m)$, $m &gt; 0$:
<ol>
<li>(1) The commander sends his value to every lieutenant.</li>
<li>(2) For each $i$, let $v(i)$ be the value Lieutenant $i$ receives from the commander. Lieutenant i acts as the commander in Algorithm $OM(m - 1)$ to send the value $v(i)$ to each of the $n - 2$ other lieutenants.</li>
<li>(3) For each $i$, and each $j \neq i$, let $v(j)$ be the value Lieutenant $i$ received from Lieutenant $j$ in step (2) (using Algorithm $OM(m - 1)$). Lieutenant $i$ uses the value $majority(v_1,&hellip;v_{n-1})$.</li>
</ol>
</li>
</ol>
<p>It&rsquo;s a short algorithm, but there&rsquo;s so much packed into it. I lost count of how many times I had to re-read this thing while implementing the code.</p>
<p>The base case ($OM(0)$) is actually straightforward. The commander at a given round sends their value to every lieutenant general, and each lieutenant <em>uses</em> that value (e.g., either <em>retreat</em> or <em>attack</em>). But here&rsquo;s a nice detail: by <em>using</em> the value, it doesn&rsquo;t necessarily mean that the lieutenant will <em>execute</em> based on that value, not until the end of the algorithm. It will simply hold on to that value either as their decision (came directly from a commander) or as a set of all values received from other lieutenants, which will then be used to make a decision based on the majority in the that lieutenants' set of values.</p>
<p>Things become slightly harder to visualize and reason once we think about the actual recursive rounds ($OM(m)$).</p>
<p>First, the commander of that round will send their value to every lieutenant. <em>&ldquo;Their value&rdquo;</em> here deserves some attention. What value? Where did they get this value? If they&rsquo;re the <em>commanding general</em> (the first commander), it&rsquo;ll be the value that we want all lieutenants/nodes to agree upon. But if a lieutenant general got &ldquo;promoted&rdquo; to a commander in this round, it&rsquo;ll be the value they received from the previous commander.</p>
<p>Then, in the actual recursive step, after the current commander sends their value to every lieutenant, each lieutenant, which <em>doesn&rsquo;t include the current commander</em>  will be &ldquo;promoted&rdquo; to a commander and execute the same algorithm, but now decrementing the $m$ (the recursion level), running $OM(m-1)$. By &ldquo;to send the value $v(i)$ to each of the $n - 2$ other lieutenants,&rdquo; Leslie means that the new commander sends the message to the lieutenants and doesn&rsquo;t include itself and the previous commander.</p>
<p>A tricky bit here that may sound obvious but, once overlooked, can trigger some confusion is that this recursive step happens for each lieutenant in the round. This means the step <code>(3)</code> of the first round won&rsquo;t be executed until all current lieutenants have acted as commanders and passed the $v(i)$, which might include more and more recursive steps!</p>
<p>It might help to visualize this workflow as a tree, which actually is how some solutions are implemented:</p>
<p><img src="/images/images/byzantine4.png" alt="Fourth"></p>
<p>And then, in step 3, after each lieutenant went into the recursive steps, a given lieutenant $i$ will use, as its decision, the majority value in the set of all the values they have received.</p>
<p>In other words, a commander in a certain round &ldquo;spreads the word&rdquo; and then waits to hear back from each lieutenant, then uses, as their own decision, the majority of these values they received from each lieutenant. This is a clever technique to overcome false information, i.e., &ldquo;<em>I</em> could&rsquo;ve heard something fake, so I&rsquo;ll wait to hear back from the others before making my decision.&rdquo;</p>
<h3 id="coding-the-oral-message-algorithm">Coding the Oral Message algorithm</h3>
<p><em>Note: you can skip ahead and check the final code <a href="https://github.com/digorithm/coding-the-byzantine-generals">here</a></em></p>
<p>So what does the code look like? Let&rsquo;s start with the smallest abstraction unit, a simple message that will hold a boolean value:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#75715e">#[derive(Debug, Clone, Default, Copy)]</span>
<span style="color:#66d9ef">struct</span> <span style="color:#a6e22e">Message</span> {
    attack: <span style="color:#66d9ef">bool</span>,
}
</code></pre></div><p>A general lieutenant is also pretty simple to represent:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#75715e">#[derive(Debug, Clone, Default)]</span>
<span style="color:#66d9ef">struct</span> <span style="color:#a6e22e">General</span> {
    id: <span style="color:#66d9ef">usize</span>,
    messages: Vec<span style="color:#f92672">&lt;</span>Message<span style="color:#f92672">&gt;</span>,
    is_traitor: <span style="color:#66d9ef">bool</span>,
    decision: <span style="color:#66d9ef">bool</span>,
    total_messages_received: <span style="color:#66d9ef">usize</span>,
}
</code></pre></div><p>Each general holds a list of messages they will receive and eventually will hold a final <code>decision</code>.</p>
<p>We&rsquo;re going to use RNG to make <code>m</code> <code>General</code>s with <code>is_traitor</code> set to <code>true</code>.</p>
<p>Also finally, <code>total_messages_received</code> is a field that could help with debugging and show some cool properties later on. Not really necessary for the algorithm.</p>
<p>Receiving an order is also very straightforward:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#75715e">// Note: this is inside a `impl General {}` block
</span><span style="color:#75715e"></span><span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">receive_order</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, msg: <span style="color:#a6e22e">Message</span>, from: <span style="color:#66d9ef">usize</span>) {
 <span style="color:#66d9ef">if</span> self.messages.is_empty() {
  self.decision <span style="color:#f92672">=</span> msg.attack;
 }

 self.messages.push(msg);
 self.total_messages_received <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span>;
}
</code></pre></div><p>A bit of detail is that if the list of messages is empty, we&rsquo;re gonna set the first message&rsquo;s decision as this <code>General</code>&rsquo;s decision.</p>
<p>Then, making the decision based on the majority is also very simple:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">decide</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self) {
 <span style="color:#66d9ef">let</span> msgs <span style="color:#f92672">=</span> self
  .messages
  .iter()
  .map(<span style="color:#f92672">|</span>m<span style="color:#f92672">|</span> m.attack)
  .collect::<span style="color:#f92672">&lt;</span>Vec<span style="color:#f92672">&lt;</span><span style="color:#66d9ef">bool</span><span style="color:#f92672">&gt;&gt;</span>();


 <span style="color:#66d9ef">let</span> attack <span style="color:#f92672">=</span> msgs.iter().filter(<span style="color:#f92672">|&amp;</span>attack<span style="color:#f92672">|</span> <span style="color:#f92672">*</span>attack).count();
 <span style="color:#66d9ef">let</span> retreat <span style="color:#f92672">=</span> msgs.iter().filter(<span style="color:#f92672">|&amp;</span>attack<span style="color:#f92672">|</span> <span style="color:#f92672">!*</span>attack).count();

 <span style="color:#66d9ef">if</span> attack <span style="color:#f92672">&gt;</span> retreat {
  self.decision <span style="color:#f92672">=</span> <span style="color:#66d9ef">true</span>;
  <span style="color:#66d9ef">return</span>;
 }
 self.decision <span style="color:#f92672">=</span> <span style="color:#66d9ef">false</span>;
}
</code></pre></div><p>Count number of <code>true</code>s and <code>false</code>s and decide based on the majority.</p>
<p>That&rsquo;s pretty much it for the <code>General</code>. Oh, actually, there&rsquo;s one more thing just to help us simulate faulty <code>General</code>s; we need something to scramble orders if a given <code>General</code> instance is a traitor! If it&rsquo;s not a traitor, then just return the original message.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">next_order</span>(<span style="color:#f92672">&amp;</span>self, idx: <span style="color:#66d9ef">usize</span>) -&gt; <span style="color:#a6e22e">Message</span> {
 <span style="color:#66d9ef">if</span> self.is_traitor <span style="color:#f92672">&amp;&amp;</span> idx <span style="color:#f92672">%</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> {
  <span style="color:#66d9ef">if</span> self.decision {
   <span style="color:#66d9ef">return</span> Message { attack: <span style="color:#a6e22e">false</span> };
  } <span style="color:#66d9ef">else</span> {
   <span style="color:#66d9ef">return</span> Message { attack: <span style="color:#a6e22e">true</span> };
  }
 }
 Message {
  attack: <span style="color:#a6e22e">self</span>.decision,
 }
}
</code></pre></div><p>Also, to make things more chaotic, we not only invert the order but only invert the order if a certain index is even. Pure evil. Now onto the hard bits!</p>
<p>The Oral Message algorithm will be built around the following struct:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">struct</span> <span style="color:#a6e22e">OMAlgorithm</span> {
 <span style="color:#75715e">// Both these fields will be used later on
</span><span style="color:#75715e"></span>    is_first_commander_loyal: <span style="color:#66d9ef">bool</span>,
    original_order: <span style="color:#a6e22e">Message</span>,
}
</code></pre></div><p>Now, Rust is going to make our lives a bit harder. <code>General</code>s will hold a list of <code>Message</code>s, and this will be constantly updated as a <code>General</code> receives orders, and since this will be a recursive algorithm and we&rsquo;ll be passing lists of references to <code>General</code>s around to achieve memory safety, Rust must hurt us deeply. That&rsquo;s okay, we&rsquo;ll cope.</p>
<p>Since <code>General</code>s will be passed around and mutated, we&rsquo;ll have to use the <code>Rc&lt;RefCell&lt;T&gt;&gt;</code> pattern: <code>Rc</code> is a pointer with shared ownership while <code>RefCell</code> provides interior mutability. This means a given <code>Rc&lt;RefCell&lt;General&gt;&gt;</code> is shared, and each shared owner gets to mutate the contents (update their list of orders). The effect of mutating the contents will be seen by all of the shared owners of the outer <code>Rc</code> because the inner data is shared.</p>
<p>Sounds simple once it&rsquo;s all laid out, but it took me a while to get to this solution, especially when you could do it <em>much</em> more easily in order languages, such as Go. But data races, though&hellip; Ugh, painful.</p>
<p>Also, it would be relatively easier if we were implementing an actual protocol. Each general would be its own process, and they would communicate over RPC or HTTP endpoints; we wouldn&rsquo;t need to keep managing all these references.</p>
<p>So this is how the implementation will look like at a high level</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">impl</span> OMAlgorithm {
    <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">om_algorithm</span>(
        <span style="color:#f92672">&amp;</span>self,
        generals: <span style="color:#66d9ef">&amp;</span>[Rc<span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>],
        commander: <span style="color:#a6e22e">Rc</span><span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>,
        m: <span style="color:#66d9ef">usize</span>,
    ) {
        <span style="color:#66d9ef">if</span> m <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> {
            <span style="color:#75715e">// OM(0):
</span><span style="color:#75715e"></span>        } <span style="color:#66d9ef">else</span> {
            <span style="color:#75715e">// OM(m):
</span><span style="color:#75715e"></span>        }
    }
}
</code></pre></div><p>Where in the <code>OM(m)</code>, <code>m &gt; 0</code> block we&rsquo;ll be calling <code>om_algorithm()</code> recursively.</p>
<p>Let&rsquo;s tackle the base case first:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">impl</span> OMAlgorithm {
    <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">om_algorithm</span>(
        <span style="color:#f92672">&amp;</span>self,
        generals: <span style="color:#66d9ef">&amp;</span>[Rc<span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>],
        commander: <span style="color:#a6e22e">Rc</span><span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>,
        m: <span style="color:#66d9ef">usize</span>,
    ) {
        <span style="color:#66d9ef">if</span> m <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> {
            <span style="color:#75715e">// OM(0):
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// The commander sends his value to every lieutenant.
</span><span style="color:#75715e"></span>            <span style="color:#66d9ef">for</span> (idx, general_rc) <span style="color:#66d9ef">in</span> generals.iter().enumerate() {
                <span style="color:#66d9ef">let</span> msg_to_relay <span style="color:#f92672">=</span> commander.as_ref().borrow().next_order(idx);

                <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> general <span style="color:#f92672">=</span> general_rc.borrow_mut();

                general.receive_order(msg_to_relay, commander.as_ref().borrow().id);
            }
        } <span style="color:#66d9ef">else</span> {
            <span style="color:#75715e">// OM(1)
</span><span style="color:#75715e"></span>        }
    }
}

</code></pre></div><p>Note that we do:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> msg_to_relay <span style="color:#f92672">=</span> commander.as_ref().borrow().next_order(idx);
</code></pre></div><p>To decide whether we&rsquo;re relaying the original message or a faulty one, in case the commander of this round is faulty.</p>
<p>Then, we mutably borrow a <code>General</code> from the list of <code>General</code>s and call its <code>receive_order</code>. And that&rsquo;s it; that&rsquo;s the whole base case, as stated by Leslie:</p>
<blockquote>
<p>OM(0): The commander sends his value to every lieutenant</p>
</blockquote>
<p>Then, the $OM(m), m &gt; 0$ case has three parts:</p>
<ol>
<li>First, the commander of the round sends a message to every lieutenant
<ol>
<li>In our code, this means the commander is the <code>commander: Rc&lt;RefCell&lt;General&gt;&gt;</code> in the function argument of this specific invocation of <code>om_algorithm()</code>, and the lieutenants are the list we&rsquo;ve received in this function call, i.e. the <code>generals: &amp;[Rc&lt;RefCell&lt;General&gt;&gt;]</code></li>
</ol>
</li>
<li>Second, for each <code>General</code> lieutenant in  <code>generals: &amp;[Rc&lt;RefCell&lt;General&gt;&gt;]</code>, we&rsquo;ll be calling <code>om_algorithm</code>, again, but now passing in list of <code>General</code>s without the <em>current</em> commander, and the new commander being this <code>General</code> (the current one in the &ldquo;for each&rdquo;)
<ol>
<li>This has interesting behaviors, as it&rsquo;s the recursive step. It might take some time to click.</li>
</ol>
</li>
<li>Lastly, and putting it in the simplest way: for each general in this scope&rsquo;s <code>generals</code>, we&rsquo;ll &ldquo;ask&rdquo; them to decide the final order based on the majority each has in their local list of orders.</li>
</ol>
<p>It&rsquo;s much easier to see in code, actually.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">impl</span> OMAlgorithm {
    <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">om_algorithm</span>(
        <span style="color:#f92672">&amp;</span>self,
        generals: <span style="color:#66d9ef">&amp;</span>[Rc<span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>],
        commander: <span style="color:#a6e22e">Rc</span><span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>,
        m: <span style="color:#66d9ef">usize</span>,
    ) {
        <span style="color:#66d9ef">if</span> m <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> {
            <span style="color:#75715e">// OM(0):
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// The commander sends his value to every lieutenant.
</span><span style="color:#75715e"></span>            <span style="color:#66d9ef">for</span> (idx, general_rc) <span style="color:#66d9ef">in</span> generals.iter().enumerate() {
                <span style="color:#66d9ef">let</span> msg_to_relay <span style="color:#f92672">=</span> commander.as_ref().borrow().next_order(idx);

                <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> general <span style="color:#f92672">=</span> general_rc.borrow_mut();

                general.receive_order(msg_to_relay, commander.as_ref().borrow().id);
            }
        } <span style="color:#66d9ef">else</span> {
            <span style="color:#75715e">// OM(1) (1):
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// The commander sends his value to every lieutenant.
</span><span style="color:#75715e"></span>            <span style="color:#66d9ef">for</span> (idx, general_rc) <span style="color:#66d9ef">in</span> generals.iter().enumerate() {
                <span style="color:#66d9ef">let</span> msg_to_relay <span style="color:#f92672">=</span> commander.as_ref().borrow().next_order(idx);

                <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> general <span style="color:#f92672">=</span> general_rc.borrow_mut();

                general.receive_order(msg_to_relay, commander.as_ref().borrow().id);
            }

            <span style="color:#75715e">// OM(1) (2):
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// For each i, let v(i) be the value Lieutenant i receives
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// from the commander, or else be RETREAT if he
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// receives no value.
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// Lieutenant i acts as the commander in Algorithm OM(m-1)
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// to send the value v(i) to each of the n-2 other lieutenants.
</span><span style="color:#75715e"></span>            <span style="color:#66d9ef">for</span> general_rc <span style="color:#66d9ef">in</span> generals {
                <span style="color:#66d9ef">let</span> next_commander <span style="color:#f92672">=</span> general_rc.as_ref().borrow();

                <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> new_generals: Vec<span style="color:#f92672">&lt;</span>Rc<span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#f92672">=</span> vec<span style="color:#f92672">!</span>[];

                <span style="color:#66d9ef">for</span> general <span style="color:#66d9ef">in</span> generals {
                    <span style="color:#66d9ef">if</span> general.as_ref().borrow().id <span style="color:#f92672">!=</span> next_commander.id {
                        new_generals.push(Rc::clone(general));
                    }
                }
                drop(next_commander);

                <span style="color:#75715e">// Sending message v(i) received from the commander
</span><span style="color:#75715e"></span>                self.om_algorithm(<span style="color:#f92672">&amp;</span>new_generals, Rc::clone(general_rc), m <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>);
            }

            <span style="color:#75715e">// (3) For each i, and each j != i, let v(j) be the value Lieutenant i
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// received from Lieutenant j in step (2) using Algorithm OM(m - 1),
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// or else RETREAT if he received no such value.
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// Lieutenant i uses the value majority (vl, ..., vn-1 ).
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// Note: honestly, this was the most subtle part of the whole algorithm...
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// Each general is updating their beliefs based on what they heard so far.
</span><span style="color:#75715e"></span>            <span style="color:#66d9ef">for</span> general <span style="color:#66d9ef">in</span> generals {
                general.borrow_mut().decide();
            }
        }
    }
}

</code></pre></div><p>And that&rsquo;s it! It&rsquo;s short, but it has a lot of details that will be more apparent the more you look at and reason about the code.</p>
<p>But, now, how do we decide whether the algorithm was successful? That&rsquo;s a step that can be tricky to debug if you get it wrong. To decide that, we have to refer back to the Interactive Inconsistencies laid out by Leslie at the beginning of the paper:</p>
<blockquote>
<p>IC1: All loyal lieutenants obey the same order.
IC2: If the commanding general is loyal, then every loyal</p>
</blockquote>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">was_successful</span>(<span style="color:#f92672">&amp;</span>self, generals: <span style="color:#66d9ef">&amp;</span>[Rc<span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;</span>]) -&gt; <span style="color:#66d9ef">bool</span> {
    <span style="color:#75715e">// Here&#39;s how Lamport defines success:
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// IC1: All loyal lieutenants obey the same order.
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// IC2: If the commanding general is loyal, then every loyal
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// lieutenant obeys the order he sends.
</span><span style="color:#75715e"></span>
    <span style="color:#75715e">// Decision of each loyal general
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> loyal_decisions <span style="color:#f92672">=</span> vec<span style="color:#f92672">!</span>[];

    <span style="color:#66d9ef">for</span> general <span style="color:#66d9ef">in</span> generals {
        <span style="color:#66d9ef">let</span> general <span style="color:#f92672">=</span> general.as_ref().borrow();
        <span style="color:#66d9ef">if</span> <span style="color:#f92672">!</span>general.is_traitor {
            loyal_decisions.push(general.decision)
        }
    }

    <span style="color:#75715e">// Was there consensus amongst all loyal generals?
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> loyal_consensus <span style="color:#f92672">=</span> loyal_decisions.windows(<span style="color:#ae81ff">2</span>).all(<span style="color:#f92672">|</span>w<span style="color:#f92672">|</span> w[<span style="color:#ae81ff">0</span>] <span style="color:#f92672">==</span> w[<span style="color:#ae81ff">1</span>]);

    <span style="color:#75715e">// If not, we&#39;ve broken IC1
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">if</span> <span style="color:#f92672">!</span>loyal_consensus {
        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>;
    }

    <span style="color:#75715e">// If we had consensus among loyal generals and the first commander
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// is loyal, does the consensus match the original order?
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// If it doesn&#39;t, we&#39;ve broken IC2.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">if</span> self.is_first_commander_loyal {
        <span style="color:#75715e">// Then the loyal consensus should match original order
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">if</span> self.original_order.attack <span style="color:#f92672">!=</span> loyal_decisions[<span style="color:#ae81ff">0</span>] {
            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>;
        }
    }

    <span style="color:#75715e">// IC1 and IC2 hold
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">true</span>
}
</code></pre></div><p>In short, <code>was_successful</code> is just following Leslie&rsquo;s 2 Interactive Consistencies.</p>
<p>Now, all we have to do is set up a nice environment for some experiments, which include:</p>
<ol>
<li>Creating many generals;</li>
<li>Turning <code>m</code> generals into traitors;</li>
<li>Selecting one of these generals as the initial commanding general;</li>
<li>Running the algorithm with this setup;</li>
<li>Checking if it <code>was_suceessful()</code>.</li>
</ol>
<p>Also, it would be nice to run this experiment many times, letting some RNG pick different combinations of traitors and commanding generals. This is simple enough, though, so I&rsquo;ll just lay out the code:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#75715e">// Configuration params
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> num_of_generals <span style="color:#f92672">=</span> <span style="color:#ae81ff">4</span>;
    <span style="color:#66d9ef">let</span> num_of_traitors <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span>;
    <span style="color:#66d9ef">let</span> m <span style="color:#f92672">=</span> num_of_traitors;
    <span style="color:#66d9ef">let</span> num_of_experiments <span style="color:#f92672">=</span> <span style="color:#ae81ff">10</span>;

    <span style="color:#66d9ef">for</span> _i <span style="color:#66d9ef">in</span> <span style="color:#ae81ff">0</span>..num_of_experiments {
        <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> generals: Vec<span style="color:#f92672">&lt;</span>Rc<span style="color:#f92672">&lt;</span>RefCell<span style="color:#f92672">&lt;</span>General<span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#f92672">=</span> vec<span style="color:#f92672">!</span>[];

        <span style="color:#75715e">// Create all generals, set `is_traitor` as false initially
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">for</span> i <span style="color:#66d9ef">in</span> <span style="color:#ae81ff">0</span>..num_of_generals {
            <span style="color:#66d9ef">let</span> g <span style="color:#f92672">=</span> Rc::new(RefCell::new(General::new(i <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, <span style="color:#66d9ef">false</span>)));
            generals.push(g);
        }

        <span style="color:#75715e">// Pick `num_of_traitors` random generals and set them as traitors
</span><span style="color:#75715e"></span>        <span style="color:#75715e">// Note that this could also be the first commanding general
</span><span style="color:#75715e"></span>        generals
            .choose_multiple(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> rand::thread_rng(), num_of_traitors)
            .for_each(<span style="color:#f92672">|</span>traitor<span style="color:#f92672">|</span> {
                println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;Traitor: General #{}\n&#34;</span>, traitor.as_ref().borrow().id);
                traitor.as_ref().borrow_mut().is_traitor <span style="color:#f92672">=</span> <span style="color:#66d9ef">true</span>;
            });

        <span style="color:#66d9ef">let</span> order <span style="color:#f92672">=</span> Message { attack: <span style="color:#a6e22e">true</span> };

        <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> om_algorithm <span style="color:#f92672">=</span> OMAlgorithm {
            is_first_commander_loyal: <span style="color:#a6e22e">true</span>,
            original_order: <span style="color:#a6e22e">order</span>,
        };

        <span style="color:#75715e">// Randomly pick first commanding general
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">let</span> first_commander <span style="color:#f92672">=</span> rand::thread_rng().gen_range(<span style="color:#ae81ff">0</span>..num_of_generals);
        <span style="color:#66d9ef">let</span> first_commander_rc <span style="color:#f92672">=</span> Rc::clone(<span style="color:#f92672">&amp;</span>generals[first_commander]);

        first_commander_rc.borrow_mut().decision <span style="color:#f92672">=</span> order.attack;

        <span style="color:#75715e">// Remove first commanding general out of the initial list of lieutenant generals
</span><span style="color:#75715e"></span>        generals.remove(first_commander);

        <span style="color:#66d9ef">if</span> first_commander_rc.as_ref().borrow().is_traitor {
            om_algorithm.is_first_commander_loyal <span style="color:#f92672">=</span> <span style="color:#66d9ef">false</span>
        }

        <span style="color:#75715e">// Start the algorithm
</span><span style="color:#75715e"></span>        om_algorithm.om_algorithm(<span style="color:#f92672">&amp;</span>generals, first_commander_rc, m);

        <span style="color:#75715e">// Calculate total messages sent for analytical purposes
</span><span style="color:#75715e"></span>        om_algorithm.get_total_messages(<span style="color:#f92672">&amp;</span>generals);

        <span style="color:#75715e">// Check whether it was successful
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">let</span> successful <span style="color:#f92672">=</span> om_algorithm.was_successful(<span style="color:#f92672">&amp;</span>generals);

        println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;successful: {:?}\n&#34;</span>, successful);

        <span style="color:#66d9ef">if</span> <span style="color:#f92672">!</span>successful {
            println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;Found a case where consensus isn&#39;t achieved\n&#34;</span>);
            <span style="color:#66d9ef">break</span>;
        }
    }
}
</code></pre></div><p>Now we can play with different parameters and see how it affects the results. For instance, with 4 generals and 1 traitor ($m = 1$):</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">Traitor: General #4

I&#39;m commander #3. Sending message: true. m: 1

General #1&#39;s first order received: true
General #1 receiving order (true) from commander #3

General #2&#39;s first order received: true
General #2 receiving order (true) from commander #3

General #4&#39;s first order received: true
General #4 receiving order (true) from commander #3

### general #1 acting as commander ###

I&#39;m commander #1. Sending message: true. m: 0

General #2 receiving order (true) from commander #1

General #4 receiving order (true) from commander #1

General #1 decision after round OM(0): true

### general #2 acting as commander ###

I&#39;m commander #2. Sending message: true. m: 0

General #1 receiving order (true) from commander #2

General #4 receiving order (true) from commander #2

General #2 decision after round OM(0): true

### general #4 acting as commander ###

I&#39;m commander #4. Sending message: true. m: 0

General #1 receiving order (false) from commander #4

General #2 receiving order (true) from commander #4

General #4 decision after round OM(0): true

deciding for general #1
Deciding majority for general #1: [true, true, false]
deciding for general #2
Deciding majority for general #2: [true, true, true]
deciding for general #4
Deciding majority for general #4: [true, true, true]
General #3 decision after round OM(1): true

total_messages: 9

successful: true
</code></pre></div><p>Note that this includes many more log messages than the code shown above. I thought it was really cool seeing the log messages as it helped a lot to visualize how the algorithm is behaving, just like a tree! You can find this version on the <a href="https://github.com/digorithm/coding-the-byzantine-generals">GitHub repo</a>.</p>
<p>Let&rsquo;s try 4 generals and 2 traitors ($m = 2$). Leslie states that it would be impossible to succeed given these assumptions (sync network model, permissioned, no cryptography), as we wouldn&rsquo;t follow the $3m + 1$ bound. In other words, we can only succeed if we have $f \geq 3m + 1$, where $f$ is the number of generals and $m$ is the number of traitors. If we use $m = 2$, we&rsquo;ll have</p>
<p>$$
f \geq 3*2 + 1
$$</p>
<p>$$
f \geq 6 + 1 \<br>
$$</p>
<p>$$
f \geq 7 \<br>
$$</p>
<p>We would need at least 7 generals in order to survive 2 traitors.</p>
<p>Let&rsquo;s see how the algorithm behaves with 4 generals and 2 traitors:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">Traitor: General #3

Traitor: General #4

I&#39;m commander #1. Sending message: true. m: 2

General #2&#39;s first order received: true
General #2 receiving order (true) from commander #1

General #3&#39;s first order received: true
General #3 receiving order (true) from commander #1

General #4&#39;s first order received: true
General #4 receiving order (true) from commander #1

### general #2 acting as commander ###

I&#39;m commander #2. Sending message: true. m: 1

General #3 receiving order (true) from commander #2

General #4 receiving order (true) from commander #2

### general #3 acting as commander ###

I&#39;m commander #3. Sending message: true. m: 0

General #4 receiving order (false) from commander #3

General #3 decision after round OM(0): true

### general #4 acting as commander ###

I&#39;m commander #4. Sending message: true. m: 0

General #3 receiving order (false) from commander #4

General #4 decision after round OM(0): true

deciding for general #3
Deciding majority for general #3: [true, true, false]
deciding for general #4
Deciding majority for general #4: [true, true, false]
General #2 decision after round OM(1): true

### general #3 acting as commander ###

I&#39;m commander #3. Sending message: true. m: 1

General #2 receiving order (false) from commander #3

General #4 receiving order (true) from commander #3

### general #2 acting as commander ###

I&#39;m commander #2. Sending message: true. m: 0

General #4 receiving order (true) from commander #2

General #2 decision after round OM(0): true

### general #4 acting as commander ###

I&#39;m commander #4. Sending message: true. m: 0

General #2 receiving order (false) from commander #4

General #4 decision after round OM(0): true

deciding for general #2
Deciding majority for general #2: [true, false, false]
deciding for general #4
Deciding majority for general #4: [true, true, false, true, true]
General #3 decision after round OM(1): true

### general #4 acting as commander ###

I&#39;m commander #4. Sending message: true. m: 1

General #2 receiving order (false) from commander #4

General #3 receiving order (true) from commander #4

### general #2 acting as commander ###

I&#39;m commander #2. Sending message: false. m: 0

General #3 receiving order (false) from commander #2

General #2 decision after round OM(0): false

### general #3 acting as commander ###

I&#39;m commander #3. Sending message: true. m: 0

General #2 receiving order (false) from commander #3

General #3 decision after round OM(0): true

deciding for general #2
Deciding majority for general #2: [true, false, false, false, false]
deciding for general #3
Deciding majority for general #3: [true, true, false, true, false]
General #4 decision after round OM(1): true

deciding for general #2
Deciding majority for general #2: [true, false, false, false, false]
deciding for general #3
Deciding majority for general #3: [true, true, false, true, false]
deciding for general #4
Deciding majority for general #4: [true, true, false, true, true]
General #1 decision after round OM(2): true

total_messages: 15

successful: false

Found a case where consensus isn&#39;t achieved
</code></pre></div><p>Well, I guess Leslie was right after all?</p>
<p>Change <code>num_of_generals</code> to 7, and it will succeed. Pretty cool, uh?</p>
<h2 id="where-to-go-from-here">Where to go from here</h2>
<p>Just sign the message, for god&rsquo;s sake!</p>
<p>The problem and solution above are really fun and all. But, come on, it&rsquo;s 2022, and we have cryptography. Why are we allowing messages to be forged by the traitors?</p>
<p>Removing the ability to forge messages simplifies the BGP a lot. The message looks like <code>v:j:i</code> where <code>v</code> is the value (e.g., either attack or retreat, true or false), signed by <code>j</code>, and then signed by `i'.</p>
<p>The implementation of this approach is really dependent on the actual business logic of the system, so I won&rsquo;t be doing that now. But from the A1-A4 assumptions on the original paper, we can simplify the phrasing that states that to implement a BGP with signed messages, one must guarantee that:</p>
<ul>
<li>A1: Every message that is sent is delivered correctly;</li>
<li>A2: The receiver of a message knows who sent it;</li>
<li>A3: The absence of a message can be detected;</li>
<li>A4: A loyal general&rsquo;s signature cannot be forged, and any alteration of the contents of his signed messages can be detected. Anyone can verify the authenticity of a general&rsquo;s signature.</li>
</ul>
<p>And the end result with PKI (private-key infrastructure, cryptographically secure signatures) is that, instead of  $f \geq 3m + 1$, it can tolerate up to 50% (or $n/2$) of faulty nodes, hence the famous 51% attack. A much better result by modifying the algorithm slightly to include signatures. Cryptography is awesome, isn&rsquo;t it?</p>
<p>The coding exercise above was really nice to build intuition on the problem and its first solution, but the <a href="https://decentralizedthoughts.github.io/2021-10-29-consensus-cheat-sheet/">rabbit hole is really deep</a>. One can continue by implementing signatures on the solution described here. Then, slowly relaxing other assumptions (synchronicity, permission model), making the problem and solution harder but more powerful and practical.</p>
]]></content></item><item><title>Let's build an LC-3 Virtual Machine</title><link>/posts/lets-build-an-lc-3-virtual-machine/</link><pubDate>Fri, 27 Aug 2021 00:00:00 +0000</pubDate><guid>/posts/lets-build-an-lc-3-virtual-machine/</guid><description>Virtual Machines (VMs) are a magical thing: a computer being emulated inside a physical computer. Since this emulated computer isn&amp;rsquo;t physical, we call it &amp;ldquo;virtual&amp;rdquo;. Such a simple description for something so powerful.
From a practical perspective, VMs allow users to safely run programs in an isolated environment: the emulated machine.
Why build a Virtual Machine from scratch So, why build one when there are already so many great VMs out there?</description><content type="html"><![CDATA[<p>Virtual Machines (VMs) are a magical thing: a computer being emulated inside a physical computer. Since this emulated computer isn&rsquo;t physical, we call it &ldquo;virtual&rdquo;. Such a simple description for something so powerful.</p>
<p>From a practical perspective, VMs allow users to safely run programs in an isolated environment: the emulated machine.</p>
<h2 id="why-build-a-virtual-machine-from-scratch">Why build a Virtual Machine from scratch</h2>
<p>So, why build one when there are already so many great VMs out there?
Simply put: To better understand how computers work. Personally, whenever I need to understand something complex enough that reading by itself won’t give me a deep understanding, I must build it. That which I cannot build, I cannot deeply understand.</p>
<p>I’ve found that learning how to build a simple VM is a great and seemingly underrated way to learn the basic philosophy behind assembly and assemblers.</p>
<p>Also, Justin Meiners and Ryan Pendleton already put out a <a href="https://justinmeiners.github.io/lc3-vm/">great piece on building an LC-3 VM</a>.
I’m writing this document as a complement to this work. I go into a little more details and some of the underlying ideas I found tricky to understand. And as an alternative to writing an LC-3 in C, I’m doing it in Rust.</p>
<p>You can find the final source code <a href="https://github.com/digorithm/LC-3-Rust">here</a>.</p>
<h2 id="how-to-read-this-document">How to read this document</h2>
<p>This guide is relatively long. VMs aren&rsquo;t simple, and there is a lot of knowledge about it that, as I went through it, I found to be sort of &ldquo;hidden,&rdquo; or &ldquo;heavy assumed to be known,&rdquo; and that made understanding much harder for me.</p>
<p>For instance, I studied bitwise operations (such as shifts) a long time ago, I know the concept, but I have never had the chance to use it directly. And because of that, many tricks used in systems-level programming went straight over my head &ndash; these are &ldquo;tribal&rdquo; knowledge that people assume to be trivial, and therefore it is barely touched in these other documents.</p>
<p>I wanted to follow a different approach, a first-principles approach. I try to go over the most fundamental principles and tricks used to build a VM, with little prerequisite knowledge in systems programming other than entry-level Rust knowledge.</p>
<p>I&rsquo;ve learned a lot along the way &ndash; systems programming is super fun. That said, let&rsquo;s get to it.</p>
<h2 id="the-vm-abstraction">The VM abstraction</h2>
<p>The virtual machine will have two main components: registers and memory. It&rsquo;s much simpler than it sounds.</p>
<p>Memory is where we will store a program&rsquo;s binary representation; it&rsquo;s a bounded array of bytes. Yup, that&rsquo;s all there is to it, a good old array that will contain instructions and the indices are the addresses.</p>
<p><img src="/images/images/vm.png" alt="The vm"></p>
<p>When loading an LC-3 program into memory, we do it at the address/index <code>0x3000</code> (<code>12288</code> in decimal), the program section of the VM&rsquo;s memory. Everything before this index is reserved for other things we&rsquo;ll talk about later. Here&rsquo;s the memory layout for the LC-3 memory:</p>
<p><img src="/images/images/20210714174252.png" alt="LC-3 memory layout"></p>
<p>Registers will store data that our opcode (Operation Code) will operate on. Physically, think of registers like a type of memory that&rsquo;s much closer to the CPU than, say, the RAM.</p>
<p>Here we have 7 of these general-purpose registers. On top of that, we have two special purpose registers that I&rsquo;ll talk about below.</p>
<h3 id="controlling-the-program-flow-with-the-program-counter-pc-register">Controlling the program flow with the Program Counter (PC) Register</h3>
<p>The <strong>program counter</strong> (PC) stores the address of the next instruction in memory to be executed. In other words, it will point to an index/address in our array that represents the memory of the VM.</p>
<p>Manipulating this PC register is how we &ldquo;walk&rdquo; through each instruction and perform loops, conditional branching, and jumps; simply changing the index/address will affect the execution of the next instruction. For instance, in a loop instruction, we change the PC to go back a few &ldquo;steps&rdquo; until we meet a specific condition.</p>
<p>But how do we check for these logical conditions? Enters our next special purpose register.</p>
<h3 id="checking-for-logical-conditions-with-the-condition-flags-cond-register">Checking for logical conditions with the Condition Flags (Cond) Register</h3>
<p>And talking about conditions brings us to the next special register: The condition flags register that tells us about the last computation. This register checks for conditions to perform control flow tasks (loops, ifs, etc.). It&rsquo;s a straightforward one, and it might not immediately make sense how we use it, but all it does is store the signal (negative, zero, or positive) status of the last operation that happened within the machine. We&rsquo;ll go over it in more detail later!</p>
<h3 id="structuring-the-project">Structuring the project</h3>
<p>This is how I&rsquo;m structuring the project:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">LC_3 git:(master) ✗ tree src
src
├── hardware
│   ├── instruction
│   │   └── mod.rs // Instruction-related code
│   ├── mod.rs // Glue-code for all the virtual hardware
│   ├── register
│   │   └── mod.rs // Register-related code 
│   └── vm
│       └── mod.rs // High-level VM-related code (uses the registers/instruction)
└── main.rs
</code></pre></div><p>This is dead simple to represent in Rust; In <code>src/hardware/register/mod.rs</code> we have the abstraction for our registers:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">struct</span> <span style="color:#a6e22e">Registers</span> {
    <span style="color:#66d9ef">pub</span> r0: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r1: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r2: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r3: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r4: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r5: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r6: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> r7: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> pc: <span style="color:#66d9ef">u16</span>,
    <span style="color:#66d9ef">pub</span> cond: <span style="color:#66d9ef">u16</span>,
}

<span style="color:#66d9ef">impl</span> Registers {
    <span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">new</span>() -&gt; <span style="color:#a6e22e">Registers</span> {
        Registers {
            r0: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r1: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r2: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r3: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r4: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r5: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r6: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            r7: <span style="color:#ae81ff">0</span>,        <span style="color:#75715e">// general purpose register
</span><span style="color:#75715e"></span>            pc: <span style="color:#a6e22e">PC_START</span>, <span style="color:#75715e">// program counter
</span><span style="color:#75715e"></span>            cond: <span style="color:#ae81ff">0</span>,      <span style="color:#75715e">// condition flag
</span><span style="color:#75715e"></span>        }
    }

    <span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">update</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, index: <span style="color:#66d9ef">u16</span>, value: <span style="color:#66d9ef">u16</span>) {
        <span style="color:#66d9ef">match</span> index {
            <span style="color:#ae81ff">0</span> <span style="color:#f92672">=&gt;</span> self.r0 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">1</span> <span style="color:#f92672">=&gt;</span> self.r1 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">2</span> <span style="color:#f92672">=&gt;</span> self.r2 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">3</span> <span style="color:#f92672">=&gt;</span> self.r3 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">4</span> <span style="color:#f92672">=&gt;</span> self.r4 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">5</span> <span style="color:#f92672">=&gt;</span> self.r5 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">6</span> <span style="color:#f92672">=&gt;</span> self.r6 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">7</span> <span style="color:#f92672">=&gt;</span> self.r7 <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">8</span> <span style="color:#f92672">=&gt;</span> self.pc <span style="color:#f92672">=</span> value,
            <span style="color:#ae81ff">9</span> <span style="color:#f92672">=&gt;</span> self.cond <span style="color:#f92672">=</span> value,
            _ <span style="color:#f92672">=&gt;</span> panic<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;Index out of bound&#34;</span>),
        }
    }

    <span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">get</span>(<span style="color:#f92672">&amp;</span>self, index: <span style="color:#66d9ef">u16</span>) -&gt; <span style="color:#66d9ef">u16</span> {
        <span style="color:#66d9ef">match</span> index {
            <span style="color:#ae81ff">0</span> <span style="color:#f92672">=&gt;</span> self.r0,
            <span style="color:#ae81ff">1</span> <span style="color:#f92672">=&gt;</span> self.r1,
            <span style="color:#ae81ff">2</span> <span style="color:#f92672">=&gt;</span> self.r2,
            <span style="color:#ae81ff">3</span> <span style="color:#f92672">=&gt;</span> self.r3,
            <span style="color:#ae81ff">4</span> <span style="color:#f92672">=&gt;</span> self.r4,
            <span style="color:#ae81ff">5</span> <span style="color:#f92672">=&gt;</span> self.r5,
            <span style="color:#ae81ff">6</span> <span style="color:#f92672">=&gt;</span> self.r6,
            <span style="color:#ae81ff">7</span> <span style="color:#f92672">=&gt;</span> self.r7,
            <span style="color:#ae81ff">8</span> <span style="color:#f92672">=&gt;</span> self.pc,
            <span style="color:#ae81ff">9</span> <span style="color:#f92672">=&gt;</span> self.cond,
            _ <span style="color:#f92672">=&gt;</span> panic<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;Index out of bound. &#34;</span>),
        }
    }
}
</code></pre></div><p>Notice how we&rsquo;re initializing the PC as: <code>pc: PC_START,</code>, where <code>PC_START</code> is <code>0x3000</code>. That&rsquo;s because, as we&rsquo;ve seen in the specs, this is where the space in the VM&rsquo;s memory reserved for the user&rsquo;s program starts.</p>
<p>Also, notice that we&rsquo;re explicitly using <code>u16</code> (unsigned 16 bits) instead of the usual <code>u8</code>. We&rsquo;ll talk about this soon enough!</p>
<p>Then, for our condition flag register, its goal is to store the information about the latest computation, which we will then use to test logical conditions. It&rsquo;s a simple <code>Enum</code>, but it contains some tricks:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">enum</span> <span style="color:#a6e22e">ConditionFlag</span> {
    POS <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">0</span>, <span style="color:#75715e">// Positive
</span><span style="color:#75715e"></span>    ZRO <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">1</span>, <span style="color:#75715e">// Zero
</span><span style="color:#75715e"></span>    NEG <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">2</span>, <span style="color:#75715e">// Negative
</span><span style="color:#75715e"></span>}
</code></pre></div><p>The <code>&lt;&lt;</code> operator is a left bit shift operator. It&rsquo;s simpler than it looks: <code>n &lt;&lt; k</code> means we&rsquo;re moving (or shifting) the bits in the binary representation of the number <code>n</code> by <code>k</code>. for instance, 1 in binary representation is 0000000000000001.</p>
<p><code>1 &lt;&lt; 2</code> means we&rsquo;re shifting the bits twice to the left so that the <code>1</code> at the end of <code>0000000000000001</code> will effectively move to the left, twice. It ends up being <code>0000000000000100</code>, which in decimal representation is 4. Thus, <code>1 &lt;&lt; 2 == 4</code>. So why are we storing 1, 2, 4 here? Glad you asked. In binary, with 3 bits only:</p>
<ul>
<li><code>1 == 001</code></li>
<li><code>2 == 010</code></li>
<li><code>4 == 100</code></li>
</ul>
<p>So we&rsquo;re playing with the possible conditional flags settings! Because the condition instruction will be <code>nzp</code> (neg, zero, pos) and only one can be set at a time, it will either be <code>001</code> (positive set <code>nz1</code>) <code>010</code> (zero set, <code>n1p</code>) <code>100</code> (negative set, <code>1zp</code>). And these three binary values are 1, 2, and 4 in decimal base. How cool is that?!</p>
<p>Now we&rsquo;ve gotta add one more method to our <code>Registers</code> implementation: one to update the condition register based on the last operation on a given (general purpose) register:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">update_r_cond_register</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, r: <span style="color:#66d9ef">u16</span>) {
    <span style="color:#66d9ef">if</span> self.get(r) <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> {
        <span style="color:#75715e">// Note that `9` is the register number 9, 
</span><span style="color:#75715e"></span>        <span style="color:#75715e">// which is the cond register
</span><span style="color:#75715e"></span>        self.update(<span style="color:#ae81ff">9</span>, ConditionFlag::ZRO <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    } <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> (self.get(r) <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">15</span>) <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
        <span style="color:#75715e">// a 1 in the left-most bit indicates negative
</span><span style="color:#75715e"></span>        self.update(<span style="color:#ae81ff">9</span>, ConditionFlag::NEG <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    } <span style="color:#66d9ef">else</span> {
        self.update(<span style="color:#ae81ff">9</span>, ConditionFlag::POS <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    }
}
</code></pre></div><h2 id="what-does-the-lc-3-compiled-binary-look-like">What does the LC-3 compiled binary look like?</h2>
<p>Now that we have the skeleton of our VM&rsquo;s abstraction somewhat ready, let&rsquo;s take a step back and see how an LC-3 compiled binary looks like.</p>
<p>Under <code>examples/</code> we have an already compiled <code>hello_world</code> program for the LC-3. Let&rsquo;s try reading it and seeing what it looks like:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> data <span style="color:#f92672">=</span> fs::read(args[<span style="color:#ae81ff">1</span>].clone()).expect(<span style="color:#e6db74">&#34;Unable to read file&#34;</span>);

println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;data: {:?}\n&#34;</span>, data);
</code></pre></div><p>Output:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">data: [48, 0, 224, 2, 240, 34, 240, 37, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33, 0, 0]
</code></pre></div><p>As expected: gibberish.</p>
<p>Okay, so, quickly taking a look at the <code>fs::read</code> docs we see that its signature is: <code>pub fn read&lt;P: AsRef&lt;Path&gt;&gt;(path: P) -&gt; io::Result&lt;Vec&lt;u8&gt;&gt;</code> meaning, it returns a vector of 8 bits.</p>
<p>However, LC-3 operates with <strong>16 bits per instruction</strong>!</p>
<p>We have to change how we&rsquo;re reading the file to read it expecting 16 bits instead of 8.</p>
<p>Let&rsquo;s see how the human-readable hello world program in LC-3 assembly looks like:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-asm" data-lang="asm"><span style="color:#a6e22e">.ORIG</span> <span style="color:#66d9ef">x3000</span>                        <span style="color:#75715e">; this is the address in memory where the program will be loaded
</span><span style="color:#75715e"></span><span style="color:#66d9ef">LEA</span> <span style="color:#66d9ef">R0</span>, <span style="color:#66d9ef">HELLO_STR</span>                  <span style="color:#75715e">; load the address of the HELLO_STR string into R0
</span><span style="color:#75715e"></span><span style="color:#66d9ef">PUTs</span>                               <span style="color:#75715e">; output the string pointed to by R0 to the console
</span><span style="color:#75715e"></span><span style="color:#66d9ef">HALT</span>                               <span style="color:#75715e">; halt the program
</span><span style="color:#75715e"></span><span style="color:#66d9ef">HELLO_STR</span> <span style="color:#66d9ef">.STRINGZ</span> <span style="color:#e6db74">&#34;Hello World!&#34;</span>  <span style="color:#75715e">; store this string here in the program
</span><span style="color:#75715e"></span><span style="color:#66d9ef">.END</span>                               <span style="color:#75715e">; mark the end of the file
</span></code></pre></div><p>The first line (<code>.ORIG x3000</code>) means that the first 16 bits read from the compiled binary tell the VM the position in memory where the program starts.</p>
<p>Back to reading and loading the compiled binary, but now expecting <code>u16</code> instead of <code>u8</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#75715e">// Note the `read_u16`, forcing it to read as u16 and not u8.
</span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> base_address <span style="color:#f92672">=</span> f.read_u16::<span style="color:#f92672">&lt;</span>BigEndian<span style="color:#f92672">&gt;</span>().expect(<span style="color:#e6db74">&#34;error&#34;</span>);

<span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> address <span style="color:#f92672">=</span> base_address <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>;
<span style="color:#66d9ef">loop</span> {
    <span style="color:#66d9ef">match</span> f.read_u16::<span style="color:#f92672">&lt;</span>BigEndian<span style="color:#f92672">&gt;</span>() {
        Ok(instruction) <span style="color:#f92672">=&gt;</span> {
            println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;address: {:?} instruction: {:?}\n&#34;</span>, address, instruction);
            address <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span>;
        }
        Err(e) <span style="color:#f92672">=&gt;</span> {
            <span style="color:#66d9ef">if</span> e.kind() <span style="color:#f92672">==</span> std::io::ErrorKind::UnexpectedEof {
                println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;OK&#34;</span>)
            } <span style="color:#66d9ef">else</span> {
                println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;failed: {}&#34;</span>, e);
            }
            <span style="color:#66d9ef">break</span>;
        }
    }
}
</code></pre></div><h3 id="endianness">Endianness</h3>
<p>Note that when we&rsquo;re reading the 16 bits chunks, we tell Rust we want it as <code>BigEndian</code>: <code>f.read_u16::&lt;BigEndian&gt;()</code>.</p>
<p>Without diving <em>too</em> deep into it, endianness is the order or direction in which the &ldquo;machine&rdquo; reads binary data. You can either read from left to right or right to left. The order is specific only to <em>byte</em> ordering and not <em>bit</em> ordering.</p>
<p>For instance, if we have only one byte, <code>0000 0010</code> (<code>2</code> in decimal), it will be the same in big-endian or little-endian. However, the ordering is affected once we have more than 1 byte.</p>
<p>Big-endian means we&rsquo;re storing the &ldquo;big end&rdquo; first, then the rest. Little-endian means storing the &ldquo;little end&rdquo; first. This big/little end thing means the <em>most significant byte</em>, the byte in a binary value that holds the biggest position.</p>
<p>In <code>00000010</code> (<code>2</code>), the left-most zero is the most significant one; changing it to 1 would cause the <em>most significant</em> change to the number, it would turn it into <code>10000010</code>, which is <code>130</code> in decimal.</p>
<p>Changing the right-most zero would cause the <em>smallest</em> change to the number: <code>00000011</code> is <code>3</code>.</p>
<p>Let&rsquo;s consider a large 2 bytes number: <code>65,535</code>, in binary: <code>1111 1111</code>.</p>
<p>Since here we have two bytes, one is the most significant, the other is the least significant:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">MSB  LSB
1111 1111
</code></pre></div><p>And now we reach the crux of this Big Endian vs. Little Endian understanding: Big Endian will first store the Most Significant Byte (MSB). Little Endian will store the Least Significant Byte (LSB) first.</p>
<p>Different machines, languages, implementations will use different endianness; such is life. LC-3 uses Big Endianness. That&rsquo;s why we&rsquo;re using <code>f.read_u16::&lt;BigEndian&gt;()</code>.</p>
<p>Now let&rsquo;s go back to the code above.</p>
<p>Running the code above passing the hello world binary file:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">address: 12288 instruction: 57346
address: 12289 instruction: 61474
address: 12290 instruction: 61477
address: 12291 instruction: 72
address: 12292 instruction: 101
address: 12293 instruction: 108
address: 12294 instruction: 108
address: 12295 instruction: 111
address: 12296 instruction: 32
address: 12297 instruction: 87
address: 12298 instruction: 111
address: 12299 instruction: 114
address: 12300 instruction: 108
address: 12301 instruction: 100
address: 12302 instruction: 33
address: 12303 instruction: 0
</code></pre></div><p>Note that it&rsquo;s showing <code>12288</code> as the base address, <code>12288</code> in hex is <code>0x3000</code>, exactly how it&rsquo;s in the original specs for the LC-3; how cool is that?!</p>
<p>We have to load the instruction <code>57346</code> in memory at the index <code>12288</code>, <code>61474</code> at <code>12289</code>, and so on.</p>
<p>Do you want to see something even cooler? In the hello world assembly, the first instruction is</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">LEA R0, HELLO_STR ; load the address of the HELLO_STR string into R0 PUTs
</code></pre></div><p><code>LEA</code> (we&rsquo;ll see what that is later) is the name of the instruction/opcode, let&rsquo;s see the binary representation of that instruction in the spec:</p>
<p><img src="/images/images/20210714180624.png" alt=""></p>
<p>Note that the OpCode is <code>1110</code>.</p>
<p>Let&rsquo;s see the output of our <code>println!</code> again:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">address: 12288 instruction: 57346
</code></pre></div><p>So, load at <code>12288</code> (<code>0x3000</code> in hex) the instruction <code>57346</code>, this instruction in binary: <code>1110000000000010</code>. Hey! The opcode is right there: <code>1110 000000000010</code>.</p>
<p>The rest of the binary is the necessary information to perform the <code>LEA</code> operation, but you see that the OpCode is there. How cool is that?!</p>
<p>Now we have to load all these instructions coming from a program into the VM memory:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">struct</span> <span style="color:#a6e22e">VM</span> {
    <span style="color:#66d9ef">pub</span> memory: [<span style="color:#66d9ef">u16</span>; MEMORY_SIZE],
    <span style="color:#66d9ef">pub</span> registers: <span style="color:#a6e22e">Registers</span>,
}

<span style="color:#66d9ef">impl</span> VM {
    <span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">new</span>() -&gt; <span style="color:#a6e22e">VM</span> {
        VM {
            memory: [<span style="color:#ae81ff">0</span>; MEMORY_SIZE],
            registers: <span style="color:#a6e22e">Registers</span>::new(),
        }
    }
 
 <span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">write_memory</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, address: <span style="color:#66d9ef">usize</span>, value: <span style="color:#66d9ef">u16</span>) {
        self.memory[address] <span style="color:#f92672">=</span> value;
    }
}
 
</code></pre></div><p>Note that we&rsquo;re using a constant <code>MEMORY_SIZE</code> that we&rsquo;re defining below. This constant is the maximum amount of memory we&rsquo;re giving to our VM. We&rsquo;ll be defining it as <code>65535</code>, which is the max value for 16 bits.</p>
<p>And then our <code>main.rs</code> looks like this</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> base_address <span style="color:#f92672">=</span> f.read_u16::<span style="color:#f92672">&lt;</span>BigEndian<span style="color:#f92672">&gt;</span>().expect(<span style="color:#e6db74">&#34;error&#34;</span>);

<span style="color:#75715e">// Here we&#39;re loading the program in memory
</span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> address <span style="color:#f92672">=</span> base_address <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>;
<span style="color:#66d9ef">loop</span> {
    <span style="color:#66d9ef">match</span> f.read_u16::<span style="color:#f92672">&lt;</span>BigEndian<span style="color:#f92672">&gt;</span>() {
        Ok(instruction) <span style="color:#f92672">=&gt;</span> {
            vm.write_memory(address, instruction);
            address <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span>;
        }
        Err(e) <span style="color:#f92672">=&gt;</span> {
            <span style="color:#66d9ef">if</span> e.kind() <span style="color:#f92672">==</span> std::io::ErrorKind::UnexpectedEof {
                println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;OK&#34;</span>)
            } <span style="color:#66d9ef">else</span> {
                println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;failed: {}&#34;</span>, e);
            }
            <span style="color:#66d9ef">break</span>;
        }
    }
}
</code></pre></div><p>In plain English: we start at the base address 0x3000, load the first instruction at this position, increment the address, load the next instruction, and so on.</p>
<h3 id="executing-the-program">Executing the program</h3>
<p>Once we have a program loaded into the VM&rsquo;s memory, running it is a matter of walking through the memory positions using the value stored in the Program Counter (PC) register.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">use</span> vm::VM;

<span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">const</span> MEMORY_SIZE: <span style="color:#66d9ef">usize</span> <span style="color:#f92672">=</span> std::<span style="color:#66d9ef">u16</span>::MAX <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>;

<span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">execute_program</span>(vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#66d9ef">while</span> vm.registers.pc <span style="color:#f92672">&lt;</span> MEMORY_SIZE <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span> {
        <span style="color:#75715e">// Read instruction
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">let</span> instruction <span style="color:#f92672">=</span> vm.read_memory(vm.registers.pc);

        <span style="color:#75715e">// Increment program counter
</span><span style="color:#75715e"></span>        vm.registers.pc <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span>;

        <span style="color:#75715e">// Extract op_code and execute operation
</span><span style="color:#75715e"></span>        instruction::execute_instruction(instruction, vm)
    }
}
</code></pre></div><p>This leads to two important functions: <code>read_memory</code> and <code>execute_instruction</code>.</p>
<p>Reading the memory is pretty straightforward, at least at this stage:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">read_memory</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, address: <span style="color:#66d9ef">u16</span>) -&gt; <span style="color:#66d9ef">u16</span> {
 self.memory[address <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>]
}
</code></pre></div><p>Executing the instruction is about:</p>
<ol>
<li>Detecting which instruction a given <code>u16</code> value is, i.e., what&rsquo;s the OpCode?</li>
<li>Matching it against all possible OpCodes</li>
<li>Running the matching OpCode and extracting the operands from the whole instruction.</li>
</ol>
<p>The first two parts are pretty simple:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">execute_instruction</span>(instr: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Extract OpCode from the instruction
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> op_code <span style="color:#f92672">=</span> get_op_code(<span style="color:#f92672">&amp;</span>instr);

    <span style="color:#75715e">// Match OpCode and execute instruction
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">match</span> op_code {
        Some(OpCode::ADD) <span style="color:#f92672">=&gt;</span> add(instr, vm),
        Some(OpCode::AND) <span style="color:#f92672">=&gt;</span> and(instr, vm),
        Some(OpCode::NOT) <span style="color:#f92672">=&gt;</span> not(instr, vm),
        Some(OpCode::BR) <span style="color:#f92672">=&gt;</span> br(instr, vm),
        Some(OpCode::JMP) <span style="color:#f92672">=&gt;</span> jmp(instr, vm),
        Some(OpCode::JSR) <span style="color:#f92672">=&gt;</span> jsr(instr, vm),
        Some(OpCode::LD) <span style="color:#f92672">=&gt;</span> ld(instr, vm),
        Some(OpCode::LDI) <span style="color:#f92672">=&gt;</span> ldi(instr, vm),
        Some(OpCode::LDR) <span style="color:#f92672">=&gt;</span> ldr(instr, vm),
        Some(OpCode::LEA) <span style="color:#f92672">=&gt;</span> lea(instr, vm),
        Some(OpCode::ST) <span style="color:#f92672">=&gt;</span> st(instr, vm),
        Some(OpCode::STI) <span style="color:#f92672">=&gt;</span> sti(instr, vm),
        Some(OpCode::STR) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">str</span>(instr, vm),
        Some(OpCode::TRAP) <span style="color:#f92672">=&gt;</span> trap(instr, vm),
        _ <span style="color:#f92672">=&gt;</span> {}
    }
}

</code></pre></div><p>Note that each OpCode is incredibly well specified in the original spec docs. Our goal is to implement one by one!</p>
<h3 id="extracting-and-handling-our-first-instruction">Extracting and handling our first instruction</h3>
<p>Okay, how do we know which instruction is a <code>u16</code> piece of data?</p>
<p>Let&rsquo;s consider the first assembly instruction in our hello world program: <code>LEA</code>, it has, as expected, 16 bits:
<img src="/images/images/20210715170817.png" alt=""></p>
<p>And we want to take an instruction, grab the first 4 bits (the OpCode) and confirm it&rsquo;s an <code>LEA</code> OpCode: <code>1110</code>. Given the first instruction, if we print its decimal and binary representation, we get:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;instruction: {:?}\n&#34;</span>, instruction);
println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;instruction in binary: {:#b}\n&#34;</span>, instruction);
</code></pre></div><p>Output:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">instruction: 57346
instruction in binary: 0b1110000000000010
</code></pre></div><p>Okay, so the OpCode is right there: <code>1110</code>, how do we extract it from the whole instruction?</p>
<p>A common technique is to use bit shifting (<code>&gt;&gt;</code> or <code>&lt;&lt;</code>) to turn <code>1110000000000010</code> into <code>0000000000001110</code>, which is the OpCode representation with the full leading zeroes!</p>
<p>That means we can right-shift the original number 12 times by using <code>&gt;&gt;</code>. Go on, count, and you will see that moving each element in that binary representation from its original position (<code>1110000000000010</code>) to the right, 12 times, will lead to <code>0000000000001110</code>.</p>
<p>So if we do this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;instruction: {:?}\n&#34;</span>, instruction);

println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;instruction in binary: {:#b}\n&#34;</span>, instruction);

println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;instruction &gt;&gt; 12: {:?}\n&#34;</span>, instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">12</span>);

println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;instruction &gt;&gt; 12: {:#b}\n&#34;</span>, instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">12</span>);
</code></pre></div><p>We get:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">instruction: 57346

instruction in binary: 0b1110000000000010

instruction &gt;&gt; 12: 14

instruction &gt;&gt; 12: 0b1110
</code></pre></div><p>Now, here are all the OpCodes from the specs:
<img src="/images/images/20210715171902.png" alt=""></p>
<p>We now have to match the extracted 4 first bits of an instruction against the list of all OpCodes:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">enum</span> <span style="color:#a6e22e">OpCode</span> {
    BR <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>, <span style="color:#75715e">// branch
</span><span style="color:#75715e"></span>    ADD,    <span style="color:#75715e">// add
</span><span style="color:#75715e"></span>    LD,     <span style="color:#75715e">// load
</span><span style="color:#75715e"></span>    JSR,    <span style="color:#75715e">// jump register
</span><span style="color:#75715e"></span>    AND,    <span style="color:#75715e">// bitwise and
</span><span style="color:#75715e"></span>    LDR,    <span style="color:#75715e">// load register
</span><span style="color:#75715e"></span>    STR,    <span style="color:#75715e">// store register
</span><span style="color:#75715e"></span>    RTI,    <span style="color:#75715e">// unused
</span><span style="color:#75715e"></span>    NOT,    <span style="color:#75715e">// bitwise not
</span><span style="color:#75715e"></span>    LDI,    <span style="color:#75715e">// load indirect
</span><span style="color:#75715e"></span>    STI,    <span style="color:#75715e">// store indirect
</span><span style="color:#75715e"></span>    JMP,    <span style="color:#75715e">// jump
</span><span style="color:#75715e"></span>    RES,    <span style="color:#75715e">// reserved (unused)
</span><span style="color:#75715e"></span>    LEA,    <span style="color:#75715e">// load effective address
</span><span style="color:#75715e"></span>    TRAP,   <span style="color:#75715e">// execute trap
</span><span style="color:#75715e"></span>}

<span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">get_op_code</span>(instruction: <span style="color:#66d9ef">&amp;</span><span style="color:#66d9ef">u16</span>) -&gt; Option<span style="color:#f92672">&lt;</span>OpCode<span style="color:#f92672">&gt;</span> {
    <span style="color:#66d9ef">match</span> instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">12</span> {
        <span style="color:#ae81ff">0</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::BR),
        <span style="color:#ae81ff">1</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::ADD),
        <span style="color:#ae81ff">2</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::LD),
        <span style="color:#ae81ff">3</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::ST),
        <span style="color:#ae81ff">4</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::JSR),
        <span style="color:#ae81ff">5</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::AND),
        <span style="color:#ae81ff">6</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::LDR),
        <span style="color:#ae81ff">7</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::STR),
        <span style="color:#ae81ff">8</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::RTI),
        <span style="color:#ae81ff">9</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::NOT),
        <span style="color:#ae81ff">10</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::LDI),
        <span style="color:#ae81ff">11</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::STI),
        <span style="color:#ae81ff">12</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::JMP),
        <span style="color:#ae81ff">13</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::RES),
        <span style="color:#ae81ff">14</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::LEA),
        <span style="color:#ae81ff">15</span> <span style="color:#f92672">=&gt;</span> Some(OpCode::TRAP),
        _ <span style="color:#f92672">=&gt;</span> None,
    }
}
</code></pre></div><p>Notice that we&rsquo;re matching it against the decimal representation of the instruction that&rsquo;s coming as <code>u16</code>.</p>
<p>Now our <code>execute_instruction</code> makes a lot more sense:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">execute_instruction</span>(instr: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Extract OpCode from the instruction
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> op_code <span style="color:#f92672">=</span> get_op_code(<span style="color:#f92672">&amp;</span>instr);

    <span style="color:#75715e">// Match OpCode and execute instruction
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">match</span> op_code {
        Some(OpCode::ADD) <span style="color:#f92672">=&gt;</span> add(instr, vm),
        Some(OpCode::AND) <span style="color:#f92672">=&gt;</span> and(instr, vm),
        Some(OpCode::NOT) <span style="color:#f92672">=&gt;</span> not(instr, vm),
        Some(OpCode::BR) <span style="color:#f92672">=&gt;</span> br(instr, vm),
        Some(OpCode::JMP) <span style="color:#f92672">=&gt;</span> jmp(instr, vm),
        Some(OpCode::JSR) <span style="color:#f92672">=&gt;</span> jsr(instr, vm),
        Some(OpCode::LD) <span style="color:#f92672">=&gt;</span> ld(instr, vm),
        Some(OpCode::LDI) <span style="color:#f92672">=&gt;</span> ldi(instr, vm),
        Some(OpCode::LDR) <span style="color:#f92672">=&gt;</span> ldr(instr, vm),
        Some(OpCode::LEA) <span style="color:#f92672">=&gt;</span> lea(instr, vm),
        Some(OpCode::ST) <span style="color:#f92672">=&gt;</span> st(instr, vm),
        Some(OpCode::STI) <span style="color:#f92672">=&gt;</span> sti(instr, vm),
        Some(OpCode::STR) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">str</span>(instr, vm),
        Some(OpCode::TRAP) <span style="color:#f92672">=&gt;</span> trap(instr, vm),
        _ <span style="color:#f92672">=&gt;</span> {}
    }
}
</code></pre></div><p>And if we print the <code>op_code</code> for each instruction coming from the hello world program, we get:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">op_code: Some(LEA)

op_code: Some(TRAP)

op_code: Some(TRAP)
</code></pre></div><p>Now let&rsquo;s continue the implementation and implement only the necessary to run the hello world program: <code>Some(OpCode::LEA) =&gt; lea(instr, vm),</code></p>
<p><code>LEA</code> stands for Load Effective Address. As we&rsquo;ve seen before, the first 4 bits are the OpCode identification (<code>1110</code>)
<img src="/images/images/20210716160026.png" alt=""></p>
<p>The other two are the Direct Register (DR) and the Program Counter (PC) offset.</p>
<p>The first instruction is doing the following:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">LEA R0, HELLO_STR
</code></pre></div><p>So, effectively, we&rsquo;re loading an address into a register. In this case, we&rsquo;re loading the string <code>HELLO_STR</code> into the register <code>R0</code> by loading the address where the <code>HELLO_STR</code> lives.</p>
<p>From the original specs:</p>
<blockquote>
<p>An address is computed by sign-extending bits [8:0] to 16 bits and adding this value to the incremented PC. This address is loaded into DR. The condition codes are set, based on whether the value loaded is negative, zero, or positive.</p>
</blockquote>
<p>And then the footnote:</p>
<blockquote>
<p>The LEA instruction does not read memory to obtain the information to load into DR. The address itself is loaded into DR.</p>
</blockquote>
<h3 id="extracting-information-from-a-binary-encoded-value">Extracting information from a binary encoded value</h3>
<p>So, for the <code>LEA</code> instruction, here&rsquo;s what the code needs to do.</p>
<p>First, get the DR portion of the instruction:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
</code></pre></div><p>This is a trick to get the destination register portion of the instruction.</p>
<p>Let&rsquo;s break this down. The instruction that we&rsquo;ve received at <code>LEA R0, HELLO_STR</code> is <code>0b1110_000_000000010</code>.</p>
<p>From left to right: <code>1110</code> is the OpCode, <code>000</code> is the Direct Register (DR), and <code>000000010</code> is the <code>PCOffset9</code>.</p>
<p>Then when we shift it to the right 9 times, we get:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">original instruction: 0b1110_000_000000010
instruction &gt;&gt; 9:     0b0000000001110_000
</code></pre></div><p>So we&rsquo;ve shifted enough that the last three bits are the direct register in the instruction: <code>000</code>. The bits shifted &ldquo;out&rdquo; of the value sorta &ldquo;disappear&rdquo; from the value; in other words, they don&rsquo;t <em>rotate</em> back to the beginning of the value.</p>
<p>Now that we have our &ldquo;target&rdquo; bits aligned at the end of the value, we apply a mask <code>&amp; 0x7</code> (<code>0b0000000000000111</code>). This mask is a bitwise <code>AND</code> against the instruction that we shifted.</p>
<p>And the result is:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">instruction &gt;&gt; 9 &amp; 0x7: 0b0000000000000000
</code></pre></div><p>So it&rsquo;s the register 0, as expected.</p>
<p>But why do we mask? There are usually three reasons to apply bitwise masking:</p>
<ul>
<li>Bitwise AND to <strong>extract</strong> a subset of the bits in the value</li>
<li>Bitwise OR to <strong>set</strong> a subset of the bits in the value</li>
<li>Bitwise XOR to <strong>toggle</strong> a subset of the bits in the value</li>
</ul>
<p>In the AND case, for instance:</p>
<pre><code class="language-clear" data-lang="clear">Mask:   0000   1111
Value:  0101   0101
-------------------
Result: 0000   0101
</code></pre><p>The goal of this mask is, from left to right, to clear the first 4 bits and keep the last 4 bits of the value. So the result will be <code>0b00000101</code>.</p>
<p>So in our <code>LEA R0, HELLO_STR</code> case, <code>(instruction &gt;&gt; 9) &amp; 0x7</code> is trying to say: shift it so that the last three bits are the direct register we&rsquo;re looking for, but since the result of that <code>instruction &gt;&gt; 9</code> isn&rsquo;t the final direct register (only the last 3 bits), mask it with <code>0b0000000000000111</code> so that we clear <em>everything</em> up to the last three bits, which is what we want. The resulting 16 bits value will be <em>exactly</em> the direct register! How cool is that?! I find the intricate simplicity behind this technique beautiful.</p>
<h3 id="sign-extension">Sign extension</h3>
<p>Now back to the <code>LEA</code> spec:</p>
<blockquote>
<p>An address is computed by sign-extending bits [8:0] to 16 bits and adding this value to the incremented PC.</p>
</blockquote>
<p>Let&rsquo;s see how this sign-extending thing works. Simply put, because we&rsquo;re operating on 16 bits, whenever a value has less than 16 bits, we have to extend it to be 16 bits.</p>
<p>The address we&rsquo;re loading with <code>LEA</code>, bits 8 to 0 (left to right), clearly isn&rsquo;t 16 bits &ndash; so we have to sign-extend it!</p>
<p>For positive numbers, it&rsquo;s easy: add zeroes before the value. This doesn&rsquo;t work for negative numbers, though. Borrowing an example from Justin:</p>
<blockquote>
<p>For example, -1 in 5 bits is <code>1 1111</code>. If we just extended it with 0&rsquo;s, this is <code>0000 0000 0001 1111</code>, which is equal to 31</p>
</blockquote>
<p>So instead of just filling in zeroes, we must also fill in ones for negative numbers. So this is how it looks:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">
<span style="color:#75715e">// ...
</span><span style="color:#75715e"></span>
<span style="color:#66d9ef">let</span> pc_offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);

<span style="color:#75715e">// ...
</span><span style="color:#75715e"></span>
<span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">sign_extend</span>(<span style="color:#66d9ef">mut</span> x: <span style="color:#66d9ef">u16</span>, bit_count: <span style="color:#66d9ef">u8</span>) -&gt; <span style="color:#66d9ef">u16</span> {
    <span style="color:#66d9ef">if</span> (x <span style="color:#f92672">&gt;&gt;</span> (bit_count <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
        x <span style="color:#f92672">|=</span> <span style="color:#ae81ff">0xFFFF</span> <span style="color:#f92672">&lt;&lt;</span> bit_count;
    }
    x
}
</code></pre></div><p>More bitwise tricks! Let&rsquo;s break this down.</p>
<p>We start off with</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);
</code></pre></div><p><code>0x1ff</code> is <code>111111111</code>, nine consecutive ones. Another mask! By <code>instruction &amp; 0x1ff</code>, we mean to keep only the last 9 bits of the instruction, which happens to be the <code>PCOffset9</code>, the address we&rsquo;re loading into a register, and the value that we have to sign-extend.</p>
<p>So here we&rsquo;re just extracting the <code>PCOffset9</code> portion from the instruction. We didn&rsquo;t need to shift things around because <code>PCOffset9</code> is already right-aligned.</p>
<p>Now, because it&rsquo;s a 9-bit value, we want to extend it to be 16. Enters <code>sign_extend</code> function. Let&rsquo;s break it down. You can check the formal definition for sign extension here: <a href="https://en.wikipedia.org/wiki/Sign_extension">https://en.wikipedia.org/wiki/Sign_extension</a>.</p>
<p>The short version is, if it&rsquo;s a signed positive number, padding with zeroes will work. Adding zeroes won&rsquo;t preserve the value if it&rsquo;s a signed negative number, but padding with ones will.</p>
<p>The <code>sign_extend</code> is doing that. It takes a <code>bit_count</code> which is the number of bits in the original value; in the case of the <code>LEA</code> command, we&rsquo;re dealing with a 9-bit value that we want to convert into 16-bit. That&rsquo;s why we call it like this: <code>let pc_offset = sign_extend(instruction &amp; 0x1ff, 9);</code></p>
<p>The if clause <code>if (x &gt;&gt; (bit_count - 1)) &amp; 1 != 0</code> is testing the sign of the value. We&rsquo;re moving <code>x</code> to the right up until the sign bit (<code>bit_count - 1</code>) and applying a single bitmask <code>&amp; 1</code> to grab it. Then check if it&rsquo;s different than zero; if it is, it&rsquo;s signed as <code>1</code> (negative), meaning we have to pad with ones instead of zeroes. Otherwise, it&rsquo;s zero, and we return as is, as it already is padded with zeroes.</p>
<p>And the part where we pad with ones is:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">x <span style="color:#f92672">|=</span> <span style="color:#ae81ff">0xFFFF</span> <span style="color:#f92672">&lt;&lt;</span> bit_count;
</code></pre></div><p>This part is tricky if you&rsquo;re new to bitwise operations. <code>0xFFFF &lt;&lt; bit_count</code> is happening, then its result is <code>|=&quot;</code>d against <code>x</code>. <code>|=</code> means bitwise <code>OR</code>, but with an assignment step, so <code>x</code> will be <code>OR</code>&rsquo;d against the result of <code>0xFFFF &lt;&lt; bit_count</code> and the result of that <code>OR</code> will be assigned to <code>x</code>, replacing the original value.</p>
<p><code>0xFFFF</code> is <code>1111111111111111</code> (16 bits). We shift it left <code>bit_count</code> times, i.e., the number of bits in the original value <code>x</code> (in this case,<code>9</code>). Meaning that, for the original value, we&rsquo;re going to &ldquo;leave it alone&rdquo; and only set <code>1</code>&rsquo;s to the rest, all the way to 16 bits total. This way, we&rsquo;re going to have <code>1111111_&lt;original x value&gt;</code>, and we&rsquo;re done! Super clever trick.</p>
<p>Effectively, the <code>LEA</code> command in our hello world example is loading the address of the beginning of the string onto the register 0.</p>
<p>The last part is updating the cond register based on the value stored in the register that we last operated on, in this case, R0. Which looks like</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">vm.registers.update_r_cond_register(dr);

<span style="color:#75715e">// ...
</span><span style="color:#75715e"></span>
<span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">update_r_cond_register</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, r: <span style="color:#66d9ef">u16</span>) {
    <span style="color:#66d9ef">if</span> self.get(r) <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> {
        self.update(<span style="color:#ae81ff">9</span>, ConditionFlag::ZRO <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    } <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> (self.get(r) <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">15</span>) <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
        <span style="color:#75715e">// a 1 in the left-most bit indicates negative
</span><span style="color:#75715e"></span>        self.update(<span style="color:#ae81ff">9</span>, ConditionFlag::NEG <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    } <span style="color:#66d9ef">else</span> {
        self.update(<span style="color:#ae81ff">9</span>, ConditionFlag::POS <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    }
}

<span style="color:#66d9ef">enum</span> <span style="color:#a6e22e">ConditionFlag</span> {
    POS <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">0</span>, <span style="color:#75715e">// Positive
</span><span style="color:#75715e"></span>    ZRO <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">1</span>, <span style="color:#75715e">// Zero
</span><span style="color:#75715e"></span>    NEG <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">2</span>, <span style="color:#75715e">// Negative
</span><span style="color:#75715e"></span>}
</code></pre></div><p>Then, in our hello world example, we run a <code>TRAP</code> OpCode. Trap is an OpCode for interacting with IO devices, such as halting, output/input of data, etc. In other words, it&rsquo;s where we go to do a very known thing called <a href="https://en.wikipedia.org/wiki/System_call">system calls</a>!</p>
<p>The trap spec is unique in comparison to the other OpCodes:
<img src="/images/images/20210721102044.png" alt=""></p>
<p><code>1111</code> is the OpCode identifier, but then we have this thing called a trap vector, which is 8 bits long. The trap vector holds the identifier to which system call it wants to execute. The spec is super clear about how it works:</p>
<blockquote>
<p><code>trap</code> allows interacting with I/O devices. First R7 is loaded with the incremented PC. (This enables a return to the instruction physically following the TRAP instruction in the original program after the service routine has completed execution.) Then the PC is loaded with the starting address of the system call specified by trap vector8. The starting address is contained in the memory location whose address is obtained by zero-extending trap vector8 to 16 bits.</p>
</blockquote>
<p>And then below:</p>
<blockquote>
<p>Memory locations x0000 through x00FF, 256 in all, are available to contain starting addresses for system calls specified by their corresponding trap vectors. This region of memory is called the Trap Vector Table.</p>
</blockquote>
<p>And below that we have the list of all &ldquo;trap service routines&rdquo;:
<img src="/images/images/20210721102603.png" alt=""></p>
<p>So our trap implementation will look like something like this</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">trap</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;trap instruction: {:#018b}\n&#34;</span>, instruction);

    <span style="color:#66d9ef">match</span> instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0xFF</span> {
        <span style="color:#ae81ff">0x20</span> <span style="color:#f92672">=&gt;</span> {
            <span style="color:#75715e">// Get character
</span><span style="color:#75715e"></span>        }
        <span style="color:#ae81ff">0x21</span> <span style="color:#f92672">=&gt;</span> {
            <span style="color:#75715e">// Write out character
</span><span style="color:#75715e"></span>        }
        <span style="color:#ae81ff">0x22</span> <span style="color:#f92672">=&gt;</span> {
            <span style="color:#75715e">// Puts
</span><span style="color:#75715e"></span>        }
        <span style="color:#ae81ff">0x23</span> <span style="color:#f92672">=&gt;</span> {
            <span style="color:#75715e">// In, Print a prompt on the screen and read a single character from the keyboard. The character is echoed onto the console monitor, and its ASCII code is copied into R0.The high eight bits of R0 are cleared.
</span><span style="color:#75715e"></span>        }
        <span style="color:#ae81ff">0x24</span> <span style="color:#f92672">=&gt;</span> {
            <span style="color:#75715e">// Putsp
</span><span style="color:#75715e"></span>        }
        <span style="color:#ae81ff">0x25</span> <span style="color:#f92672">=&gt;</span> {
   <span style="color:#75715e">// Halt
</span><span style="color:#75715e"></span>        }
        _ <span style="color:#f92672">=&gt;</span> {
            process::exit(<span style="color:#ae81ff">1</span>);
        }
    }
}
</code></pre></div><p>And just like the &ldquo;higher level&rdquo; OpCodes (<code>LEA</code>, <code>ADD</code>, etc.), we have to implement one by one.</p>
<p>In our hello world example, the first trap used is <code>PUTS</code>, to print a string. The instruction binary representation is: <code>1111000000100010</code>. So, <code>00100010</code> (the last 8 bits) is the trap vector identifier. <code>00100010</code> is <code>0x22</code> in hex, which maps to <code>PUTS</code>!</p>
<p>Notice that we do a <code>match instruction &amp; 0xFF {</code> to find <code>0x22</code>.  Just like before, we do the <code>&amp; 0xFF</code> (called a mask) to capture only the <code>0xFF</code> worth of bits from the <code>instruction</code>, <code>0xFF</code> is <code>11111111</code>, 8 bits, which is the length of the trap vector we want to capture.</p>
<p>Here&rsquo;s how the <code>PUTS</code> implementation looks like</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">x22 <span style="color:#f92672">=&gt;</span> {
 <span style="color:#75715e">// Puts
</span><span style="color:#75715e"></span> <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> index <span style="color:#f92672">=</span> vm.registers.r0;
 
 <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> c <span style="color:#f92672">=</span> vm.read_memory(index);
 
 <span style="color:#66d9ef">while</span> c <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0x0000</span> {
     print<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;{}&#34;</span>, (c <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u8</span>) <span style="color:#66d9ef">as</span> char);
     index <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span>;
     c <span style="color:#f92672">=</span> vm.read_memory(index);
 }
 
 io::stdout().flush().expect(<span style="color:#e6db74">&#34;failed to flush&#34;</span>);
}
</code></pre></div><p>We&rsquo;re printing char by char, and the address of the beginning of the string lives in the register 0. So we&rsquo;re walking through it.</p>
<p>Let&rsquo;s visualize this better. If we print instruction:address pairs at the beginning, when we&rsquo;re loading the hello world program into the VM&rsquo;s memory, we see this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">address: 12288 instruction: 57346
address: 12289 instruction: 61474
address: 12290 instruction: 61477
address: 12291 instruction: 72
address: 12292 instruction: 101
address: 12293 instruction: 108
address: 12294 instruction: 108
address: 12295 instruction: 111
address: 12296 instruction: 32
address: 12297 instruction: 87
address: 12298 instruction: 111
address: 12299 instruction: 114
address: 12300 instruction: 108
address: 12301 instruction: 100
address: 12302 instruction: 33
address: 12303 instruction: 0
</code></pre></div><p>Notice how at the beginning of the address <code>12291</code> the instructions become slightly different. This is where the characters of the <code>&quot;hello world&quot;</code> string start being loaded at. Fun detail: these &ldquo;instructions&rdquo; start to look like utf8 encoding!</p>
<p>Let&rsquo;s further confirm that <code>12291</code> is the beginning of the string:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> index <span style="color:#f92672">=</span> vm.registers.r0;
println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;index: {:?}\n&#34;</span>, index);
</code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">index: 12291
</code></pre></div><p>Alright! Once we understand that, the reading loop becomes trivial:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">while</span> c <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0x0000</span> {
    print<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;{}&#34;</span>, (c <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u8</span>) <span style="color:#66d9ef">as</span> char);
    index <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span>;
    c <span style="color:#f92672">=</span> vm.read_memory(index);
}
</code></pre></div><p>We&rsquo;re just walking through each address until we see a <code>0x0000</code>. And the <code>print!</code> over there is printing it to the stdout, that&rsquo;s how we see <code>Hello, world!</code> coming from the register 0!</p>
<p>Then, the next trap instruction we see is <code>HALT</code>, <code>1111000000100101</code>.  Which is the simplest one to implement:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#ae81ff">0x25</span> <span style="color:#f92672">=&gt;</span> {
    println<span style="color:#f92672">!</span>(<span style="color:#e6db74">&#34;HALT detected&#34;</span>);
    io::stdout().flush().expect(<span style="color:#e6db74">&#34;Failed to flush&#34;</span>);
    process::exit(<span style="color:#ae81ff">1</span>);
}
</code></pre></div><p>And that&rsquo;s it for the hello world example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">  Finished dev [unoptimized + debuginfo] target(s) in 0.19s
     Running `target/debug/LC-3 examples/hello-world.obj`
OK
Hello World!HALT detected
</code></pre></div><p>We just managed to run a binary file for the LC-3 computer in our VM!</p>
<p>Now, our next goal is to implement the rest of the OpCodes, add some more keyboard input control, and then we&rsquo;ll be good to run more complex programs. It might sound complicated, but it isn&rsquo;t. Now that we understand the logic and flow behind this VM, its bitwise operation tricks, how we use registers, etc., it&rsquo;s now a matter of reading the spec for each OpCode and implementing its logic, which is usually very straightforward.</p>
<h2 id="implementing-the-add-opcode">Implementing the ADD OpCode</h2>
<p>Here&rsquo;s the ADD spec:</p>
<p><img src="/images/images/20210721120132.png" alt=""></p>
<p>We have two operation modes for ADD, and we can pick which one we&rsquo;re gonna use by setting the bit [5] of the instruction. Here&rsquo;s how it&rsquo;s officially described:</p>
<blockquote>
<p>If bit [5] is 0, the second source operand is obtained from SR2. If bit [5] is 1, the second source operand is obtained by sign-extending the imm5 field to 16 bits. In both cases, the second source operand is added to the contents of SR1 and the result stored in DR. The condition codes are set, based on whether the result is negative, zero, or positive</p>
</blockquote>
<p>In other words, <code>ADD</code> will be adding two numbers; the first comes from a register, the second will come either from a register (SR2) or by directly passing an immediate value to the instruction, like:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plaintext" data-lang="plaintext">ADD R2, R3, R4 ; R2←R3+R4, R2 receives the sum of what&#39;s in R3 and R4
ADD R2, R3, #7 ; R2←R3+7, R2 receives the sum of what&#39;s in R3 and the num 7
</code></pre></div><p>In the immediate case, it needs to be in 16 bits because it&rsquo;s a full value, so we sign-extend it. The trade-off is that the instruction only has room for a small number, up to <code>2^5=32</code>.</p>
<p>Here&rsquo;s how the code looks like</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">add</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// First operand
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> sr1 <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Check if we&#39;re in immediate mode or register mode.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> imm_flag <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">5</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1</span>;
    <span style="color:#66d9ef">if</span> imm_flag <span style="color:#f92672">==</span> <span style="color:#ae81ff">1</span> {
        <span style="color:#66d9ef">let</span> imm5 <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1F</span>, <span style="color:#ae81ff">5</span>);
        <span style="color:#75715e">//val is declared as u32 to prevent from overflow.
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> imm5 <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> vm.registers.get(sr1) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
        <span style="color:#75715e">//val is declared as u16, so that type arithmatic kick in and number is rounded to get fit into u16.
</span><span style="color:#75715e"></span>        vm.registers.update(dr, val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    } <span style="color:#66d9ef">else</span> {
        <span style="color:#75715e">/* first operand (SR2) */</span>
        <span style="color:#66d9ef">let</span> sr2 <span style="color:#f92672">=</span> instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
        <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.get(sr1) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> vm.registers.get(sr2) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
        vm.registers.update(dr, val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    }

    vm.registers.update_r_cond_register(dr);
}
</code></pre></div><p>Let&rsquo;s break it down.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
</code></pre></div><p>This gets the destination address using bitwise operation tricks.</p>
<p><code>instruction &gt;&gt; 9</code> will shift the binary from the instruction it 9 times to the right.
That means the last bit will be the end of the DR portion of the instruction.
And the bitwise-and (<code>&amp;</code>) <code>0x7</code> will grab only the length of <code>111</code> out of the instruction, i.e., the last 3 bits, which is precisely the length of the DR.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> sr1 <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
</code></pre></div><p>Same thing as before, but now we&rsquo;re moving only 6 times because the SR1 register is after the direct register (DR).</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">let</span> imm_flag <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">5</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1</span>;
</code></pre></div><p>Again, same thing, just the one bit at position 5 that represents the operation mode.</p>
<p>Then we proceed with the operation mode logic:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">if</span> imm_flag <span style="color:#f92672">==</span> <span style="color:#ae81ff">1</span> {
    <span style="color:#66d9ef">let</span> imm5 <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1F</span>, <span style="color:#ae81ff">5</span>);

    <span style="color:#75715e">// This is declared as u32 to prevent from overflow.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> imm5 <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> vm.registers.get(sr1) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;

    <span style="color:#75715e">// Set the result of the sum to the target register
</span><span style="color:#75715e"></span>    vm.registers.update(dr, val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
} <span style="color:#66d9ef">else</span> {
    <span style="color:#75715e">// If not immediate mode, we need to extract the second register.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> sr2 <span style="color:#f92672">=</span> instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Proceed as usual
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.get(sr1) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> vm.registers.get(sr2) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;

    <span style="color:#75715e">// Set the result of the sum to the target register
</span><span style="color:#75715e"></span>    vm.registers.update(dr, val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
}
</code></pre></div><p>If it&rsquo;s the immediate mode, grab the immediate value by extending it to be 16 bits. Then add and update the target register (<code>R0</code>).</p>
<p>If not immediate mode, grab the other register passed in the instruction and proceed as usual.</p>
<p>And that&rsquo;s it! Then we have to update the condition register:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust">vm.registers.update_r_cond_register(dr);
</code></pre></div><p>We pass <code>dr</code> here because this is the register containing the result of the last operation. Remember that the cond register&rsquo;s idea is to set positive/negative/zero based on the result of the last operation, which in this case live in <code>dr</code>.</p>
<h2 id="implementing-the-ldi-opcode">Implementing the LDI OpCode</h2>
<p><img src="/images/images/20210721181133.png" alt=""></p>
<p>In simple terms, the <code>LDI</code> operation is loading the address of a piece of data onto a register. However, it&rsquo;s a bit trickier than that because it adds another layer of indirection (that&rsquo;s why it&rsquo;s called load indirect).</p>
<p>It starts by adding the <code>PC</code> to a <code>PCOffset9</code> in the instruction. This sum is an address to a memory location, and that address contains another value which is the address of the value to load. It sounds tricky, but the code probably makes it clear. It looks like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">ldi</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Get the PC offset and sign extend it to be 16 bits
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> pc_offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);

    <span style="color:#66d9ef">let</span> first_read <span style="color:#f92672">=</span> vm.read_memory(vm.registers.pc <span style="color:#f92672">+</span> pc_offset);
   
    <span style="color:#66d9ef">let</span> resulting_address <span style="color:#f92672">=</span> vm.read_memory(first_read);
    
    vm.registers.update(dr, resulting_address);
    vm.registers.update_r_cond_register(dr);
}
</code></pre></div><h2 id="implementing-the-and-opcode">Implementing the AND OpCode</h2>
<p><img src="/images/images/20210721181058.png" alt=""></p>
<p>Good old logical <code>and</code>, but applied to binary values. This one is similar to <code>ADD</code>; it has two operation modes: immediate and register. Since you probably already got the hang of it, here&rsquo;s the code without much explanation:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">and</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// As seen in `add` fn, same tricks.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> sr1 <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
    <span style="color:#66d9ef">let</span> imm_flag <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">5</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1</span>;

    <span style="color:#66d9ef">if</span> imm_flag <span style="color:#f92672">==</span> <span style="color:#ae81ff">1</span> {
        <span style="color:#66d9ef">let</span> imm5 <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1F</span>, <span style="color:#ae81ff">5</span>);
        <span style="color:#75715e">// Perform the bitwise and (`&amp;`) and store its value in the DR.
</span><span style="color:#75715e"></span>        vm.registers.update(dr, vm.registers.get(sr1) <span style="color:#f92672">&amp;</span> imm5);
    } <span style="color:#66d9ef">else</span> {
        <span style="color:#66d9ef">let</span> sr2 <span style="color:#f92672">=</span> instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
        <span style="color:#75715e">// Perform the bitwise and (`&amp;`) and store its value in the DR.
</span><span style="color:#75715e"></span>        vm.registers
            .update(dr, vm.registers.get(sr1) <span style="color:#f92672">&amp;</span> vm.registers.get(sr2));
    }

    vm.registers.update_r_cond_register(dr);
}
</code></pre></div><p>Nothing new here, same old tricks, but instead of <code>+</code>ing stuff, we&rsquo;re just bitwise-and&rsquo;ing it.</p>
<h2 id="implementing-the-not-opcode">Implementing the NOT OpCode</h2>
<p><img src="/images/images/20210721181921.png" alt="">
Another dead simple OpCode, simple binary negation. Won&rsquo;t bore you with the details:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">not</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
    <span style="color:#66d9ef">let</span> sr1 <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
    vm.registers.update(dr, <span style="color:#f92672">!</span>vm.registers.get(sr1));

    vm.registers.update_r_cond_register(dr);
}
</code></pre></div><h2 id="implementing-the-br-opcode">Implementing the BR OpCode</h2>
<p>Finally, we&rsquo;re using the condition register! We use a branch (<code>BR</code>) operation to control the flow of a program. There are many ways to use it:
<img src="/images/images/20210722103139.png" alt=""></p>
<p>Let&rsquo;s look at the instruction encoding:
<img src="/images/images/20210721182455.png" alt=""></p>
<p>This one has some tricks that are worth digging into.</p>
<p>We have three bits set here: <code>n</code> for negative, <code>z</code> for zero, and <code>p</code> for positive. If any of these conditions are true, we&rsquo;ll move the flow of the program to wherever <code>LABEL</code> is, which is a position stored in the <code>PC</code> register.</p>
<p>In a more concrete example, if the <code>BR</code> instruction has <code>101</code> for <code>nzp</code>, we&rsquo;re saying that if the last instruction resulted in a negative number of a positive number, <em>but not zero</em>, then we trigger the branching, by moving the <code>PC</code> to <code>LABEL</code>.</p>
<p>This brings us to how we implement the condition flags in our VM:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">enum</span> <span style="color:#a6e22e">ConditionFlag</span> {
    POS <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">0</span>, <span style="color:#75715e">// Positive
</span><span style="color:#75715e"></span>    ZRO <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">1</span>, <span style="color:#75715e">// Zero
</span><span style="color:#75715e"></span>    NEG <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">2</span>, <span style="color:#75715e">// Negative
</span><span style="color:#75715e"></span>}
</code></pre></div><p>Simple enough, but why these values set for <code>POS</code>, <code>ZRO</code>, and <code>NEG</code>?</p>
<p><code>1</code> in binary representation is <code>0000000000000001</code>, <code>1 &lt;&lt; 2</code> means we&rsquo;re shifting the bits twice to the left, so that <code>1</code> at the end will effectively move to left twice. It ends up being <code>0000000000000100</code>, which in decimal representation is <code>4</code>. Thus, <code>1 &lt;&lt; 2 == 4</code>.</p>
<p>So why are we storing 1, 2, 4 here? Glad you asked. In binary, with 3 bits only:
<code>1 == 001</code>
<code>2 == 010</code>
<code>4 == 100</code></p>
<p>So we&rsquo;re playing with the possible conditional flags settings! Because the condition instruction will be <code>nzp</code> (neg, zero, pos) and only one can be set at a time, it will either be:</p>
<ul>
<li><code>001</code> (positive set <code>nz1</code>)</li>
<li><code>010</code> (zero set, <code>n1p</code>)</li>
<li><code>100</code> (negative set, <code>1zp</code>)</li>
</ul>
<p>And these three binary values are <code>1</code>, <code>2</code>, and <code>4</code> in decimal!</p>
<p>Now, our branching operation looks like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">br</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Grab the PCOffset of the instruction and sign extend it
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// You can read more sign extension inside the `sign_extend` fn.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> pc_offset <span style="color:#f92672">=</span> sign_extend((instruction) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);

    <span style="color:#75715e">// Shift 9 and grab 3 bits (&amp; 0x7 is doing that)
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// You can read more about this trick inside `lea` fn.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> cond_flag <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#66d9ef">if</span> cond_flag <span style="color:#f92672">&amp;</span> vm.registers.cond <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
        <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.pc <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> pc_offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
        vm.registers.pc <span style="color:#f92672">=</span> val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>;
    }

    <span style="color:#75715e">// If the branch isn&#39;t taken (no condition met), PC isn&#39;t changed
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// and PC will just point to the next sequential instruction.
</span><span style="color:#75715e"></span>}
</code></pre></div><p>And we do the testing there as: <code>f cond_flag &amp; vm.registers.cond != 0 {</code></p>
<p>We&rsquo;re taking the <code>001</code>, or <code>010</code>, or <code>100</code> stored in the condition register and <code>&amp;</code>ing it to the <code>001</code>, or <code>010</code>, or <code>100</code> coming from the instruction; note that the one coming from the instruction can be <code>110</code>, <code>111</code> or any combination.</p>
<p>For example, if the last operation turned positive, we have <code>001</code> in the condition register. If the condition to trigger the branching is <code>011</code> (either positive or zero), then <code>001 &amp; 011</code> will be <code>001</code>, which means the branching is enabled, meaning we will change the <code>PC</code> by adding the <code>PCOffset</code> to it and moving on. The next instruction executed will be decided by this new <code>PCOffset</code>; this is usually used for while/for loops and if-statements.</p>
<h2 id="implementing-the-jmp-opcode">Implementing the JMP OpCode</h2>
<p><code>JMP</code> is another flow control operation, like <code>BR</code>, but without conditions. So we&rsquo;re mutating the <code>PC</code> register no matter what.</p>
<p>The program unconditionally jumps to the location specified by the content of the base register in the instruction. Bits [8:6] identify the base register.</p>
<p><code>RET</code> is listed as a separate instruction in the specification since it is a different keyword in assembly. However, it is a particular case of <code>JMP</code>. <code>RET</code> happens whenever <code>R1</code> is <code>7</code>.</p>
<p>This is how the encoding looks like:
<img src="/images/images/20210722111111.png" alt=""></p>
<p>In our implementation, <code>RET</code> and <code>JMP</code> are going to be handled by the same <code>JMP</code> function, as they&rsquo;re basically the same, just different assembly keywords, and <code>RET</code> is always when the register is <code>111</code> (register 7) instead of an arbitrary register <code>BaseR</code>..</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">jmp</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// base_reg will either be an arbitrary register or the 
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// register 7 (`111`) which in this 
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// case it would be the `RET` operation.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> base_reg <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
    vm.registers.pc <span style="color:#f92672">=</span> vm.registers.get(base_reg);
}
</code></pre></div><h2 id="implementing-the-jsr-opcode">Implementing the JSR OpCode</h2>
<p>Also known as <code>JumptoSubRoutine</code>. The spec itself for this one is incredibly clear:</p>
<blockquote>
<p>First, the incremented PC is saved in R7. This is the linkage back to the calling routine. Then the PC is loaded with the address of the first instruction of the subroutine, causing an unconditional jump to that address. The address of the subroutine is obtained from the base register (if bit [11] is 0), or the address is computed by sign-extending bits [10:0] and adding this value to the incremented PC (if bit [11] is 1).</p>
</blockquote>
<p>The code, then, is pretty straightforward:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">jsr</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Grab the base register
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> base_reg <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// 0x7ff == 11111111111 (11 ones, exactly the length of PCOffset11)
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// Grab it and extend it to 16 bits.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> long_pc_offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7ff</span>, <span style="color:#ae81ff">11</span>);

    <span style="color:#75715e">// Grab the flag bit at [11] and test it
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> long_flag <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">11</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">1</span>;

    <span style="color:#75715e">// Save the incremented PC in R7
</span><span style="color:#75715e"></span>    vm.registers.r7 <span style="color:#f92672">=</span> vm.registers.pc;

    <span style="color:#66d9ef">if</span> long_flag <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
        <span style="color:#75715e">// JSR case, the address to jump is computed from PCOffset11
</span><span style="color:#75715e"></span>        <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.pc <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> long_pc_offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
        vm.registers.pc <span style="color:#f92672">=</span> val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>;
    } <span style="color:#66d9ef">else</span> {
        <span style="color:#75715e">// JSRR case, address to jump to lives in the base register
</span><span style="color:#75715e"></span>        vm.registers.pc <span style="color:#f92672">=</span> vm.registers.get(base_reg);
    }
}
</code></pre></div><h2 id="implementing-the-ld-opcode">Implementing the LD OpCode</h2>
<p>The standard load operation. Incredibly simple one!
<img src="/images/images/20210722171433.png" alt=""></p>
<p>We&rsquo;re loading onto a register <code>DR</code> the value stored in a place in memory computed using the <code>PCOffset9</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">ld</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Grab the PCOffset and sign extend it
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> pc_offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);

    <span style="color:#66d9ef">let</span> mem: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> pc_offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> vm.registers.pc <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;

    <span style="color:#75715e">// Read the value from the place where the memory above was computed
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> value <span style="color:#f92672">=</span> vm.read_memory(mem <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);

    <span style="color:#75715e">// Save that value to the direct register and update the condition register
</span><span style="color:#75715e"></span>    vm.registers.update(dr, value);
    vm.registers.update_r_cond_register(dr);
}
</code></pre></div><h2 id="implementing-the-ldr-opcode">Implementing the LDR OpCode</h2>
<p><img src="/images/images/20210722173139.png" alt="">
It stands for Load Base+Offset; it&rsquo;s a specialized version of the <code>LD</code> operation. The only difference is that instead of only using a base register, we add the base register to an <code>Offset6</code> (sign-extended to 16 bits) before loading.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">ldr</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;
    
    <span style="color:#75715e">// Grab the base register 
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> base_reg <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Grab the offset6 and sign extend it
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x3F</span>, <span style="color:#ae81ff">6</span>);

    <span style="color:#75715e">// Compute the memory location to be loaded
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.get(base_reg) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;

    <span style="color:#75715e">// Read the value at that memory location
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> mem_value <span style="color:#f92672">=</span> vm.read_memory(val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>).clone();

    <span style="color:#75715e">// Update the register with the loaded value and update the condition register
</span><span style="color:#75715e"></span>    vm.registers.update(dr, mem_value);
    vm.registers.update_r_cond_register(dr);
}
</code></pre></div><h2 id="implementing-the-st-opcode">Implementing the ST OpCode</h2>
<p><img src="/images/images/20210723113018.png" alt=""></p>
<p>Another simple operation: Store. It will store the contents in the register <code>SR</code> in the memory location computed by the current <code>PC</code> and the <code>PCOffset9</code>. As usual, the offset will be sign-extended to 16-bit.</p>
<p>The code for it is as easy as the description:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">st</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> sr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Grab the PC offset and sign extend it
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> pc_offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);

    <span style="color:#75715e">// Add the current PC to the PC offset
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// We&#39;re doing these conversions to avoid overflow
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.pc <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> pc_offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u16</span> <span style="color:#f92672">=</span> val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>;

    <span style="color:#75715e">// Store the value in the register being passed in the instruction at
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// the address computed above
</span><span style="color:#75715e"></span>    vm.write_memory(val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>, vm.registers.get(sr));
}
</code></pre></div><h2 id="implementing-the-sti-opcode">Implementing the STI OpCode</h2>
<p>Store indirect, just like <code>STORE</code>, but with a layer of indirection. The encoding is very similar, though:
<img src="/images/images/20210723113641.png" alt=""></p>
<p>This part of the official spec covers it well IMO:</p>
<blockquote>
<p>What is in memory at this address is the address of the location to which the data in SR is stored</p>
</blockquote>
<p>It kind of sounds like pointers, right?!</p>
<p>The code is pretty much the same as <code>ST</code> (Store) with one extra step:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">sti</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> sr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Grab the PC offset and sign extend it
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> pc_offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x1ff</span>, <span style="color:#ae81ff">9</span>);
    
    <span style="color:#75715e">// Add the current PC to the PC offset
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// We&#39;re doing these conversions to avoid overflow
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.pc <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> pc_offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u16</span> <span style="color:#f92672">=</span> val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>;

    <span style="color:#75715e">// This is the difference between STI and ST
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> address <span style="color:#f92672">=</span> vm.read_memory(val) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>;

    vm.write_memory(address, vm.registers.get(sr));
}
</code></pre></div><h2 id="implementing-the-str-opcode">Implementing the STR OpCode</h2>
<p>Store base+offset. Similar to Load Base+Offset, but store instead of load. The instruction has a base register and offset, and we add them together to get the place where we want to store the values in the register <code>SR</code>.
<img src="/images/images/20210723133337.png" alt=""></p>
<p>The code is also fairly simple:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">str</span>(instruction: <span style="color:#66d9ef">u16</span>, vm: <span style="color:#66d9ef">&amp;</span><span style="color:#a6e22e">mut</span> VM) {
    <span style="color:#75715e">// Get the register encoded in the instruction (see `add` fn for more in-depth details)
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> dr <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">9</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Grab the base register
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> base_reg <span style="color:#f92672">=</span> (instruction <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">6</span>) <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x7</span>;

    <span style="color:#75715e">// Grab the offset and sign extend it
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> offset <span style="color:#f92672">=</span> sign_extend(instruction <span style="color:#f92672">&amp;</span> <span style="color:#ae81ff">0x3F</span>, <span style="color:#ae81ff">6</span>);

    <span style="color:#75715e">// Get the value in the base_register and sum it to the offset encoded in the instruction
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// Note that we&#39;re doing some conversions here to prevent overflow.
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u32</span> <span style="color:#f92672">=</span> vm.registers.get(base_reg) <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span> <span style="color:#f92672">+</span> offset <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u32</span>;
    <span style="color:#66d9ef">let</span> val: <span style="color:#66d9ef">u16</span> <span style="color:#f92672">=</span> val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>;
    vm.write_memory(val <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>, vm.registers.get(dr));
}
</code></pre></div><p>And that&rsquo;s it! We&rsquo;ve implemented all the operations from the spec, and we can now run more complex programs.</p>
<p>However, we will need to add more IO control stuff to our VM, like handling keyboard input and such. Let&rsquo;s do that!</p>
<h2 id="memory-mapped-registers">Memory-mapped registers</h2>
<p>It&rsquo;s common to create special registers to interact with peripherals, like a keyboard and mouse. These registers are only accessed by reading and writing from a reserved memory location.</p>
<p>In LC-3, we have two of those special memory-mapped registers:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">enum</span> <span style="color:#a6e22e">MemoryMappedReg</span> {
    <span style="color:#75715e">// Keyboard status: The KBSR indicates whether a key has been pressed
</span><span style="color:#75715e"></span>    Kbsr <span style="color:#f92672">=</span> <span style="color:#ae81ff">0xFE00</span>,

    <span style="color:#75715e">// Keyboard data: The KBDR identifies which key was pressed
</span><span style="color:#75715e"></span>    Kbdr <span style="color:#f92672">=</span> <span style="color:#ae81ff">0xFE02</span>,
}
</code></pre></div><p>One for keyboard status (i.e., is key pressed?) and another for keyboard data (i.e., which key pressed?). Why not just use <code>getc</code> to get this information? I like <a href="https://github.com/justinmeiners"><strong>Justin Meiners</strong></a>&rsquo;s explanation about it:</p>
<blockquote>
<p>Although you can request keyboard input using <code>GETC</code>, this blocks execution until input is received. <code>KBSR</code> and <code>KBDR</code> allows you to <a href="https://en.wikipedia.org/wiki/Polling_(computer_science)">poll the state</a> of the device and continue execution, so the program can stay responsive while waiting for input.</p>
</blockquote>
<p>Okay, so when do we read/write from/to these registers? Simple enough, whenever we&rsquo;re reading the VM&rsquo;s memory, we will perform this check. That means we&rsquo;ll be extending our <code>read_memory</code> function from the beginning, which was:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">read_memory</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, address: <span style="color:#66d9ef">u16</span>) -&gt; <span style="color:#66d9ef">u16</span> {
    self.memory[address <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>]
}
</code></pre></div><p>And it will become this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-rust" data-lang="rust"><span style="color:#66d9ef">pub</span> <span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">read_memory</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self, address: <span style="color:#66d9ef">u16</span>) -&gt; <span style="color:#66d9ef">u16</span> {
    <span style="color:#66d9ef">if</span> address <span style="color:#f92672">==</span> MemoryMappedReg::Kbsr <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span> {
        self.handle_keyboard();
    }
    self.memory[address <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>]
}

<span style="color:#66d9ef">fn</span> <span style="color:#a6e22e">handle_keyboard</span>(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> self) {
    <span style="color:#66d9ef">let</span> <span style="color:#66d9ef">mut</span> buffer <span style="color:#f92672">=</span> [<span style="color:#ae81ff">0</span>; <span style="color:#ae81ff">1</span>];
    std::io::stdin().read_exact(<span style="color:#f92672">&amp;</span><span style="color:#66d9ef">mut</span> buffer).unwrap();
    <span style="color:#66d9ef">if</span> buffer[<span style="color:#ae81ff">0</span>] <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
        self.write_memory(MemoryMappedReg::Kbsr <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>, <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">15</span>);
        self.write_memory(MemoryMappedReg::Kbdr <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>, buffer[<span style="color:#ae81ff">0</span>] <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">u16</span>);
    } <span style="color:#66d9ef">else</span> {
        self.write_memory(MemoryMappedReg::Kbsr <span style="color:#66d9ef">as</span> <span style="color:#66d9ef">usize</span>, <span style="color:#ae81ff">0</span>)
    }
}
</code></pre></div><p>So, if the address we&rsquo;re reading is the address of the keyboard status register, we&rsquo;ll enter this &ldquo;keyboard handling mode,&rdquo; where we&rsquo;ll write the status and the keyboard data to these special registers.</p>
<p>With that done, we can now even run a game called Rogue in our LC-3 VM:
<img src="/images/images/rogue.gif" alt=""></p>
<p>The compiled object for the Rogue program is inside <code>examples/</code> in this project&rsquo;s repository. To run it: <code>cargo run -- examples/rogue.obj</code>.</p>
<h2 id="where-to-go-from-here">Where to go from here</h2>
<p>We have a working Virtual Machine for the LC-3 computer, that&rsquo;s awesome. We&rsquo;re able to run any compiled program that&rsquo;s supposed to run on LC-3 on our VM—This is super powerful!</p>
<p>However, we have one problem: we depend on <em>compiled</em> programs to do stuff with our VM. It would be nice to write LC-3 assembly in plaintext and compile it to the LC-3 architecture. This is something I&rsquo;d like to work on at some point as a continuation of this project—that and a disassembler, i.e., from the compiled <code>.obj</code> files to plaintext assembly.</p>
<p>I might work on that if I have the time and do another write-up that would be a follow-up to this one.</p>
]]></content></item><item><title>Golang pattern: graceful shutdown of concurrent events</title><link>/posts/golang-pattern-graceful-shutdown-of-concurrent-events/</link><pubDate>Fri, 30 Oct 2020 00:00:00 +0000</pubDate><guid>/posts/golang-pattern-graceful-shutdown-of-concurrent-events/</guid><description>Graceful shutdowns are a fundamental trait of most distributed systems. Often, gracefully shutting down a server is very straightforward: stop accepting new connections and let the open ones finish their job. This is usually handled by your server code of choice — Golang&amp;rsquo;s HTTP package has a shutdown method to help you with that. Yet, many cases need a more thorough and hand-crafted graceful shutdown, especially systems/services that are highly concurrent and/or are dealing with partitioned services / external services.</description><content type="html"><![CDATA[<p>Graceful shutdowns are a fundamental trait of most distributed systems. Often, gracefully shutting down a server is very straightforward: stop accepting new connections and let the open ones finish their job. This is usually handled by your server code of choice — Golang&rsquo;s HTTP package has a shutdown method to help you with that.
Yet, many cases need a more thorough and hand-crafted graceful shutdown, especially systems/services that are highly concurrent and/or are dealing with partitioned services / external services. Handling shutdown in these cases can get quite tricky, and forcefully shutting down the program can lead to weird bugs, most commonly, data loss.
In my experience, implementing a nice graceful shutdown mechanism at an early stage of a project is the best approach. Leaving it for later usually means performing complex surgical code changes in many places and potentially introducing newer bugs that are hard to catch.</p>
<p>Here is a simple pattern to apply graceful shutdowns when the program has some level of concurrency in it.
If you want to browse the code, you can skip the explanation and get them <a href="https://gist.github.com/digorithm/6ea1b0a129bea2ce4fac404143738cc5#file-simple-go">here</a>.</p>
<h2 id="a-simple-scenario">A simple scenario</h2>
<p>Let&rsquo;s consider a simple scenario where we have an HTTP endpoint that takes a job name, asynchronously starts 3 slow jobs related to this job (could be writing to a DB, S3, Kafka, and whatnot), and then responds a simple &ldquo;job started&rdquo; to the caller. The moment we return an answer to the caller doesn&rsquo;t mean it has finished the 3 slow jobs — they&rsquo;re running in the background, inside goroutines.</p>
<p><img src="/images/images/simplescenario.png" alt=""></p>
<p>This is a &ldquo;mock&rdquo; code that represents this scenario:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;fmt&#34;</span>
	<span style="color:#e6db74">&#34;log&#34;</span>
	<span style="color:#e6db74">&#34;net/http&#34;</span>
	<span style="color:#e6db74">&#34;time&#34;</span>
)


<span style="color:#75715e">/////////////////////////////////////////////////////////////
</span><span style="color:#75715e">/// 3 functions that take some time to run something fictitious
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>) {
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 1 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">5</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 1 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)

}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>) {
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 2 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">4</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 2 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>) {
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 3 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">3</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 3 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
}
<span style="color:#75715e">/////////////////////////////////////////////////////////////
</span><span style="color:#75715e"></span>
<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">handler</span>(<span style="color:#a6e22e">w</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">ResponseWriter</span>, <span style="color:#a6e22e">r</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Request</span>) {
	<span style="color:#a6e22e">jobName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">URL</span>.<span style="color:#a6e22e">Path</span>[<span style="color:#ae81ff">1</span>:]
	
	<span style="color:#75715e">// Spawn three goroutines that will run in the background
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// even after this function returns
</span><span style="color:#75715e"></span>	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">jobName</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">jobName</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">jobName</span>)
	
	<span style="color:#75715e">// Write back to the caller
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Fprintf</span>(<span style="color:#a6e22e">w</span>, <span style="color:#e6db74">&#34;job %s started&#34;</span>, <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">URL</span>.<span style="color:#a6e22e">Path</span>[<span style="color:#ae81ff">1</span>:])
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">HandleFunc</span>(<span style="color:#e6db74">&#34;/&#34;</span>, <span style="color:#a6e22e">handler</span>)
	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatal</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">ListenAndServe</span>(<span style="color:#e6db74">&#34;:8080&#34;</span>, <span style="color:#66d9ef">nil</span>))
}
</code></pre></div><p>Now let&rsquo;s imagine that this endpoint gets called many times per second. That means we&rsquo;re going to have <em>many</em> goroutines working in the background at any given time.</p>
<p>However, here&rsquo;s an important contract we&rsquo;ve implicitly made with our clients: once the job is started, it must be finished (well well well&hellip; what a surprise?). So, once we return &ldquo;job $name started&rdquo; to the client, they can be confident the service will execute it.</p>
<p>But, even assuming the server won&rsquo;t ever crash and burn, in cases of scheduled maintenance or deployment rollouts, this service will be shut down at some point so that updated versions of it can be rolled out. So what happens with our service, right now, if we send a SIGTERM or SIGINT to its PID? Let&rsquo;s see!</p>
<p><img src="/images/images/firstgif.gif" alt=""></p>
<p>Oops. Seems like a CTRL-c (SIGINT) or a SIGTERM (coming from a docker stop or something) would force the service to exit before finishing the already started jobs; that&rsquo;s not good.</p>
<p>Here&rsquo;s where proper shutdown is crucial. In this scenario, when we receive a SIGTERM, what we want is:</p>
<ol>
<li>Stop accepting new requests</li>
<li>Finish the jobs we already started</li>
<li>Exit</li>
</ol>
<p><strong>Important</strong>: note that if the HTTP requests were being handled synchronously, i.e., keeping the connection alive, a simple shutdown() in the HTTP server would suffice. It would wait for the handlers that are still working before shutting down the server. The tricky part here, however, is that the HTTP endpoint is acting as a trigger to more long-lived background-running jobs - a typical pattern. The HTTP connection between the client and server will be long gone before the jobs actually finish.</p>
<h3 id="signal-handling-and-server-shutdown">Signal handling and server shutdown</h3>
<p>First, we need to capture these UNIX signals, such as SIGTERM and SIGINT. Golang gives you a nice abstraction that takes the signals you wanna listen to and a channel that it will use to notify you. You, then, read from this channel to get notified about the signals you&rsquo;re listening to.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// Handle sigterm and await termChan signal
</span><span style="color:#75715e"></span><span style="color:#a6e22e">termChan</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">chan</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Signal</span>)
<span style="color:#a6e22e">signal</span>.<span style="color:#a6e22e">Notify</span>(<span style="color:#a6e22e">termChan</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">SIGTERM</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">SIGINT</span>)

<span style="color:#66d9ef">go</span> <span style="color:#66d9ef">func</span>() {
	<span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">termChan</span> <span style="color:#75715e">// Blocks here until interrupted
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Print</span>(<span style="color:#e6db74">&#34;SIGTERM received. Shutdown process initiated\n&#34;</span>)
	<span style="color:#a6e22e">httpServer</span>.<span style="color:#a6e22e">Shutdown</span>(<span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Background</span>())
}()
</code></pre></div><pre><code class="language-console" data-lang="console">$ go-complex-shutdown go run main.go
^C2020/10/21 17:42:52 SIGTERM received. Shutdown process initiated
2020/10/21 17:42:52 HTTP server shut down
</code></pre><p>Note the <code>^C</code>, meaning I just slapped a <code>CTRL-C</code> in there, sending a SIGTERM to the process. Now we&rsquo;re capturing it and shutting down the server. But we&rsquo;re still <em>not</em> waiting for the goroutines to finish their job.</p>
<h3 id="gracefully-shutting-down-the-server">Gracefully shutting down the server</h3>
<p>Now we&rsquo;re capturing the SIGTERMs and shutting down the HTTP server. Let&rsquo;s now wait for the running goroutines to finish before exiting the program.</p>
<p>To do that, we&rsquo;re going to use the good old sync.WaitGroup. We want to pass a waitgroup into the handler itself. For that, we&rsquo;ll have to create a custom handler struct that implements ServeHttp(w http.ResponseWriter, r *http.Request). Then we move the logic from the previous handler into this new ServeHTTP function</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// Our custom handler that holds a wait group used to 
</span><span style="color:#75715e">// block the shutdown while it&#39;s running the jobs.
</span><span style="color:#75715e"></span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CustomHandler</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewCustomHandler</span>(<span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">CustomHandler</span> {
	<span style="color:#75715e">// You can check for wg == nil if feeling paranoid
</span><span style="color:#75715e"></span>	<span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">CustomHandler</span>{<span style="color:#a6e22e">wg</span>: <span style="color:#a6e22e">wg</span>}
}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">h</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">CustomHandler</span>) <span style="color:#a6e22e">ServeHTTP</span>(<span style="color:#a6e22e">w</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">ResponseWriter</span>, <span style="color:#a6e22e">r</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Request</span>) {
	<span style="color:#a6e22e">vars</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mux</span>.<span style="color:#a6e22e">Vars</span>(<span style="color:#a6e22e">r</span>)
	<span style="color:#a6e22e">jobName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">vars</span>[<span style="color:#e6db74">&#34;jobName&#34;</span>]

	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Fprintf</span>(<span style="color:#a6e22e">w</span>, <span style="color:#e6db74">&#34;job %s started&#34;</span>, <span style="color:#a6e22e">jobName</span>)
	
	<span style="color:#75715e">// Here&#39;s where the magic happens. 
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// We&#39;ll use the *WaitGroup inside the handler struct to add 3 to it
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// and pass in the waitgroup to the slowJobs, they&#39;ll have to wg.Done()
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// once they return. 
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// Also keep in mind that this will happen for every HTTP 
</span><span style="color:#75715e"></span>    <span style="color:#75715e">// request coming in.
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// So at any given time, we&#39;ll have `3 * n` in the &#34;global&#34; WaitGroup,
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// where `n` is the number of requests.  
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Add</span>(<span style="color:#ae81ff">3</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">jobName</span>, <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">jobName</span>, <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">jobName</span>, <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>)
}
</code></pre></div><p>And now our <code>slowJob</code> functions will look like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>) {
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Done</span>()

	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 1 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">5</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 1 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
}
</code></pre></div><p>And that&rsquo;s about it. Let&rsquo;s see how it behaves once we interrupt the program:</p>
<p><img src="/images/images/secondgif.gif" alt=""></p>
<p>Awesome, working just as intended — no jobs interrupted while shutting down and no new jobs started! The idea behind how we achieved this is fairly simple and you can easily replicate this pattern elsewhere. In my experience, this can be tricky to implement at later stages of the project. More things are going on, more concurrency, more layers. Introducing this capability, then, becomes quite a surgical task. Just imagine passing WaitGroup (or context objects) deeper into different layers. It&rsquo;s not impossible, plus, if it makes our systems more reliable, predictable, and fault-tolerant, it&rsquo;s usually worth the effort. But doing it early on is definitely a better approach.</p>
<h3 id="full-code">Full code</h3>
<p>Here&rsquo;s the full code for what we&rsquo;ve created so far:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;context&#34;</span>
	<span style="color:#e6db74">&#34;fmt&#34;</span>
	<span style="color:#e6db74">&#34;net/http&#34;</span>
	<span style="color:#e6db74">&#34;os&#34;</span>
	<span style="color:#e6db74">&#34;os/signal&#34;</span>
	<span style="color:#e6db74">&#34;sync&#34;</span>
	<span style="color:#e6db74">&#34;syscall&#34;</span>
	<span style="color:#e6db74">&#34;time&#34;</span>

	<span style="color:#e6db74">&#34;log&#34;</span>

	<span style="color:#e6db74">&#34;github.com/gorilla/mux&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>) {
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Done</span>()
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 1 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">5</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 1 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>) {
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Done</span>()
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 2 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">4</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 2 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>) {
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Done</span>()
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;starting job 3 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Sleep</span>(<span style="color:#ae81ff">3</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>)
	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;finished job 3 for %s\n&#34;</span>, <span style="color:#a6e22e">name</span>)
}

<span style="color:#75715e">// Our custom handler that holds a wait group used to block the shutdown 
</span><span style="color:#75715e">// while it&#39;s running the jobs.
</span><span style="color:#75715e"></span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CustomHandler</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewCustomHandler</span>(<span style="color:#a6e22e">wg</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">CustomHandler</span> {
	<span style="color:#75715e">// You can check for wg == nil if feeling paranoid
</span><span style="color:#75715e"></span>	<span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">CustomHandler</span>{<span style="color:#a6e22e">wg</span>: <span style="color:#a6e22e">wg</span>}
}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">h</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">CustomHandler</span>) <span style="color:#a6e22e">ServeHTTP</span>(<span style="color:#a6e22e">w</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">ResponseWriter</span>, <span style="color:#a6e22e">r</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Request</span>) {
	<span style="color:#a6e22e">vars</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mux</span>.<span style="color:#a6e22e">Vars</span>(<span style="color:#a6e22e">r</span>)
	<span style="color:#a6e22e">jobName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">vars</span>[<span style="color:#e6db74">&#34;jobName&#34;</span>]

	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Fprintf</span>(<span style="color:#a6e22e">w</span>, <span style="color:#e6db74">&#34;job %s started&#34;</span>, <span style="color:#a6e22e">jobName</span>)

	<span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Add</span>(<span style="color:#ae81ff">3</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">jobName</span>, <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">jobName</span>, <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>)
	<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">jobName</span>, <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">wg</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">wg</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>{}
	<span style="color:#a6e22e">customHandler</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">NewCustomHandler</span>(<span style="color:#a6e22e">wg</span>)

	<span style="color:#a6e22e">router</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mux</span>.<span style="color:#a6e22e">NewRouter</span>()
	<span style="color:#a6e22e">router</span>.<span style="color:#a6e22e">Handle</span>(<span style="color:#e6db74">&#34;/{jobName}&#34;</span>, <span style="color:#a6e22e">customHandler</span>)

	<span style="color:#a6e22e">httpServer</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Server</span>{
		<span style="color:#a6e22e">Addr</span>:    <span style="color:#e6db74">&#34;:8080&#34;</span>,
		<span style="color:#a6e22e">Handler</span>: <span style="color:#a6e22e">router</span>,
	}

	<span style="color:#75715e">// Handle sigterm and await termChan signal
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">termChan</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">chan</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Signal</span>)
	<span style="color:#a6e22e">signal</span>.<span style="color:#a6e22e">Notify</span>(<span style="color:#a6e22e">termChan</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">SIGTERM</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">SIGINT</span>)

	<span style="color:#66d9ef">go</span> <span style="color:#66d9ef">func</span>() {
		<span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">termChan</span> <span style="color:#75715e">// Blocks here until interrupted
</span><span style="color:#75715e"></span>		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Print</span>(<span style="color:#e6db74">&#34;SIGTERM received. Shutdown process initiated\n&#34;</span>)
		<span style="color:#a6e22e">httpServer</span>.<span style="color:#a6e22e">Shutdown</span>(<span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Background</span>())
	}()

	<span style="color:#75715e">// Blocking
</span><span style="color:#75715e"></span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">httpServer</span>.<span style="color:#a6e22e">ListenAndServe</span>(); <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Error</span>() <span style="color:#f92672">!=</span> <span style="color:#e6db74">&#34;http: Server closed&#34;</span> {
			<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;HTTP server closed with: %v\n&#34;</span>, <span style="color:#a6e22e">err</span>)
		}
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;HTTP server shut down&#34;</span>)
	}
	

	<span style="color:#75715e">// This is where, once we&#39;re closing the program, we wait for all
</span><span style="color:#75715e"></span>	<span style="color:#75715e">// jobs (they all have been added to this WaitGroup) to `wg.Done()`.
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;waiting for running jobs to finish&#34;</span>)
	<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Wait</span>()
	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;jobs finished. exiting&#34;</span>)
}
</code></pre></div><h2 id="a-more-complex-scenario">A more complex scenario</h2>
<p>Now, another typical pattern is to send the jobs straight to a shared job queue that&rsquo;ll be consumed by a consumer process (likely in a separate goroutine), now it looks like this:</p>
<p><img src="/images/images/complexscenario.png" alt=""></p>
<p>Let&rsquo;s not get into the discussion of keeping all jobs in memory for now — a better approach would be writing these jobs to a Kafka topic — but the principle of graceful shutdown works roughly the same way for both. Still, with an in-memory job queue, we can easily demonstrate how to gracefully shut it down.</p>
<p>Once we get a SIGTERM, we want to:</p>
<ol>
<li>Stop the HTTP handler from writing more jobs to the job queue</li>
<li>Stop the HTTP server from accepting new connections</li>
<li>Drain the job queue by running the leftover jobs in there</li>
<li>Actually shut down the program</li>
</ol>
<p>Fortunately, Golang provides us with a nice construct for this: channel and controlling the flow to it is just a matter of closing it.</p>
<p>This is how our consumer looks like:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">consumer</span>(<span style="color:#a6e22e">jobQueue</span> <span style="color:#66d9ef">chan</span> <span style="color:#66d9ef">string</span>) {
	<span style="color:#a6e22e">wg</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>{}

	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">job</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">jobQueue</span> {
		<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Add</span>(<span style="color:#ae81ff">3</span>)
		<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">job</span>, <span style="color:#a6e22e">wg</span>)
		<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">job</span>, <span style="color:#a6e22e">wg</span>)
		<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">job</span>, <span style="color:#a6e22e">wg</span>)
	}

	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;Waiting for running jobs to finish&#34;</span>)
	<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Wait</span>()
	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;Done, shutting down the consumer&#34;</span>)
}
</code></pre></div><p>The <code>slowJobN</code> functions are the same from the previous scenario.</p>
<p>Now our handler simply writes to a channel that&rsquo;s acting as our job queue:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">h</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">CustomHandler</span>) <span style="color:#a6e22e">ServeHTTP</span>(<span style="color:#a6e22e">w</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">ResponseWriter</span>, <span style="color:#a6e22e">r</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Request</span>) {
	<span style="color:#a6e22e">vars</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mux</span>.<span style="color:#a6e22e">Vars</span>(<span style="color:#a6e22e">r</span>)
	<span style="color:#a6e22e">jobName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">vars</span>[<span style="color:#e6db74">&#34;jobName&#34;</span>]

	<span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">jobQueue</span> <span style="color:#f92672">&lt;-</span> <span style="color:#a6e22e">jobName</span>

	<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Fprintf</span>(<span style="color:#a6e22e">w</span>, <span style="color:#e6db74">&#34;job %s started&#34;</span>, <span style="color:#a6e22e">jobName</span>)
}
</code></pre></div><p>And our <code>main</code> gets a wee bit more complicated, now that the consumer should be the blocking part of this workflow:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">jobQueue</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">chan</span> <span style="color:#66d9ef">string</span>)

	<span style="color:#a6e22e">customHandler</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">NewCustomHandler</span>(<span style="color:#a6e22e">jobQueue</span>)

	<span style="color:#a6e22e">router</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mux</span>.<span style="color:#a6e22e">NewRouter</span>()
	<span style="color:#a6e22e">router</span>.<span style="color:#a6e22e">Handle</span>(<span style="color:#e6db74">&#34;/{jobName}&#34;</span>, <span style="color:#a6e22e">customHandler</span>)

	<span style="color:#a6e22e">httpServer</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Server</span>{
		<span style="color:#a6e22e">Addr</span>:    <span style="color:#e6db74">&#34;:8080&#34;</span>,
		<span style="color:#a6e22e">Handler</span>: <span style="color:#a6e22e">router</span>,
	}

	<span style="color:#75715e">// Handle sigterm and await termChan signal
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">termChan</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">chan</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Signal</span>)
	<span style="color:#a6e22e">signal</span>.<span style="color:#a6e22e">Notify</span>(<span style="color:#a6e22e">termChan</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">SIGTERM</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">SIGINT</span>)

	<span style="color:#66d9ef">go</span> <span style="color:#66d9ef">func</span>() {
		<span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">termChan</span> <span style="color:#75715e">// Blocks here until interrupted
</span><span style="color:#75715e"></span>		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;SIGTERM received. Shutdown process initiated&#34;</span>)

		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;stopping the consumer&#34;</span>)

		<span style="color:#75715e">// This will force the consumer to stop its main loop
</span><span style="color:#75715e"></span>		close(<span style="color:#a6e22e">jobQueue</span>) 

		<span style="color:#a6e22e">httpServer</span>.<span style="color:#a6e22e">Shutdown</span>(<span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Background</span>())
	}()

	<span style="color:#66d9ef">go</span> <span style="color:#66d9ef">func</span>() {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">httpServer</span>.<span style="color:#a6e22e">ListenAndServe</span>(); <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Error</span>() <span style="color:#f92672">!=</span> <span style="color:#e6db74">&#34;http: Server closed&#34;</span> {
				<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;HTTP server closed with: %v\n&#34;</span>, <span style="color:#a6e22e">err</span>)
			}
			<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;HTTP server shut down&#34;</span>)
		}
	}()

	<span style="color:#75715e">// Now the consumer is the blocking part
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">consumer</span>(<span style="color:#a6e22e">jobQueue</span>)
}
</code></pre></div><p>And the trick is simply grabbing the SIGTERM and closing the <code>jobQueue</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go">close(<span style="color:#a6e22e">jobQueue</span>) 
</code></pre></div><p>This means, from a producer (the handler) perspective: you can&rsquo;t write to the channel anymore (can&rsquo;t write to closed channels). And from a consumer perspective: it can read the data inside the channel, even if it was closed, but once we reach the last bit of data in there, the for-loop will break.</p>
<p>Once we&rsquo;ve started all the slowJobNs, and after the for-loop breaks, we&rsquo;ll be waiting on that wg.Wait(). Meaning that we&rsquo;ve drained the jobQueue and waited for all of them to finish before exiting the program.</p>
<p>You can find the full code here: <a href="https://gist.github.com/digorithm/6ea1b0a129bea2ce4fac404143738cc5#file-jobqueue-go">https://gist.github.com/digorithm/6ea1b0a129bea2ce4fac404143738cc5#file-jobqueue-go</a></p>
<h3 id="making-this-code-better">Making this code better</h3>
<p>Thanks to some comments, I&rsquo;ve noticed a few issues with this last iteration, namely:</p>
<ol>
<li>Calling <code>httpServer.Shutdown()</code> in a goroutine can cause some weird issues.</li>
<li>There&rsquo;s a race condition between the goroutine that closes the channel (<code>close(jobQueue)</code>), and the handler writing to this channel (<code>h.jobQueue &lt;- jobName</code>). That means the handler could write to a closed channel and the program would panic.</li>
<li><code>Context</code>&rsquo;s cancellation is a much better way to propagate shutdown signals.</li>
</ol>
<p>So let&rsquo;s do another iteration here and fix some loose ends.</p>
<p>For the main, let&rsquo;s create a <code>context.WithCancel</code> and a channel that we&rsquo;ll pass to the consumer and it will use to tell us when the jobs are finished, and it&rsquo;s safe to exit the program:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">ctx</span>, <span style="color:#a6e22e">cancel</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">WithCancel</span>(<span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Background</span>())

<span style="color:#75715e">// ...
</span><span style="color:#75715e">// ... same as before
</span><span style="color:#75715e">// ...
</span><span style="color:#75715e"></span>
<span style="color:#75715e">// doneChan will be the channel we&#39;ll be listening on
</span><span style="color:#75715e">// to know all already started jobs have finished
</span><span style="color:#75715e">// before we actually exit the program
</span><span style="color:#75715e"></span><span style="color:#a6e22e">doneChan</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">chan</span> <span style="color:#66d9ef">interface</span>{})
<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">consumer</span>(<span style="color:#a6e22e">ctx</span>, <span style="color:#a6e22e">jobQueue</span>, <span style="color:#a6e22e">doneChan</span>) <span style="color:#75715e">// &lt;- not blocking anymore
</span></code></pre></div><p>Now, to solve the first problem (&quot;<em>Calling <code>httpServer.Shutdown()</code> in a goroutine can cause some weird issues&quot;</em>), we won&rsquo;t block on the consumer anymore. Instead, we&rsquo;ll run the consumer on a separate goroutine and move our shutdown logic to be inside the <code>main()</code> itself:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// Wait for SIGTERM to be captured
</span><span style="color:#75715e"></span><span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">termChan</span>
<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;SIGTERM received. Shutdown process initiated&#34;</span>)

<span style="color:#75715e">// Shutdown the HTTP server
</span><span style="color:#75715e"></span><span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">httpServer</span>.<span style="color:#a6e22e">Shutdown</span>(<span style="color:#a6e22e">ctx</span>); <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Server Shutdown Failed:%+v&#34;</span>, <span style="color:#a6e22e">err</span>)
}

<span style="color:#75715e">// Cancel the context, this will make the consumer stop
</span><span style="color:#75715e"></span><span style="color:#a6e22e">cancel</span>()

<span style="color:#75715e">// Wait for the consumer&#39;s jobs to finish
</span><span style="color:#75715e"></span><span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;waiting consumer to finish its jobs&#34;</span>)
<span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">doneChan</span>
<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;done. returning.&#34;</span>)
</code></pre></div><p>Now upon a <code>SIGTERM</code> we&rsquo;ll <code>cancel()</code> the context, which will trigger the consumer to stop, then we&rsquo;ll wait on <code>doneChan</code> for the running jobs to finish. Now our consumer looks like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">consumer</span>(<span style="color:#a6e22e">ctx</span> <span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Context</span>, <span style="color:#a6e22e">jobQueue</span> <span style="color:#66d9ef">chan</span> <span style="color:#66d9ef">string</span>, 
									<span style="color:#a6e22e">doneChan</span> <span style="color:#66d9ef">chan</span> <span style="color:#66d9ef">interface</span>{}) {
	<span style="color:#a6e22e">wg</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">sync</span>.<span style="color:#a6e22e">WaitGroup</span>{}

	<span style="color:#66d9ef">for</span> {
		<span style="color:#66d9ef">select</span> {
		<span style="color:#75715e">// If the context was cancelled, a SIGTERM was captured
</span><span style="color:#75715e"></span>        <span style="color:#75715e">// So we wait for the jobs to finish, 
</span><span style="color:#75715e"></span>        <span style="color:#75715e">// write to the done channel and return
</span><span style="color:#75715e"></span>		<span style="color:#66d9ef">case</span> <span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">ctx</span>.<span style="color:#a6e22e">Done</span>():
            <span style="color:#75715e">// Note that the waiting time here is unbounded 
</span><span style="color:#75715e"></span>            <span style="color:#75715e">// and can take a long time. If that&#39;s an issue you can:
</span><span style="color:#75715e"></span>			<span style="color:#75715e">// (1) issue a SIGKILL after a certain time or
</span><span style="color:#75715e"></span>			<span style="color:#75715e">// (2) use a context with timeout
</span><span style="color:#75715e"></span>			<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Wait</span>()
			<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;writing to done channel&#34;</span>)
			<span style="color:#a6e22e">doneChan</span> <span style="color:#f92672">&lt;-</span> <span style="color:#66d9ef">struct</span>{}{}
			<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;Done, shutting down the consumer&#34;</span>)
			<span style="color:#66d9ef">return</span>
		<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">job</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">jobQueue</span>:
			<span style="color:#a6e22e">wg</span>.<span style="color:#a6e22e">Add</span>(<span style="color:#ae81ff">3</span>)
			<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob1</span>(<span style="color:#a6e22e">job</span>, <span style="color:#a6e22e">wg</span>)
			<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob2</span>(<span style="color:#a6e22e">job</span>, <span style="color:#a6e22e">wg</span>)
			<span style="color:#66d9ef">go</span> <span style="color:#a6e22e">slowJob3</span>(<span style="color:#a6e22e">job</span>, <span style="color:#a6e22e">wg</span>)
		}
	}
}
</code></pre></div><p>Much cleaner and self-contained, isn&rsquo;t it?  Now once we <code>cancel()</code> the context, the <code>case &lt;-ctx.Done()</code> will be selected, and we&rsquo;ll not consume from the <code>jobQueue</code> anymore, wait for the running ones to finish, then let the main thread know the consumer is done. This solves the potential risk of writing to a closed channel (the channel isn&rsquo;t being closed anymore). With a context with cancellation coming from the entrypoint, we can pass it further down in more complex scenarios.</p>
<p>Full code here: <a href="https://gist.github.com/digorithm/fc68573db5618bb6d57d090fd66528bd">https://gist.github.com/digorithm/fc68573db5618bb6d57d090fd66528bd</a></p>
<hr>
<p><em>Thanks to <a href="https://github.com/kennylouie">Kenny Louie</a> and <a href="https://www.reddit.com/user/epsleq0/">epsleq0</a> for reviewing this piece.</em></p>
]]></content></item><item><title>From synchronous service calls to message-passing dataflow systems</title><link>/posts/from-synchronous-service-calls-to-message-passing-dataflow-systems/</link><pubDate>Mon, 15 Jul 2019 00:00:00 +0000</pubDate><guid>/posts/from-synchronous-service-calls-to-message-passing-dataflow-systems/</guid><description>In this past year I have been working on a big system that is fundamentally an ETL to process real estate data across the US and Canada. I can&amp;rsquo;t talk much about the business details, but let&amp;rsquo;s say that if you&amp;rsquo;re browsing for real estate properties, it&amp;rsquo;s very likely you&amp;rsquo;re using this system. You&amp;rsquo;re welcome. Or I&amp;rsquo;m sorry, who knows?
I joined this project from the very beginning. When I joined, a couple of technical decisions had been made.</description><content type="html"><![CDATA[<p>In this past year I have been working on a <em>big</em> system that is fundamentally an ETL to process real estate data across the US and Canada. I can&rsquo;t talk much about the business details, but let&rsquo;s say that if you&rsquo;re browsing for real estate properties, it&rsquo;s very likely you&rsquo;re using this system. You&rsquo;re welcome. Or I&rsquo;m sorry, who knows?</p>
<p>I joined this project from the very beginning. When I joined, a couple of technical decisions had been made. Initially, before I&rsquo;d arrived on this project, the microservices would talk to each other directly, REST/gRPC style. Nothing new here.</p>
<p><img src="/images/images/2019-07-11_19-154e43ee-0c5f-4866-9efc-7af7ac54e7f4.22.05.png" alt="">
<em>Simple architecture where the services talk to each other directly</em></p>
<p>The great majority of these services communicated with each other through synchronous calls. In most scenarios, this would be 100% fine. In an ETL constantly streaming copious amounts of data that need fast processing though? Not so much.</p>
<p>One big problem with this architecture is that this application isn&rsquo;t an &ldquo;user-triggered&rdquo; application and the events happens in a streaming fashion, i.e this is a streaming system, synchronous calls then quickly become a bottleneck. For instance: to process property X we&rsquo;d need to wait for all other services to do their jobs before moving onto the property X + 1.</p>
<p>And because of that property (streaming system), it means we can go full asynchronous here; we want to stream data in a constant flow and each service will do its job independently.</p>
<p><img src="/images/images/2019-07-12_15-15a5f630-c173-4a14-ab93-ee1bf2ca5092.07.25.png" alt="">
<em>Direct communication through an API gateway vs. streaming system using message-passing (fully async)</em></p>
<p>However, an unfortunate bad technical decision had been made before I arrived on this project: yes, they would go from sync requests to async requests, but they would do it through a service developed internally called <code>Queuer</code>, which, in hindsight, was nothing like a queue. Queuer would just take the request coming from one service, buffer it, and route it to another service (again, not a queue), which sounded more like what you&rsquo;d get from a service mesh, but without all the reliability that you&rsquo;d get from battle-tested robust tools. We had something like this:</p>
<p><img src="/images/images/2019-07-11_19-9c20194e-2150-4c4a-b12b-89bd5224e801.28.54.png" alt="">
<em>A queueing system that acts exactly like an API gateway</em></p>
<p>We had many problems with this:</p>
<ol>
<li>Maintaining a &ldquo;queueing&rdquo; system built in-house was terrible.</li>
<li><code>Queuer</code> wasn&rsquo;t service-agnostic; we had to encode domain knowledge about other services inside <code>Queuer</code>.</li>
<li>My favourite: Queuer had a buffer, which was simply a in-memory variable. It would buffer thousands of jobs there. If queuer died, well, the jobs were lost. Oh and forget about deliver-once guarantees and/or other goodies you can get by using a battle-tested queueing system such as RabbitMQ or Kafka.</li>
</ol>
<p>About 3 months into the project I convinced people to move away from Queuer, it had become too much of a hassle to maintain and evolve it. Godspeed <code>Queuer</code>.</p>
<p>Also, around that time I was reading <code>designing data-intensive data applications</code>. It advocates &ndash; with very good arguments &ndash; for what&rsquo;s called Message-Passing Dataflow. I&rsquo;d seen this somewhere else with the name event-centric architecture or something like that; but I believe the philosophies between them are very similar. I like the simple way the author explains it, so here it is:</p>
<blockquote>
<p>Composing stream operators into dataflow systems has a lot of similar characteristics
to the microservices approach. However, the underlying communication mechanism is very different: one-directional, asynchronous message streams rather than
synchronous request/response interactions.</p>
</blockquote>
<p>I then decided to experiment with Message-Passing Dataflow; after all, we&rsquo;re talking about a never-ending stream processing system. Therefore, I didn&rsquo;t want much synchronous communication between the services and wanted something that&rsquo;s closer to an actual streaming system.</p>
<p>To achieve this, we need a central component that would act as a communication bus, streaming messages between the services. And the services, instead of being just HTTP rest APIs, would be active consumers, consuming messages from this bus.</p>
<p><img src="/images/images/2019-07-12_15-542f22e7-5cae-4f21-aabe-d232f4f56360.27.22.png" alt="">
<em>Services consume messages being passed to the channels they&rsquo;re subscribed to</em></p>
<p>Not surprisingly, I decided to use Kafka as our communication bus. The services around Kafka are Kafka consumers and producers. All communication between the services happens through <em>message passing</em>.</p>
<p>Here are some observations after adopting this paradigm:</p>
<h2 id="async-usually-means-that-it-will-be-faster">Async usually means that it will be faster</h2>
<p>I noticed that this approach is faster that what we had before. A service does one thing and does it as fast as it can and don&rsquo;t have to wait for the next steps. Then, it might produce a message to Kafka, which will be a job being performed by other services, and that&rsquo;s it.</p>
<h2 id="more-robustness">More robustness</h2>
<p>This approach is much, much more robust. All services are completely stateless and they don&rsquo;t hold jobs in memory. The service died? All good, the job can be easily recovered from Kafka, Kafka only moves its offsets when the offsets are commited, i.e when the service actually finishes the job.</p>
<h2 id="you-must-think-about-how-you-handle-the-offsets">You must think about how you handle the offsets</h2>
<p>Even though it&rsquo;s robust, consumers must be smart about it. Consuming offsets from topics (think of it as jobs in a queue) and failing to commit the new offset properly can be catastrophic. For instance, if we have a Kafka producer&rsquo;s <code>auto.commit</code> enabled, the service reads a message from a topic, the auto commit mechanism commits after a few milliseconds, but then the process fail. That means we marked that offset as consumed, but we didn&rsquo;t finished the job, so it&rsquo;s&hellip; well, lost. Manually committing the offsets is much more reliable in high risk cases.</p>
<h2 id="a-different-and-refreshing-computational-model">A different and refreshing computational model</h2>
<p>It&rsquo;s a very different computational model. Instead of proactively querying things from other services, we <em>subscribe</em> to channels of messages (called topics) and work our way through the messages in there.
It&rsquo;s closer to Alan Kay&rsquo;s view of object-oriented programming (<a href="https://ovid.github.io/articles/alan-kay-and-oo-programming.html">https://ovid.github.io/articles/alan-kay-and-oo-programming.html</a>). And I&rsquo;m not talking about <em>that</em> OOP created by the C++/Java community, but the core ideas of OOP thought by Kay and colleagues back in the early days of computing &ndash; which curiously was grounded in Biology. The idea of passing messages to objects in order to better scale systems (like biological cells do!). Kafka is nothing but a (very reliable) communication bus, and the objects (services, microservices, whatever) attach themselves to it and listen to messages, responding accordingly and sending other kinds of messages back to kafka which will be consumed by other services. Once you have well-defined messages and protocols, things flow beautifully.</p>
<h2 id="watch-out-for-waste">Watch out for waste</h2>
<p>Be careful with idle consumers, that means you gotta think about your partitions carefully. What&rsquo;s worked for us is to set 1:1 partition-to-consumer ratio. For instance, we have an image processing service that fetches jobs from kafka. If we have more instances of that services than partitions, that means some of those instances will be idle, preventing us from achieving a higher throughput than we could.</p>
<h3 id="closing-thoughts">Closing thoughts</h3>
<p>I am, now, a big fan of this architectural style I can totally recommend <em>if it fits your problems</em>. Which in most cases it does. I believe we&rsquo;ve been going with the flow that was set in the early 00s when it comes to architecting systems; we&rsquo;ve been using the request-response paradigm without really questioning its efficacy.</p>
<p>To close, the author of <code>designing data-intensive applications</code> has some really cool insights about this paradigm:</p>
<blockquote>
<p>It would be very natural to extend this programming model to also allow a server to
push state-change events into this client-side event pipeline. Thus, state changes
could flow through an end-to-end write path: from the interaction on one device that
triggers a state change, via event logs and through several derived data systems and
stream processors, all the way to the user interface of a person observing the state on
another device. These state changes could be propagated with fairly low delay—say,
under one second end to end.</p>
</blockquote>
<blockquote>
<p>Some applications, such as instant messaging and online games, already have such a
“real-time” architecture (in the sense of interactions with low delay, not in the sense
of “Response time guarantees”). <strong>But why don’t we build all applications
this way?</strong></p>
</blockquote>
<blockquote>
<p>The challenge is that the assumption of stateless clients and request/response interac‐
tions is very deeply ingrained in our databases, libraries, frameworks, and protocols.
Many datastores support read and write operations where a request returns one
response, but much fewer provide an ability to subscribe to changes—i.e., a request
that returns a stream of responses over time.</p>
</blockquote>
<blockquote>
<p>In order to extend the write path all the way to the end user, we would need to funda‐
mentally rethink the way we build many of these systems: moving away from request/
response interaction and toward publish/subscribe dataflow. I think that the
advantages of more responsive user interfaces and better offline support would make
it worth the effort. If you are designing data systems, I hope that you will keep in
mind the option of subscribing to changes, not just querying the current state.</p>
</blockquote>
<p>My next steps? Experimenting with this architecture for applications where the events <em>are</em> user-triggered and the results are near real-time and user-facing.</p>
]]></content></item><item><title>On machine learning enhanced software systems</title><link>/post/machine-learning-enhanced-software/</link><pubDate>Wed, 13 Dec 2017 00:00:00 +0000</pubDate><guid>/post/machine-learning-enhanced-software/</guid><description>I have been brewing the idea of using machine learning to improve software systems since 2016. It was pretty vague and broad, without an actionable plan. I just had the intuition — the software configuration and tuning, especially after the adoption of microservices, was getting too complex.
The increasing complexity of configuring and tuning systems If you have enough experience in the software industry, then it’s very likely that you’ve struggled with either a configuration problem or a tuning problem.</description><content type="html"><![CDATA[<p>I have been brewing the idea of using machine learning to improve software systems since 2016. It was pretty vague and broad, without an actionable plan. I just had the intuition — the software configuration and tuning, especially after the adoption of microservices, was getting too complex.</p>
<h3 id="the-increasing-complexity-of-configuring-and-tuning-systems">The increasing complexity of configuring and tuning systems</h3>
<p>If you have enough experience in the software industry, then it’s very likely that you’ve struggled with either a configuration problem or a tuning problem.</p>
<p>Configuration and tuning problems are pretty common and can lead to really bad outages. They often occur when:</p>
<ol>
<li>
<p>Some parts of the system are poorly or wrongly configured, or</p>
</li>
<li>
<p>A configuration that worked before now doesn’t work because the context of the system has changed.</p>
</li>
</ol>
<p>Think of a number of database replicas and their writing schemes. Or in Postgresql, think of the number of shared buffers, effective cache size, and the min and max wal size.</p>
<p>If wrongly configured from the start, it won’t work in the given context, plain and simple. What’s more interesting, though, is if it’s <em>correctly</em> configured, it might work at a given time. But as the context changes — system workload, system resources usage, overall system architecture — the system will behave poorly. Or, even worse, an outage might happen.</p>
<p>This will, inevitably, lead to manually-performed operations and the creation of heuristics. In other words, it will lead to:</p>
<blockquote>
<p>Oh, we should set X to A, when workload is T, but it should be A+10 when workload is T+100 and we have system resources usage above 80%… I guess. Or maybe let’s just up a queue in front of this component, queues solve everything, right?</p>
</blockquote>
<p>Now multiply this scenario by tens or hundreds of services. Think for a second about the cognitive burden resulting from these configurations.</p>
<p>This is not a new concern. In 2003, Ganek and Corbi <a href="http://ieeexplore.ieee.org/document/5386835/?reload=true">discussed</a> the need for autonomic computing to handle the complexity of managing software systems. They noted that managing complex systems became too costly, labor-intensive, and prone to error due to the pressure engineers felt while maintaining them. This increased the potential of system outages with a concurrent impact on business.</p>
<p>Even nowadays, most of the configurations and tuning of the systems are performed manually, often in run-time, which is known to be a very time-consuming and risky practice. Check out these two links (<a href="https://link.springer.com/book/10.1007/978-3-642-35813-5">here</a> and <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.8651&amp;rep=rep1&amp;type=pdf">here</a>) to read more about it.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*6Kh0EXVHQ9zmau8kLs4pzQ.jpeg" alt=""></p>
<h3 id="the-need-for-autonomic-computing">The need for autonomic computing</h3>
<p>Most decisions to configure and tune the system are made based on the context — there are many different variables such as workload, number of instances of some services, resources usage, and more. So why not delegate these tasks to something that excels at exactly that? <em>Machine learning sounds like a feasible tool for the job.</em></p>
<p>After starting my Masters at the University of British Columbia, I kept working on this idea. It seemed interesting although quite weird, and, sometimes, unpractical and impossible to implement.</p>
<p>To my surprise, I realized I wasn’t alone. Some very interesting people were working on these ideas — so it might not be that weird, unpractical, and impossible.</p>
<p>Recently, Jeff Dean — a man that I admire a lot — <a href="https://news.ycombinator.com/item?id=15892956">gave a talk at NIPS 2017 talking about machine learning for systems</a>, where he stated:</p>
<blockquote>
<p>Learning should be used throughout our computing systems. Traditional low-level systems code (operating systems, compilers, storage systems) does not make extensive use of machine learning today. This should change!</p>
</blockquote>
<blockquote>
<p>Computer Systems are filled with heuristics: compilers, networking code, operating systems. Heuristics have to work well “in general case”. [They] generally don’t adapt to actual pattern of usage and don’t take into account available context</p>
</blockquote>
<blockquote>
<p>Learning in the core of all of our computer systems will make them better/more adaptive.</p>
</blockquote>
<p>I was in complete awe when I read this. One of the engineers I admire the most was talking about the very same ideas I’ve been thinking about and working on.</p>
<p>This led me to think that it’s not only interesting but <strong>natural to think about enhancing software systems with machine learning.</strong> Throughout the whole software stack, we have many heuristics that, although they work well, could be improved by machine learning.</p>
<p>Is it challenging and potentially risky? Yes, most definitely. Especially given that interpretability, apparently, has become a secondary goal in the machine learning community. How can we interpret and explain the decisions made by neural nets?</p>
<p>However, with that said, these obstacles shouldn’t hinder scientific and technological progress. <a href="https://arxiv.org/pdf/1712.01208.pdf">Yes, we should question old paradigms </a>and try to improve things.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*puiL2EVDE6Ztlocw3JD1uQ.png" alt=""></p>
<h3 id="towards-machine-learning-enhanced-software-systems">Towards machine learning-enhanced software systems</h3>
<p>As Jeff Dean pointed out: we need to find <strong>practical</strong> ways to make systems data-aware. We need systems that collect metrics and metadata about themselves. To achieve this, we could learn a thing a two from the ideas in systems observability and instrumentation. We have been instrumenting systems for decades, and the data is already there.</p>
<p>We also need to find <strong>practical</strong> and <strong>clean</strong> ways to <strong>integrate</strong> machine learning components into software systems, making learning a first-class citizen in the system. This will lead to <strong>systems that learn how to improve themselves,</strong> beating heuristics and manually-performed operations. Think about this for a second. It does sound cool <em>and</em> feasible.</p>
<p>I would also add that we need <strong>practical</strong> and <strong>clean</strong> ways to propagate the decisions made by the learned models to the rest of the system. This would allow the system to have self-adaptive capabilities. Here, we could learn something from the control theory community.</p>
<p>The general idea is fairly simple: make a system learn about its behavior by training a model on its context. Then allow it to change its structures and configurations in order to optimize for a certain scenario. Now implement this idea in such a way that it could be possible to integrate it into many kinds of systems.</p>
<h3 id="summary">Summary</h3>
<p>The most interesting questions I have in mind are:</p>
<ol>
<li>
<p>Can self-adaptation by learned models lead to more stable, faster, safer software systems? Can it reduce the need for manually configuring and tuning systems, allowing engineers to focus on more important tasks?</p>
</li>
<li>
<p>Can this be easily integrated into software systems, requiring only small changes to the codebase?</p>
</li>
<li>
<p>Can this work with low overhead?</p>
</li>
</ol>
<p>It is worth noting that this <strong>would not</strong> replace good engineers, but would rather free the engineers’ cognitive abilities to focus on what matters.</p>
<p><a href="http://www.sysml.cc/">I genuinely believe that this will become a trend in the next few years</a>. I myself am working on these ideas as part of my graduate studies, and I will be posting the results of my research, so <a href="https://twitter.com/digorithm">stay tuned</a>.</p>
]]></content></item><item><title>Neural Computation: An Intuitive Understanding of the Perceptron</title><link>/post/neural-computation-pt1/</link><pubDate>Thu, 16 Jul 2015 00:00:00 +0000</pubDate><guid>/post/neural-computation-pt1/</guid><description>&lt;p>Artificial Neurons is one of the most beautiful ways to simulate a biological behavior through computation, despite the fact that it&amp;rsquo;s not very close to the level of details of a real neuron. But it captured the core of what a neuron is doing.&lt;/p>
&lt;p>And I find that trying to understand this mathematical method by first understanding the concept through a metaphor &lt;em>(which, in this case, I think that the metaphor is our mathematical side, and not the biological one, the biological is just, you know, the real thing)&lt;/em> is really valuable to gain an intuition on this topic.&lt;/p></description><content type="html"><![CDATA[<p>Artificial Neurons is one of the most beautiful ways to simulate a biological behavior through computation, despite the fact that it&rsquo;s not very close to the level of details of a real neuron. But it captured the core of what a neuron is doing.</p>
<p>And I find that trying to understand this mathematical method by first understanding the concept through a metaphor <em>(which, in this case, I think that the metaphor is our mathematical side, and not the biological one, the biological is just, you know, the real thing)</em> is really valuable to gain an intuition on this topic.</p>
<p>If you were about to make a decision, given many variables, how would you make this decision? It may not look obvious, due the fact that, on normal occasions, we&rsquo;re not thinking about our thinking process, but the truth is, we are collecting those variables that affect the future decision, and we&rsquo;re giving weights to them. Weights? how? Simple, some variables are more crucial than other while making decision, isn&rsquo;t it? the word <em>&lsquo;crucial&rsquo;</em>, in this case, means a huge weight on this variable, and it will strongly affect the final decision.</p>
<p>Suppose a scenario: we&rsquo;re deciding whether we should go to beach or not. Let&rsquo;s put a few binary variables on table:</p>
<ol>
<li>Are we in the mood to go to the beach?</li>
<li>Is it raining?</li>
<li>Our other friends are going?</li>
<li>Do we have money?</li>
</ol>
<p>So, depending on those variables, it will be more likely that we will go to the beach&hellip; or not. Let&rsquo;s think about the variable <em>&lsquo;is it raining?'</em>, if it&rsquo;s raining, we can say that it&rsquo;s a deal breaker, so we can conclude that this variable has more weights than the other. The fact is that we already trained those weights inside our brain, long time ago.</p>
<p>That&rsquo;s what an Artificial Neuron try to do, the AN try to learn the weights of things so it can make decisions. So, drawing back to the mathematical and computational aspect of it, the perceptron is a single unit that will receive external inputs*(variables)*, it will have a weight for each input, it will do some computation, send this result to a decision function, and, finally, output the final decision.</p>
<p>Those inputs are the variables we&rsquo;re talking before, and like our process to make a decision, the Perceptron will weight each input to make a decision.</p>
<p>Now, how the Perceptron knows how the weights should be for each input? Well&hellip; it doesn&rsquo;t. At least, not from the beginning of the learning process, just like you and me, when trying to learn something new.</p>
<p>That&rsquo;s why this case is a case of supervised learning, what the Perceptron will do is: start with a random small weights, take one previously trained example <em>(e.g: (1) yes to mood to beach, (2) not raining, (3) yes to friends going to beach and (4) yes to money, the output: 1 - yes, we shall go to the beach)</em> do some computation taking in consideration the random weights we defined before, send it to a decision function, output something <em>(1 - yes, 0 - no)</em> and check if this output is equal to the expected <em>(we&rsquo;re using a trained example, remember?)</em>, of course that at the first try, it won&rsquo;t be equal. So the Perceptron calculate the error rate and update its weights&hellip; after this, guess what? it repeat the process of trying to predict, but now, with the updated weights, after a few tries, the error rate tends to reduce and it starts predicting correctly. So it learned to predict a behavior, by training with previously trained examples.</p>
<p>So, a nice learning behavior would be something like this:</p>
<!-- raw HTML omitted -->
<p>Which means, at every iteration <em>(we call it epochs)</em>, the error rate tend to decrease and, as consequence, the Perceptron starts to predict correctly!</p>
<p>As you may have noted, I omitted a few details of the process so you could see the whole picture of the process: we take an example, we practice on it, we see what we missed, we try again, we learn. That&rsquo;s the core process.</p>
<p>Now, to the details:</p>
<h3 id="the-computation">The computation</h3>
<p>The first step that the Perceptron does it&rsquo;s a computation that I referred as <em>&ldquo;some computation&rdquo;</em>, this is a simple computation, it&rsquo;s just a simple Linear Combination of the feature vector <em>(the variables)</em> and the weight vector, which is just the sum of the products between feature/input and its respective weight:</p>
<p>$$
x_{1}w_{1}+x_{2}w_{2}+x_{3}w_{3}+ \cdots +x_{n}w_{n}
$$</p>
<p> </p>
<h3 id="the-decision-function">The Decision Function</h3>
<p>So, after the Linear Combination, we send the result of it to a decision function, which will, somehow, based on some threshold <em>(or without a threshold as we&rsquo;re going to see)</em>, give us the output, that will be checked with the correct output, in case if it&rsquo;s correct, fine, keep the weights like this, otherwise, it will calculate the error rate, adjust the weights and restart the process.</p>
<p> </p>
<h4 id="binary-output-with-threshold">Binary output with threshold</h4>
<p>This technique is very simple, after the linear combination, if the output is bigger than some threshold, it outputs 1 and we say that the neuron was activated, otherwise, output 0.</p>
<p>$$
\begin{equation}
X=
\begin{cases}
1, &amp; \text{if}\ Linear,Combination&gt;0 \<br>
0, &amp; \text{otherwise}
\end{cases}
\end{equation}
$$</p>
<p> </p>
<h4 id="using-sigmoid-function">Using sigmoid function</h4>
<p>Now, that a interesting one, it won&rsquo;t use a threshold anymore, we&rsquo;ll send the output of the Linear Combination to a sigmoid function</p>
<p>$$
S(\vec{w}\vec{x}) = \dfrac{1}{1+e^{-\vec{w}\vec{x}}}
$$</p>
<p>which will, then, smooth the output, making it in the range of 0 and 1. Which is the most used in many Machine Learning Algorithms.</p>
<!-- raw HTML omitted -->
<h3 id="adjusting-the-weights-and-learning">Adjusting the weights and learning</h3>
<p>After the perceptron fails to predict correctly, it&rsquo;s time to adjust the weight, using some rule, the classic perceptron has 2 rules:</p>
<p> </p>
<h4 id="perceptron-learning-rule">Perceptron Learning Rule</h4>
<p>This is very simple, when the perceptron has the incorrect output, it update its weights following this:</p>
<p>$$
w_{i} = w_{i} + \eta (t_{i} - o_{i})x_{i}
$$</p>
<p>Which is simply multiplying a learning rate <em>(usually 0.001)</em> by the difference between the correct output and the wrong output and then multiplying it by its original input, after this, we add this value to the previous weight and then we have the value of the new weight.
It&rsquo;s fair simple, isn&rsquo;t it? The problem arises when the data isn&rsquo;t linearly separable, like this:</p>
<!-- raw HTML omitted -->
<p> </p>
<p>With this scenario, the result just won&rsquo;t converge. So we adopt another rule!</p>
<p> </p>
<h4 id="delta-rule">Delta Rule</h4>
<p>Now we must find a way to have a non-linear output, and what&rsquo;s the best for this if not the classic Gradient Descent algorithm? GD will simply search through hypothesis spaces and try to minimize the cost function, I wrote about this <!-- raw HTML omitted -->here<!-- raw HTML omitted -->.</p>
<!-- raw HTML omitted -->
<p>So, it&rsquo;s just a technique to solve our previous problem, but still, the weights will be updated <em>(now, using the GD)</em> and then the process start over!</p>
<p> </p>
<h3 id="code-of-a-perceptron">Code of a Perceptron</h3>
<p>Now, here&rsquo;s a code of a Perceptron that will behave like a simple Boolean function. I didn&rsquo;t use the Delta Dule (Gradient Descent) to optimize the weights, as this problem (binary Boolean functions) is linearly separable.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">  <span style="color:#f92672">import</span> math
  <span style="color:#f92672">from</span> numpy <span style="color:#f92672">import</span> random, array
  <span style="color:#f92672">from</span> random <span style="color:#f92672">import</span> choice
  <span style="color:#f92672">import</span> matplotlib.pyplot <span style="color:#66d9ef">as</span> plt

  <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Perceptron</span>():
      
      <span style="color:#e6db74">&#34;&#34;&#34;
</span><span style="color:#e6db74">      this is the thereshold to activate the unit 
</span><span style="color:#e6db74">      &#34;&#34;&#34;</span>
      <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">activation</span>(self,x):
          <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">1</span><span style="color:#f92672">/</span>(<span style="color:#ae81ff">1</span> <span style="color:#f92672">+</span> math<span style="color:#f92672">.</span>exp(<span style="color:#f92672">-</span>x))

      <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">linear_combination</span>(self, X):
          total <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>
          <span style="color:#66d9ef">for</span> i <span style="color:#f92672">in</span> xrange(len(self<span style="color:#f92672">.</span>weights)):
              total <span style="color:#f92672">+=</span> self<span style="color:#f92672">.</span>weights[i] <span style="color:#f92672">*</span> X[i]
          <span style="color:#66d9ef">return</span> total
      
      <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">unit_output</span>(self, X):
          <span style="color:#66d9ef">return</span> self<span style="color:#f92672">.</span>activation(self<span style="color:#f92672">.</span>linear_combination(X))

      <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">train</span>(self, training_data, epochs):
          
          self<span style="color:#f92672">.</span>learning_rate <span style="color:#f92672">=</span> <span style="color:#ae81ff">0.5</span>
          self<span style="color:#f92672">.</span>errors <span style="color:#f92672">=</span> []

          <span style="color:#75715e"># initializing weights</span>
          self<span style="color:#f92672">.</span>weights <span style="color:#f92672">=</span> random<span style="color:#f92672">.</span>rand(len(training_data[<span style="color:#ae81ff">1</span>][<span style="color:#ae81ff">0</span>]))
          
          <span style="color:#66d9ef">for</span> i <span style="color:#f92672">in</span> xrange(epochs):
              X, y <span style="color:#f92672">=</span> choice(training_data)
              <span style="color:#75715e"># &gt; calculate output with current weight</span>
              output <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>unit_output(X)
              <span style="color:#75715e"># &gt; calculate error rate (t - o)</span>
              error_rate <span style="color:#f92672">=</span> y <span style="color:#f92672">-</span> output
              self<span style="color:#f92672">.</span>errors<span style="color:#f92672">.</span>append(error_rate)
              print <span style="color:#e6db74">&#39;the X: &#39;</span>, X
              print <span style="color:#e6db74">&#39;output: &#39;</span>,output
              print <span style="color:#e6db74">&#39;correct target: &#39;</span>, y
              <span style="color:#75715e"># &gt; apply learning rule which will update weights</span>
              self<span style="color:#f92672">.</span>weights <span style="color:#f92672">+=</span> self<span style="color:#f92672">.</span>learning_rate <span style="color:#f92672">*</span> error_rate <span style="color:#f92672">*</span> X

      <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">predict</span>(self,X):
          y <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>unit_output(X)
          <span style="color:#66d9ef">return</span> y
                  

          training_data <span style="color:#f92672">=</span> [
                  (array([<span style="color:#ae81ff">0</span>,<span style="color:#ae81ff">0</span>,<span style="color:#ae81ff">1</span>]), <span style="color:#ae81ff">0</span>),
                  (array([<span style="color:#ae81ff">0</span>,<span style="color:#ae81ff">1</span>,<span style="color:#ae81ff">1</span>]), <span style="color:#ae81ff">0</span>),
                  (array([<span style="color:#ae81ff">1</span>,<span style="color:#ae81ff">0</span>,<span style="color:#ae81ff">1</span>]), <span style="color:#ae81ff">0</span>),
                  (array([<span style="color:#ae81ff">1</span>,<span style="color:#ae81ff">1</span>,<span style="color:#ae81ff">1</span>]), <span style="color:#ae81ff">1</span>),
                  
          ]

  p <span style="color:#f92672">=</span> Perceptron()

  p<span style="color:#f92672">.</span>train(training_data, <span style="color:#ae81ff">2000</span>)
  print p<span style="color:#f92672">.</span>predict([<span style="color:#ae81ff">1</span>,<span style="color:#ae81ff">0</span>,<span style="color:#ae81ff">1</span>])
  plt<span style="color:#f92672">.</span>plot(p<span style="color:#f92672">.</span>errors)
  plt<span style="color:#f92672">.</span>ylabel(<span style="color:#e6db74">&#39;errors&#39;</span>)
  plt<span style="color:#f92672">.</span>xlabel(<span style="color:#e6db74">&#39;epochs&#39;</span>)
  plt<span style="color:#f92672">.</span>show()</code></pre></div>
<h3 id="conclusion-and-next-steps">Conclusion and next steps</h3>
<p>With this we conclude what a simple single Perceptron is doing! Of course there are many improvements on it and we can connect many of these Artificial Neurons in many layers&hellip; that&rsquo;s what is called Artificial Neural Network, I&rsquo;ll be writing about it soon!</p>]]></content></item><item><title>Gradient Descent Algorithm in Java</title><link>/posts/gradient-descent-algorithm-in-java/</link><pubDate>Fri, 09 Jan 2015 00:00:00 +0000</pubDate><guid>/posts/gradient-descent-algorithm-in-java/</guid><description>&lt;h3 id="how-can-we-make-a-machine-learn-from-data">How can we make a machine learn from data?&lt;/h3>
&lt;p>Then, how can we make the machine predicts things based on that learned data? Those are the question answered by one of the most classic Machine Learning Algorithms, the &lt;strong>Gradient Descent Algorithm&lt;/strong>, from a Mathematical-Statistical side it’s called &lt;strong>Univariate Linear Regression&lt;/strong>.&lt;/p>
&lt;p>This is one of the tools of the Machine Learning toolbox, and what it tries to do is to model a relationship between a scalar dependent variable Y and a explanatory variable X.&lt;/p>
&lt;h3 id="in-laymans-term">In Layman’s term…&lt;/h3>
&lt;p>Let’s suppose you have a few points distributed in a Graph, so you already know that in a point A you have a well defined X and Y, which means, if you input X, your output will be Y, and in a point B you have a well defined X’ and Y’ as well. But, thing is, if a point emerge between A and B, and you only have the X… what will be the Y &lt;em>(the output)&lt;/em>?&lt;/p></description><content type="html"><![CDATA[<h3 id="how-can-we-make-a-machine-learn-from-data">How can we make a machine learn from data?</h3>
<p>Then, how can we make the machine predicts things based on that learned data? Those are the question answered by one of the most classic Machine Learning Algorithms, the <strong>Gradient Descent Algorithm</strong>, from a Mathematical-Statistical side it’s called <strong>Univariate Linear Regression</strong>.</p>
<p>This is one of the tools of the Machine Learning toolbox, and what it tries to do is to model a relationship between a scalar dependent variable Y and a explanatory variable X.</p>
<h3 id="in-laymans-term">In Layman’s term…</h3>
<p>Let’s suppose you have a few points distributed in a Graph, so you already know that in a point A you have a well defined X and Y, which means, if you input X, your output will be Y, and in a point B you have a well defined X’ and Y’ as well. But, thing is, if a point emerge between A and B, and you only have the X… what will be the Y <em>(the output)</em>?</p>
<p>What this algorithm does is: <strong>It tries to predict this Y value, based on the previous data</strong>! Amazing, right?</p>
<p>At the end of the execution, you’ll have a full trend line that you can use to predict values! just like the image below.</p>
<p><img src="/content/images/2015/06/linearRegression.png" alt=""></p>
<h3 id="the-theory-behind-it">The Theory Behind It</h3>
<p>I’ll cover a few theories about this algorithm here, but, it won’t be complete, as this demand a great coverage of mathematical material that if I would write it all here, It would be a <em>long, long</em>, <strong>very</strong> <em>long</em> post. So I’m assuming that you’re already familiar with Calculus <em>(Sums, Partial Derivatives)</em>, Statistics and Discrete Mathematics.</p>
<p>So, our goal here is to <strong>fit the best straight line in our initial data</strong>, right?</p>
<p>Thus, we need something to represent this straight line, which will be our hypothesis function:</p>
<!-- raw HTML omitted -->
<p>Where this \( \Theta_{0} \) and \( \Theta_{1} \) are the parameters of the function, and <strong>finding the best parameters for this function is what is going to give us the correct straight line to plot on our data</strong>.</p>
<p>Here’s an example of what we&rsquo;re trying to do, which is, fit the best straight line in the data:</p>
<p><img src="/content/images/2015/06/Linear-regression.svg" alt=""></p>
<p>So what we want to do is to find a \( \Theta_{0} \) and \( \Theta_{1} \) so our Hypothesis outputs can be very close to the real Y output.</p>
<p>Formally we want:</p>
<!-- raw HTML omitted -->
<p>So we want <strong>minimize</strong> \( \Theta_{0} \) and \( \Theta_{1} \) so the difference between the <strong>Hypothesis</strong> and the <strong>real output</strong> is minimal.</p>
<p><strong>But we want it for every point in our data</strong>, which is \(x(i)\) <em>(which is the i-th x of our data)</em>, so we want the <strong>sum of this average</strong>, which is, formally:</p>
<!-- raw HTML omitted -->
<p>And we’re going to call this function <strong>Cost Function</strong>, with the following notation:</p>
<!-- raw HTML omitted -->
<p>So, our goals is to <strong>minimize this cost function</strong>:</p>
<!-- raw HTML omitted -->
<p>This cost function is also called <a href="http://en.wikipedia.org/wiki/Mean_squared_error">Square Error Function</a>.</p>
<h3 id="now-the-gradient-descent-algorithm">Now, the gradient descent algorithm</h3>
<p>With our cost function built, we need to “keep” finding values for \( \Theta_{0} \) and \( \Theta_{1} \) so we can reach our ideal trend line. So, basically:</p>
<p>1. We start with some \( \Theta_{0} \) and \( \Theta_{1} \)</p>
<p>2. keep changing \( \Theta_{0} \) and \( \Theta_{1} \) to reduce our cost function \( J(\Theta_{0}, \Theta_{1}) \), until we find the minimum.</p>
<p>That’s quite simple and intuitive, right? There’s a lot of intuitive explanation and more visual examples of what this algorithm is doing in the <a href="https://class.coursera.org/ml-007/">machine learning course taught by Andrews Ng (From Stanford)</a>.</p>
<p>What this algorithm will be doing is: partially derive our cost function for \( \Theta_{0} \) and \( \Theta_{1} \) simultaneously, so we can find the minimum value for them, with every iteration updating our \( \Theta_{0} \) and \( \Theta_{1} \) with their new value!</p>
<blockquote>
<p>Meh, talk is cheap show me the math!</p>
</blockquote>
<p>Formally, the algorithm is:</p>
<!-- raw HTML omitted -->
<p><em><strong>Make sure that this will run for j = 0 and j = 1.</strong></em></p>
<p>But, pay attention, this is the generic version, the \( \Theta_{j} \) represent both \( \Theta_{0} \) and \( \Theta_{1} \).</p>
<p>What the algorithm is saying is that we’ll be doing this procedure to \( \Theta_{0} \) and \( \Theta_{1} \) at the same time! So, we can put it in this way:</p>
<!-- raw HTML omitted -->
<p>Also, we can expand the <strong>Cost Function</strong> that is being derived, doing this, it will be exactly what I’ll be putting into code soon, so, our <strong>final algorithm</strong> is:</p>
<!-- raw HTML omitted -->
<p><strong>Now it’s time to code all of it!</strong></p>
<p>First things first, we’ll be using <a href="http://code.google.com/p/jmathplot/">Google’s JMathPlot</a> to plot graphs using Java and Swing to use its JFrame, we shall start with our class to represent our <strong>Initial Data</strong>, which will be the <strong>Training Set</strong>.</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p><img src="/content/images/2015/06/example-plot.png" alt=""></p>
<p>Now we’re going to take our first steps on writing the <strong>GradientDescent.java</strong>, we must be very careful here. Let’s start with the main settings and parameters of it:</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p>Now let me explain a few details of this part:</p>
<p><strong>Alpha</strong> is the <strong>Learning Rate</strong>, it’s a <em>dangerous variable</em>, it’s used to set the size of the step that the algorithm will take while trying to find the \( \Theta_{0} \) and \( \Theta_{1} \), that’s the learning rate of the algorithm. If Alpha is <strong>too low</strong>, the algorithm can be very slow, although very precise, if Alpha is <strong>higher</strong>, it will be taking <strong>larger steps</strong>, which can be <strong>faster</strong>, or <strong>dangerous</strong>, causing the algorithm to <strong>DIVERGE</strong>, which, <em>trust me</em>, you don’t want this! <em>(Andrew Ng explain this part very well in its course)</em></p>
<p>The variable <strong>TrendLine</strong> is what we’ll use to plot the straight line which is our main goal.</p>
<p>The <strong>tol</strong> variable is our safe move in case of a dangerous convergence, which means, in case of convergence, it will stop the execution.</p>
<p>The other variables and objects in this part are very intuitive to understand, it’s auto explainable! <em>(forgive if i’m wrong, just say something and I’ll put more detail on that)</em>.</p>
<p>About the Constructor, we’re saying that our initial guesses for \( \Theta_{0} \) and \( \Theta_{1} \) is 0. The rest is just data plotting.</p>
<p><strong>next: our Hypothesis Function</strong> <em>(that will be doing exactly as the model that I did show above)</em></p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p>Now, our two function to derive our \( \Theta \), again, it will be doing exactly the same as the mathematical model, there’s no magic!</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p>Note that it does <em>almost</em> exactly the same as the mathematical model of the Gradient Descent demonstrated above, the difference is only a few details, such as the <em>if</em> and <em>while</em> to verify convergence or divergence <em>(which is, if it reached the iteration’s limit)</em></p>
<p>Next we have the <strong>addTrendLine</strong> function, used to keep plotting our straight line as it will become more updated.</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p>And now we have an extra, it’s a function to store and plot the convergence history of both \( \Theta_{0} \) and \( \Theta_{1} \), so we can see how it happened.</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p>Finally, we have our <strong>Test Class</strong>, that will execute everything:</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<p>Now, executing the code, the output will be, at first, the initial data:</p>
<p><img src="/content/images/2015/06/example-plot-2.png" alt=""></p>
<p><strong>Executing the algorithm, it learns and generate its prediction based on its initial data:</strong></p>
<p><img src="/content/images/2015/06/example-plot-line-e1420763780646.png" alt=""></p>
<h3 id="magical-right">Magical, right?</h3>
<p>And then, we can see the <strong>convergence</strong>:</p>
<p><img src="/content/images/2015/06/example-convergence.png" alt=""></p>
<p>And you can see in the terminal the final values of \( \Theta_{0} \) and \( \Theta_{1} \) that minimized the Cost Function.</p>
<p><em>If it wasn’t Science, probably would be black magic. heh.</em></p>
<h3 id="a-few-considerations">A few considerations</h3>
<p>You can download the complete code <a href="https://github.com/digorithm/ArtificialIntelligenceAlgorithms">here</a>.</p>
<p>If you have any questions/suggestion, drop me an email so we can talk!</p>
<p>If you need further details of the mathematical model, I ultra advice to watch Andrew’s Ng Videos at Stanford@Coursera. <strong>His skills to teach it is something unbelievable awesome</strong>.</p>
<p><em>Thanks for reading!</em></p>]]></content></item></channel></rss>