<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2Ffeed.xml" rel="self" type="application/atom+xml" /><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F" rel="alternate" type="text/html" /><updated>2026-05-24T14:05:14+00:00</updated><id>https://de-engineer.github.io/feed.xml</id><title type="html">de engineering</title><subtitle>Blogs related to low level stuff, mainly focused on Vulnerability Research and Reverse Engineering.</subtitle><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><entry><title type="html">Agents Engineering: Context</title><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FAgents-Engineering-Context%2F" rel="alternate" type="text/html" title="Agents Engineering: Context" /><published>2026-01-16T00:00:00+00:00</published><updated>2026-01-16T00:00:00+00:00</updated><id>https://de-engineer.github.io/Agents-Engineering-Context</id><content type="html" xml:base="https://de-engineer.github.io/Agents-Engineering-Context/"><![CDATA[<p>The influx of tools and techniques to optimize and improve agentic systems is becoming overwhelming. We have something new coming out every few days which promises to solve all our problems. It’s hard to keep up with it all.</p>

<p>We have spent the last few months reading everything that seems effective in theory and tried it in practice. However, covering all of the methods in one post is not possible, thus this blog specifically covers everything around context engineering.</p>

<h2 id="harness">Harness</h2>

<p>The harness is the operating system of the agent. We know that an agent is just a loop of LLM and tools, similarly, how the tools are provided, how the context is managed, how the compaction is done, etc. are the jobs of the harness.</p>

<p>ChatGPT is a chat interface harness, not ideal for long running coding workflows, however, before we had Claude Code and Opencode almost all of us had accepted that copy pasting code from the editor to the input box was the ideal or the best way.</p>

<p>Different harnesses have different tools, different system prompts, different ways to manage the context, etc.</p>

<p>The model is as good as the harness, this is why models running inside <a href="iframe.php?url=https%3A%2F%2Ffactory.ai%2Fnews%2Fterminal-bench">droid can reach higher scores on benchmarks</a> vs. others.
There are many things we don’t know that agents can do, simply because there is no ideal harness for it.</p>

<p>All the techniques we use for making our agents better are essentially techniques of harness engineering. Now, with that out of the way, we will proceed to the understanding and techniques of actually doing harness engineering. This post is all about context.</p>

<h2 id="context">Context</h2>

<p>The context is short term, volatile memory like RAM for the agent. The identity of the agent, the tool definitions, the tool calls made by the agent and their outputs, etc. all live in the context.</p>

<p><img src="iframe.php?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FG-xXUTza4AAUZGr%3Fformat%3Djpg%26amp%3Bname%3Dlarge" alt="Context visualised in claude code" style="height:200px;width:auto;" /></p>

<p>As the context fills, the abilities of the model deteriorates. Some models like Gemini 3 flash/pro have a context window of 1 million tokens, which sounds huge in theory and definitely is compared to any other model in the market, however, in practice most models are good only until ~60-70% of their context is filled.
This is, in the most strict sense a limited resource. Every new tool added, every new MCP server added, every new instruction added fills up the context. Chroma Research called this <a href="iframe.php?url=https%3A%2F%2Fresearch.trychroma.com%2Fcontext-rot">context rot</a>.</p>

<p>Thus, the best way to preserve agent performance is to guarantee that the model’s context contains the least amount of useless tokens.
While techniques such as compaction (discussed later) do help, they are no silver bullet. Compaction could be the death of your agent if not done properly.</p>

<h2 id="context-engineering">Context Engineering</h2>

<p>Context engineering is all about minimizing the bloat in the context window of the model so it can do it’s best. There are very clever ways to do this. Let us discuss them one by one.</p>

<h3 id="1-tool-reduction">1. Tool Reduction</h3>

<p>If your agent has both a Bash tool and a python_package_install tool, which one will the agent use when it has to install a Python package?</p>

<p>These types of scenarios confuse the model. This is a simple example, but you can think how the same applies to reading files, or deleting files, etc.</p>

<p>This confusion can lead the agent to waste effort thinking (gpt-5.2-xhigh we’re looking at you), which is not what we want, as it all fills up the context window.
You always have to ask yourself when adding a new tool whose job can by done by an existing tool:</p>

<blockquote>
  <p>Can we make the agent do the same task using an existing tool without overloading the context with new instructions?</p>
</blockquote>

<p>The answer to this is up to you to decide.</p>

<h4 id="1a-tool-minimization">1A. Tool minimization</h4>

<p>If you’re providing the agent with custom tools that you yourself have written, or have full control over - you can analyze the trace of the agent to remove the parameters or instructions which the agent seems to not use.</p>

<p>For example, if your Bash tool has a cwd parameter but the agent seems to just use cd or full paths to do it’s operations, then you can consider removing it.</p>

<p>This can in practice, reduce the bloat from the tool definitions. Remember, every token counts.</p>

<h4 id="1b-batching">1B. Batching</h4>

<p>Another thing you can do by analyzing traces is finding out if the agent does something in multiple steps which can be done in one step.</p>

<p>For example, we found out that our agent was using one tool to first find the definition of a function, which returned it the line number and another one to actually get the definition’s code. We optimized this simply by adding a <code class="language-plaintext highlighter-rouge">include_source</code> parameter in the tool.
Now the agent can do both things with one tool call. The definition of the other tool is no longer needed.</p>

<h4 id="1c-scripting">1C. Scripting</h4>

<p>If there are a bunch of things, which can’t be batched as one tool because of the complexity of operations - you can always write scripts in Bash or Python which do those things and then put them in a <code class="language-plaintext highlighter-rouge">scripts/</code> folder and give the agent access to them.</p>

<p>These scripts now become new tools for the agent that it can discover simply by doing <code class="language-plaintext highlighter-rouge">ls</code> inside the scripts directory.</p>

<p>Of course, some amount of custom system instructions is needed for this, but it can be very high ROI.</p>

<h3 id="2-mcp">2. MCP</h3>

<p>MCP tools are great, however as soon as you connect to one you load all the definitions of every tool defined to your context.</p>

<p>This is the same problem as we discussed earlier when talking about tools but it is scaled up because MCP tools are written by someone else or hosted somewhere else.</p>

<p>This is bad because unless you manipulate the underlying framework (e.g. langchain) which you use to connect, there are very few things you can do.
There are a few solutions to this. Some MCP providers, e.g. Exa allow you to specify which tools you want through a get parameter.</p>

<p><img src="iframe.php?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FG-s1IshbQAIVmme%3Fformat%3Djpg%26amp%3Bname%3Dlarge" alt="Exa MCP documentation" style="height:200px;width:auto;" /></p>

<p>If you are developing an MCP server, you MUST do this.</p>

<p>This is, however, not reliable because tons of MCP servers don’t have this. So, what do we do?</p>

<h4 id="2a-code-mode">2A. Code Mode</h4>

<p>According to <a href="iframe.php?url=https%3A%2F%2Fblog.cloudflare.com%2Fcode-mode%2F">this article by Cloudflare research</a>, converting the MCP tools into a TypeScript API, and then asking an LLM to write code that calls that API.</p>

<p><img src="iframe.php?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FG-s29nLbQAI1fm2%3Fformat%3Djpg%26amp%3Bname%3Dmedium" alt="Benefits of Code Mode from Cloudflare" style="height:200px;width:auto;" /></p>

<p>This can be very helpful, because now you and the agent have more control over the available tools. Now, you can more easily modify them as your agent needs, if this is something you can do.</p>

<h4 id="2b-cli-mode">2B. CLI Mode</h4>

<p>The other variant of code mode is when you convert MCP server into a CLI tool. We call this CLI mode. We discovered this by <a href="iframe.php?url=https%3A%2F%2Fwww.philschmid.de%2Fcontext-engineering-part-2">reading this Manus’ blog post</a>.</p>

<p>We have personally done this for the <a href="iframe.php?url=https%3A%2F%2Fgithub.com%2Fpwno-io%2Ftreesitter-mcp%2F">treesitter-mcp server</a> that we wrote by creating a tool <code class="language-plaintext highlighter-rouge">ts-cli</code> which the agent uses as needed! No preloading instruction, no bloat!</p>

<p>Now the agent can use the CLI tool as needed and will only load how to use it by calling <code class="language-plaintext highlighter-rouge">--help</code>.</p>

<p><del>This is a little hard for MCP servers that you did not write yourself but again, it is worth the ROI.</del></p>

<p>Philipp Schmid has released <a href="iframe.php?url=https%3A%2F%2Fgithub.com%2Fphilschmid%2Fmcp-cli">mcp-cli</a> which does this for you!</p>

<h4 id="2c-design-your-mcp-server">2C. Design your MCP server</h4>

<p>Instead of first taking an MCP server and then developing tooling around it to optimize it, you can just build your own MCP server over the API of that service.</p>

<p>This is really easy since most MCP providers also have an API and you can likely vibe engineer it in a few hours.</p>

<p><a href="iframe.php?url=https%3A%2F%2Fblog.fsck.com%2F2025%2F10%2F19%2Fmcps-are-not-like-other-apis%2F">This</a> blog post covers a great technique to design MCP servers.</p>

<h3 id="3-skills">3. Skills</h3>

<p>In essence <a href="iframe.php?url=https%3A%2F%2Fagentskills.io%2Fhome">skills</a> are just a formal way of writing instructions to a file and loading them as needed. This is crucial.</p>

<p>If your agent needs to do multiple things and do them well, putting everything in it’s system prompt is not going to help nor is making one subagent (discussed later) for every scenario. The instructions may be contradictory based on the existing context or useless if those scenarios are never encountered.
You can put these specific instructions for specific occasions into a different files and expose them as skills. Now, the agent should be intelligent enough to load these as needed and prevent context overload and confusion!</p>

<p>For the <code class="language-plaintext highlighter-rouge">ts-cli</code> tool we mentioned earlier, we know some specific agents in our multi-agent system needs to use it often, so we just expose it’s common usage techniques to it using a skill. So far, it has been greatly useful.</p>

<h3 id="4-purging-context">4. Purging context</h3>

<p>It is very hard to know what part of the context window is actually useful and what is irrelevant.</p>

<p>One agreeable answer to this is that we can purge the outputs of the tool calls before, lets say, the last 30 tool calls.</p>

<p>The usefulness of this completely depends on the work your agent is doing. If it spends majority of it’s time finding code snippets, it wouldn’t hurt much because the calls will stay which contain filenames, etc. only the outputs will be purged.
You could also purge the the tool calls themselves, however, in that case, the agent will no longer know what files it has already operated on for example. Essentially it will lose track. Not what we want.</p>

<p>The other type of information that should not be purged is errors. This is hard to implement in practice because unless the system you’re working on is deterministic it is very hard to know what is an error and what is not.
For a Bash output you could look at the exit code (hypothetically) and employ such techniques. Personally we prefer not minding this too much.</p>

<p>However you can see some improvement if you can do this correctly as shown <a href="iframe.php?url=https%3A%2F%2Ffactory.ai%2Fnews%2Fevaluating-compression">here</a> by factoryai research.</p>

<h3 id="5-compaction">5. Compaction</h3>

<p>Even with all these optimizations, you will have to implement some form of compaction. Compaction or summarisation is when the whole context window is taken and summarized at a certain threshold (n tokens used, n% of context usage, etc.).</p>

<p>The context window will be rewritten as the summary. Tons of information is completely lost never to be recovered ever again!
If not done correctly compaction is pure doom for the agent. However, fear not. There are great techniques to battle this doom.</p>

<h4 id="5a-dual-pass-summarisation">5A. Dual-Pass Summarisation</h4>

<p>At a certain threshold, the whole context window is sent to an instance of the model with a summary prompt and then the output of the model is used to replace the whole context with the summary.</p>

<p>This is terrible as you can see. This is how we used to do it too and it would kill our agent’s ability to do useful work instantly.</p>

<p>One bottleneck here that can be optimized is the summary prompt itself.
In an ideal scenario you’d like it to be general enough to summarize any action it has done without losing information. For that, the summary prompt will also be general but that makes it vague and unspecific.</p>

<p>We can make it more specific and thus more useful by first using the conversation history to generate an ideal summary prompt and then using that prompt to do the summarisation.
Summarization triggered -&gt; Pass the conversation history to the model with a prompt “Based on this history, generate a prompt to generate a summary…” (upto you) -&gt; Use the summary prompt to do the summarization -&gt; Replace the conversation history with the summary</p>

<p>There are gains to be achieved here and they can be noticeable if done well. However, one could argue that if the model instance is just prompted well, it can achieve similar or same performance.
There is unfortunately no data on this so the usefulness of this method is on you to decide.</p>

<h4 id="5b-just-in-time-conversation-history">5B. Just-in-time conversation history</h4>

<p>However good a summary is, it is still a summary. Information is still lost. It is a lossy form of compression. Again, this is not all doom as you shall see.</p>

<p>We can write the existing conversation history to a file and tell the agent to read it as it needed. If the summarisation job was well done, this would massively help the agent if the agent is prompted well about it or given a skill to learn this.
This is employed in our agentic systems and it seems to work well. This is originally from <a href="iframe.php?url=https%3A%2F%2Fcursor.com%2Fblog%2Fdynamic-context-discovery">cursor’s research</a>.</p>

<p><img src="iframe.php?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FG-xeQLnasAAQIMa%3Fformat%3Djpg%26amp%3Bname%3Dmedium" alt="Just-in-time conversation history" style="height:400px;width:auto;" /></p>

<h3 id="6-subagents">6. Subagents</h3>

<p>Subagents are just agents which are specialized for some task and which can be called like tools by the primary agent. Having subagents allows the primary agent to offload tasks which require a specific type of expertise (much specific than what you could put in a skill) and directly get the result.
From the primary agent’s perspective, it is something like looking up the solutions on the back of a Math book as soon as it encounters a hard problem. The subagents does all the hardwork and prevents the context pollution of the primary agent.</p>

<p>You can have a subagent to explore the codebase, another to write tests, another to write documentation, etc. in an end-to-end development agentic workflow.</p>

<h2 id="conclusion">Conclusion</h2>

<p>This is it, these were all the techniques that we have learned around context engineering. We’re sure we may have missed a few (please share them with us so we can cover them later) but these were the ones we had first hand experience with so we prioritized writing about them.</p>

<p>We wish to continue this series with more techniques!</p>

<h2 id="references">References</h2>

<ul>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.philschmid.de%2Fcontext-engineering-part-2">https://www.philschmid.de/context-engineering-part-2</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Frlancemartin.github.io%2F2025%2F10%2F15%2Fmanus%2F">https://rlancemartin.github.io/2025/10/15/manus/</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fblog.langchain.com%2Fhow-agents-can-use-filesystems-for-context-engineering%2F">https://blog.langchain.com/how-agents-can-use-filesystems-for-context-engineering/</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fcursor.com%2Fblog%2Fsemsearch%3Fref%3Dblog.langchain.com">https://cursor.com/blog/semsearch?ref=blog.langchain.com</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.anthropic.com%2Fengineering%2Fwriting-tools-for-agents">https://www.anthropic.com/engineering/writing-tools-for-agents</a></li>
</ul>]]></content><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><category term="Agents" /><category term="Agent Engineering" /><summary type="html"><![CDATA[The influx of tools and techniques to optimize and improve agentic systems is becoming overwhelming.]]></summary></entry><entry><title type="html">A deep dive into Processes, Threads, Fibers and Jobs on Windows.</title><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FProcesses-threads-jobs-fibers%2F" rel="alternate" type="text/html" title="A deep dive into Processes, Threads, Fibers and Jobs on Windows." /><published>2022-08-03T05:00:00+00:00</published><updated>2022-08-03T05:00:00+00:00</updated><id>https://de-engineer.github.io/Processes-threads-jobs-fibers</id><content type="html" xml:base="https://de-engineer.github.io/Processes-threads-jobs-fibers/"><![CDATA[<p>Learning how processes and threads work is a crucial part of understanding any Operating System as they are the building block on top of which almost all of the user-mode mechanisms work. Additionally, Windows offers us an elegant API that enables us to interact with them. Unsurprisingly enough, these topics can be a bit complicated to understand since Microsoft does not provide a clear documentation of them and there are not a lot of resources that cover these topics clearly. Windows also provides us the fiber and job APIs which are built on top of the process and thread APIs to allow the developers to manage processes and threads “easily”.</p>

<p>Table of contents:</p>

<ul id="markdown-toc">
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23processes" id="markdown-toc-processes">Processes</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23process-resources" id="markdown-toc-process-resources">Process resources</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23threads" id="markdown-toc-threads">Threads</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23thread-scheduling" id="markdown-toc-thread-scheduling">Thread scheduling</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23thread-resources" id="markdown-toc-thread-resources">Thread resources</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23using-threads" id="markdown-toc-using-threads">Using Threads</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23fibers" id="markdown-toc-fibers">Fibers</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23using-fibers" id="markdown-toc-using-fibers">Using Fibers</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23createprocess-internals" id="markdown-toc-createprocess-internals">CreateProcess internals</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23arguments" id="markdown-toc-arguments">Arguments</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23classification-of-processes" id="markdown-toc-classification-of-processes">Classification of Processes</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23protected-processes" id="markdown-toc-protected-processes">Protected Processes</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23protected-processes-light-ppl" id="markdown-toc-protected-processes-light-ppl">Protected Processes Light (PPL)</a></li>
        </ul>
      </li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23minimal-processes" id="markdown-toc-minimal-processes">Minimal Processes</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23pico-processes" id="markdown-toc-pico-processes">Pico Processes</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23windows-subsystem-for-linux" id="markdown-toc-windows-subsystem-for-linux">Windows Subsystem for Linux</a></li>
        </ul>
      </li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23trustlets-secure-processes" id="markdown-toc-trustlets-secure-processes">Trustlets (Secure Processes)</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23jobs" id="markdown-toc-jobs">Jobs</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23job-limits" id="markdown-toc-job-limits">Job limits</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23api-functions-for-working-with-jobs" id="markdown-toc-api-functions-for-working-with-jobs">API functions for working with Jobs</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23using-jobs" id="markdown-toc-using-jobs">Using Jobs</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23code-examples" id="markdown-toc-code-examples">Code Examples</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23creating-a-process" id="markdown-toc-creating-a-process">Creating a Process</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23creating-a-thread" id="markdown-toc-creating-a-thread">Creating a Thread</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23creating-a-fiber" id="markdown-toc-creating-a-fiber">Creating a Fiber</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23creating-a-job-object" id="markdown-toc-creating-a-job-object">Creating a Job Object</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23summary" id="markdown-toc-summary">Summary</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources" id="markdown-toc-resources">Resources</a></li>
</ul>

<h1 id="processes">Processes</h1>
<p>Many people assume that a program and a process are the same. However, a <strong>process</strong> is not same as a <strong>program</strong>. A <strong>program</strong> is simply a file containing code. On the other hand, a <strong>process</strong> is a container of threads and various resources that are required for the threads inside the process to execute.</p>
<h2 id="process-resources">Process resources</h2>
<p>The resources that are required to run a process might differ for each process according to it’s need but these are the fundamental components that every (almost) process has:  <br />
<strong>Process Identifier</strong>: Process identifier (aka PID or process ID) is a unique identifier for each process on the system. While processes with same name can exist on the system, process with same process IDs can not.</p>

<p><strong>Private Virtual Address Space</strong>: A specific amount of virtual addresses that a process can use. This amount is different for different systems. I’ve previously wrote a detailed post about Virtual Memory which can be found <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FVirtual-Address-Translation-and-structure-of-PTE%2F">here</a>.</p>

<p><strong>Executable Code</strong>: This refers to the code that is mapped into the private virtual address space (“stored in process’s memory”) of the process from the program. Processes can and do exist without any executable code for special purposes.</p>

<p><strong>Handle Table</strong>: A Handle table contains all the pointer to the actual objects in the kernel that are being used by the process. The handles returned by the APIs are essentially the indexes inside the handle table. This table can not be accessed from the user-mode, since it is stored in the kernel mode. Another thing to note here is that this handle table only consists of handles for kernel objects and not for any other <em>category</em> of object, i.e. GDI and user.</p>

<p><strong>Access Token</strong>: Each process also has an access token that defines it’s security context which is used by the system to check identity information such as which process belongs to which user, what are the privileges that it has, etc.</p>

<p><strong>Process Environment Block</strong>: PEB is a user-mode per process structure that contains quite a lot of information about a process, such as the arguments provided to this process, if it’s being debugged or not, list of loaded modules, etc.  <br />
This is how the PEB looks like:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">_PEB</span> <span class="p">{</span>
    <span class="mh">0x000</span> <span class="n">BYTE</span> <span class="n">InheritedAddressSpace</span><span class="p">;</span>
    <span class="mh">0x001</span> <span class="n">BYTE</span> <span class="n">ReadImageFileExecOptions</span><span class="p">;</span>
    <span class="mh">0x002</span> <span class="n">BYTE</span> <span class="n">BeingDebugged</span><span class="p">;</span>
    <span class="mh">0x003</span> <span class="n">BYTE</span> <span class="n">SpareBool</span><span class="p">;</span>
    <span class="mh">0x004</span> <span class="kt">void</span><span class="o">*</span> <span class="n">Mutant</span><span class="p">;</span>
    <span class="mh">0x008</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ImageBaseAddress</span><span class="p">;</span>
    <span class="mh">0x00c</span> <span class="n">_PEB_LDR_DATA</span><span class="o">*</span> <span class="n">Ldr</span><span class="p">;</span>
    <span class="mh">0x010</span> <span class="n">_RTL_USER_PROCESS_PARAMETERS</span><span class="o">*</span> <span class="n">ProcessParameters</span><span class="p">;</span>
    <span class="mh">0x014</span> <span class="kt">void</span><span class="o">*</span> <span class="n">SubSystemData</span><span class="p">;</span>
    <span class="mh">0x018</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ProcessHeap</span><span class="p">;</span>
    <span class="mh">0x01c</span> <span class="n">_RTL_CRITICAL_SECTION</span><span class="o">*</span> <span class="n">FastPebLock</span><span class="p">;</span>
    <span class="mh">0x020</span> <span class="kt">void</span><span class="o">*</span> <span class="n">FastPebLockRoutine</span><span class="p">;</span>
    <span class="mh">0x024</span> <span class="kt">void</span><span class="o">*</span> <span class="n">FastPebUnlockRoutine</span><span class="p">;</span>
    <span class="mh">0x028</span> <span class="n">DWORD</span> <span class="n">EnvironmentUpdateCount</span><span class="p">;</span>
    <span class="mh">0x02c</span> <span class="kt">void</span><span class="o">*</span> <span class="n">KernelCallbackTable</span><span class="p">;</span>
    <span class="mh">0x030</span> <span class="n">DWORD</span> <span class="n">SystemReserved</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
    <span class="mh">0x034</span> <span class="n">DWORD</span> <span class="n">ExecuteOptions</span><span class="o">:</span><span class="mi">2</span><span class="p">;</span> <span class="c1">// bit offset: 34, len=2</span>
    <span class="mh">0x034</span> <span class="n">DWORD</span> <span class="n">SpareBits</span><span class="o">:</span><span class="mi">30</span><span class="p">;</span> <span class="c1">// bit offset: 34, len=30</span>
    <span class="mh">0x038</span> <span class="n">_PEB_FREE_BLOCK</span><span class="o">*</span> <span class="n">FreeList</span><span class="p">;</span>
    <span class="mh">0x03c</span> <span class="n">DWORD</span> <span class="n">TlsExpansionCounter</span><span class="p">;</span>
    <span class="mh">0x040</span> <span class="kt">void</span><span class="o">*</span> <span class="n">TlsBitmap</span><span class="p">;</span>
    <span class="mh">0x044</span> <span class="n">DWORD</span> <span class="n">TlsBitmapBits</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span>
    <span class="mh">0x04c</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ReadOnlySharedMemoryBase</span><span class="p">;</span>
    <span class="mh">0x050</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ReadOnlySharedMemoryHeap</span><span class="p">;</span>
    <span class="mh">0x054</span> <span class="kt">void</span><span class="o">**</span> <span class="n">ReadOnlyStaticServerData</span><span class="p">;</span>
    <span class="mh">0x058</span> <span class="kt">void</span><span class="o">*</span> <span class="n">AnsiCodePageData</span><span class="p">;</span>
    <span class="mh">0x05c</span> <span class="kt">void</span><span class="o">*</span> <span class="n">OemCodePageData</span><span class="p">;</span>
    <span class="mh">0x060</span> <span class="kt">void</span><span class="o">*</span> <span class="n">UnicodeCaseTableData</span><span class="p">;</span>
    <span class="mh">0x064</span> <span class="n">DWORD</span> <span class="n">NumberOfProcessors</span><span class="p">;</span>
    <span class="mh">0x068</span> <span class="n">DWORD</span> <span class="n">NtGlobalFlag</span><span class="p">;</span>
    <span class="mh">0x070</span> <span class="n">_LARGE_INTEGER</span> <span class="n">CriticalSectionTimeout</span><span class="p">;</span>
    <span class="mh">0x078</span> <span class="n">DWORD</span> <span class="n">HeapSegmentReserve</span><span class="p">;</span>
    <span class="mh">0x07c</span> <span class="n">DWORD</span> <span class="n">HeapSegmentCommit</span><span class="p">;</span>
    <span class="mh">0x080</span> <span class="n">DWORD</span> <span class="n">HeapDeCommitTotalFreeThreshold</span><span class="p">;</span>
    <span class="mh">0x084</span> <span class="n">DWORD</span> <span class="n">HeapDeCommitFreeBlockThreshold</span><span class="p">;</span>
    <span class="mh">0x088</span> <span class="n">DWORD</span> <span class="n">NumberOfHeaps</span><span class="p">;</span>
    <span class="mh">0x08c</span> <span class="n">DWORD</span> <span class="n">MaximumNumberOfHeaps</span><span class="p">;</span>
    <span class="mh">0x090</span> <span class="kt">void</span><span class="o">**</span> <span class="n">ProcessHeaps</span><span class="p">;</span>
    <span class="mh">0x094</span> <span class="kt">void</span><span class="o">*</span> <span class="n">GdiSharedHandleTable</span><span class="p">;</span>
    <span class="mh">0x098</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ProcessStarterHelper</span><span class="p">;</span>
    <span class="mh">0x09c</span> <span class="n">DWORD</span> <span class="n">GdiDCAttributeList</span><span class="p">;</span>
    <span class="mh">0x0a0</span> <span class="kt">void</span><span class="o">*</span> <span class="n">LoaderLock</span><span class="p">;</span>
    <span class="mh">0x0a4</span> <span class="n">DWORD</span> <span class="n">OSMajorVersion</span><span class="p">;</span>
    <span class="mh">0x0a8</span> <span class="n">DWORD</span> <span class="n">OSMinorVersion</span><span class="p">;</span>
    <span class="mh">0x0ac</span> <span class="n">WORD</span> <span class="n">OSBuildNumber</span><span class="p">;</span>
    <span class="mh">0x0ae</span> <span class="n">WORD</span> <span class="n">OSCSDVersion</span><span class="p">;</span>
    <span class="mh">0x0b0</span> <span class="n">DWORD</span> <span class="n">OSPlatformId</span><span class="p">;</span>
    <span class="mh">0x0b4</span> <span class="n">DWORD</span> <span class="n">ImageSubsystem</span><span class="p">;</span>
    <span class="mh">0x0b8</span> <span class="n">DWORD</span> <span class="n">ImageSubsystemMajorVersion</span><span class="p">;</span>
    <span class="mh">0x0bc</span> <span class="n">DWORD</span> <span class="n">ImageSubsystemMinorVersion</span><span class="p">;</span>
    <span class="mh">0x0c0</span> <span class="n">DWORD</span> <span class="n">ImageProcessAffinityMask</span><span class="p">;</span>
    <span class="mh">0x0c4</span> <span class="n">DWORD</span> <span class="n">GdiHandleBuffer</span><span class="p">[</span><span class="mi">34</span><span class="p">];</span>
    <span class="mh">0x14c</span> <span class="kt">void</span> <span class="p">(</span><span class="o">*</span><span class="n">PostProcessInitRoutine</span><span class="p">)();</span>
    <span class="mh">0x150</span> <span class="kt">void</span><span class="o">*</span> <span class="n">TlsExpansionBitmap</span><span class="p">;</span>
    <span class="mh">0x154</span> <span class="n">DWORD</span> <span class="n">TlsExpansionBitmapBits</span><span class="p">[</span><span class="mi">32</span><span class="p">];</span>
    <span class="mh">0x1d4</span> <span class="n">DWORD</span> <span class="n">SessionId</span><span class="p">;</span>
    <span class="mh">0x1d8</span> <span class="n">_ULARGE_INTEGER</span> <span class="n">AppCompatFlags</span><span class="p">;</span>
    <span class="mh">0x1e0</span> <span class="n">_ULARGE_INTEGER</span> <span class="n">AppCompatFlagsUser</span><span class="p">;</span>
    <span class="mh">0x1e8</span> <span class="kt">void</span><span class="o">*</span> <span class="n">pShimData</span><span class="p">;</span>
    <span class="mh">0x1ec</span> <span class="kt">void</span><span class="o">*</span> <span class="n">AppCompatInfo</span><span class="p">;</span>
    <span class="mh">0x1f0</span> <span class="n">_UNICODE_STRING</span> <span class="n">CSDVersion</span><span class="p">;</span>
    <span class="mh">0x1f8</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ActivationContextData</span><span class="p">;</span>
    <span class="mh">0x1fc</span> <span class="kt">void</span><span class="o">*</span> <span class="n">ProcessAssemblyStorageMap</span><span class="p">;</span>
    <span class="mh">0x200</span> <span class="kt">void</span><span class="o">*</span> <span class="n">SystemDefaultActivationContextData</span><span class="p">;</span>
    <span class="mh">0x204</span> <span class="kt">void</span><span class="o">*</span> <span class="n">SystemAssemblyStorageMap</span><span class="p">;</span>
    <span class="mh">0x208</span> <span class="n">DWORD</span> <span class="n">MinimumStackCommit</span><span class="p">;</span>
<span class="p">);</span>
</code></pre></div></div>
<p><strong>Thread</strong>: Thread is the entity inside a process that executes code. Every process starts with at least one thread of execution, this thread is called the primary thread. A process without threads can exist, but again, it’s mostly of times it’s of no use since it is not running any code.</p>

<p><strong>EPROCESS structure</strong>: The <code class="language-plaintext highlighter-rouge">EPROCESS</code> (Executive Process) data structure is the kernel’s representation of the process object. The structure is huge and it contains every possible bit of information related to a process, such as pointers to other data structure, values of different attributes, etc. This structure is not documented by Microsoft.  <br />
The structure is very big in size so I’m not including it but it can be found <a href="iframe.php?url=https%3A%2F%2Fgist.github.com%2FHACKE-RC%2Fac54ecc7215290f649cb7bccf122795b">here</a></p>

<p><strong>KPROCESS structure</strong>: One of the most interesting structure inside the <code class="language-plaintext highlighter-rouge">EPROCESS</code> data structure is the <code class="language-plaintext highlighter-rouge">KPROCESS</code> (Kernel Process) data structure. This data structure also contains a lot of information about the process, such as pointer to process’s page directory, how much time the threads of the process has consumed in the user and kernel-mode, etc. Just like it <code class="language-plaintext highlighter-rouge">EPROCESS</code>, this structure is also not documented.  <br />
The structure looks like this:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">_KPROCESS</span> <span class="p">{</span>
  <span class="k">struct</span> <span class="n">_DISPATCHER_HEADER</span> <span class="n">Header</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_LIST_ENTRY</span> <span class="n">ProfileListHead</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">DirectoryTableBase</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">Asid</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_LIST_ENTRY</span> <span class="n">ThreadListHead</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">ProcessLock</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">Spare0</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">DeepFreezeStartTime</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_KAFFINITY_EX</span> <span class="n">Affinity</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_LIST_ENTRY</span> <span class="n">ReadyListHead</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_SINGLE_LIST_ENTRY</span> <span class="n">SwapListEntry</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_KAFFINITY_EX</span> <span class="n">ActiveProcessors</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">AutoAlignment</span> <span class="o">:</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">DisableBoost</span> <span class="o">:</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">DisableQuantum</span> <span class="o">:</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">DeepFreeze</span> <span class="o">:</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">TimerVirtualization</span> <span class="o">:</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">CheckStackExtents</span> <span class="o">:</span> <span class="mi">1</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">SpareFlags0</span> <span class="o">:</span> <span class="mi">2</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">ActiveGroupsMask</span> <span class="o">:</span> <span class="mi">20</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">ReservedFlags</span> <span class="o">:</span> <span class="mi">4</span><span class="p">;</span>
  <span class="kt">long</span> <span class="n">ProcessFlags</span><span class="p">;</span>
  <span class="kt">char</span> <span class="n">BasePriority</span><span class="p">;</span>
  <span class="kt">char</span> <span class="n">QuantumReset</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">Visited</span><span class="p">;</span>
  <span class="k">union</span> <span class="n">_KEXECUTE_OPTIONS</span> <span class="n">Flags</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">ThreadSeed</span><span class="p">[</span><span class="mi">20</span><span class="p">];</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">IdealNode</span><span class="p">[</span><span class="mi">20</span><span class="p">];</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">IdealGlobalNode</span><span class="p">;</span>
  <span class="k">union</span> <span class="n">_KSTACK_COUNT</span> <span class="n">StackCount</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_LIST_ENTRY</span> <span class="n">ProcessListEntry</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">CycleTime</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">ContextSwitches</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">_KSCHEDULING_GROUP</span> <span class="o">*</span><span class="n">SchedulingGroup</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">FreezeCount</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">KernelTime</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">long</span> <span class="n">UserTime</span><span class="p">;</span>
  <span class="kt">void</span> <span class="o">*</span><span class="n">InstrumentationCallback</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>This diagram shows the components of a process:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2FProcess_structure.png" width="500px" height="600px" class="align-center" /></p>

<h1 id="threads">Threads</h1>
<p>Threads are the actual entities inside a process that are running code on the CPU. Threads can execute any part of the code. A process provides all the resources that threads require to complete their task. Without threads, a process can’t run any code. A process can have multiple threads and such processes are called multi-threaded processes.</p>

<h2 id="thread-scheduling">Thread scheduling</h2>
<p>When there are multiple threads on the system, the scheduler switches between different threads and creates an illusion that all the threads running in parallel. While what’s really happening is that the scheduler is switching between different threads so quickly that it appears that the threads are running in parallel.<br />
The amount of time for which a thread can run on a CPU before it switches is called the thread’s quantum. This quantum is a value that is set by the scheduler. This is usually set to a value that is a multiple of the processor’s clock speed.<br />
Windows uses priority based thread scheduling model where the scheduler uses the thread’s priority to determine which thread should run next. The priority of a thread is a value that is set by the thread’s creator or by the system.<br />
Because this system is quite complex, I will not go over it in detail here.</p>

<h2 id="thread-resources">Thread resources</h2>
<p>While a process provides a fair amount of resources for threads to run, there are still a few things that threads need in order to execute, these include:</p>

<p><strong>Context</strong>: Every thread has a context which is a user-mode per thread data structure (managed by kernel) that contains the state of all the registers from the time the thread was last executed on the CPU. This data structure is very important because there can’t be multiple threads running on a CPU, so Windows switches between different threads after a few moments and each time it switches a thread, it stores the current CPU registers’ state in the context. This context is loaded again into as the values of the registers when the thread resumes it’s execution on the CPU. Since this data structure stores information related to registers, it’s processor-specific.  <br />
This is the how the data structure looks like for x64 machines:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="n">_CONTEXT</span> <span class="p">{</span>
  <span class="n">DWORD64</span> <span class="n">P1Home</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">P2Home</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">P3Home</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">P4Home</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">P5Home</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">P6Home</span><span class="p">;</span>
  <span class="n">DWORD</span>   <span class="n">ContextFlags</span><span class="p">;</span>
  <span class="n">DWORD</span>   <span class="n">MxCsr</span><span class="p">;</span>
  <span class="n">WORD</span>    <span class="n">SegCs</span><span class="p">;</span>
  <span class="n">WORD</span>    <span class="n">SegDs</span><span class="p">;</span>
  <span class="n">WORD</span>    <span class="n">SegEs</span><span class="p">;</span>
  <span class="n">WORD</span>    <span class="n">SegFs</span><span class="p">;</span>
  <span class="n">WORD</span>    <span class="n">SegGs</span><span class="p">;</span>
  <span class="n">WORD</span>    <span class="n">SegSs</span><span class="p">;</span>
  <span class="n">DWORD</span>   <span class="n">EFlags</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Dr0</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Dr1</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Dr2</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Dr3</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Dr6</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Dr7</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rax</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rcx</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rdx</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rbx</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rsp</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rbp</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rsi</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rdi</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R8</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R9</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R10</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R11</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R12</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R13</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R14</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">R15</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">Rip</span><span class="p">;</span>
  <span class="k">union</span> <span class="p">{</span>
    <span class="n">XMM_SAVE_AREA32</span> <span class="n">FltSave</span><span class="p">;</span>
    <span class="n">NEON128</span>         <span class="n">Q</span><span class="p">[</span><span class="mi">16</span><span class="p">];</span>
    <span class="n">ULONGLONG</span>       <span class="n">D</span><span class="p">[</span><span class="mi">32</span><span class="p">];</span>
    <span class="k">struct</span> <span class="p">{</span>
      <span class="n">M128A</span> <span class="n">Header</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span>
      <span class="n">M128A</span> <span class="n">Legacy</span><span class="p">[</span><span class="mi">8</span><span class="p">];</span>
      <span class="n">M128A</span> <span class="n">Xmm0</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm1</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm2</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm3</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm4</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm5</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm6</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm7</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm8</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm9</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm10</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm11</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm12</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm13</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm14</span><span class="p">;</span>
      <span class="n">M128A</span> <span class="n">Xmm15</span><span class="p">;</span>
    <span class="p">}</span> <span class="n">DUMMYSTRUCTNAME</span><span class="p">;</span>
    <span class="n">DWORD</span>           <span class="n">S</span><span class="p">[</span><span class="mi">32</span><span class="p">];</span>
  <span class="p">}</span> <span class="n">DUMMYUNIONNAME</span><span class="p">;</span>
  <span class="n">M128A</span>   <span class="n">VectorRegister</span><span class="p">[</span><span class="mi">26</span><span class="p">];</span>
  <span class="n">DWORD64</span> <span class="n">VectorControl</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">DebugControl</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">LastBranchToRip</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">LastBranchFromRip</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">LastExceptionToRip</span><span class="p">;</span>
  <span class="n">DWORD64</span> <span class="n">LastExceptionFromRip</span><span class="p">;</span>
<span class="p">}</span> <span class="n">CONTEXT</span><span class="p">,</span> <span class="o">*</span><span class="n">PCONTEXT</span><span class="p">;</span>
</code></pre></div></div>

<p><strong>Two stacks</strong>: Every thread has two stacks, a user-mode stack and a kernel-mode stack. The user-mode stack is used for normal purposes, such as for storing the values of variables. Unsurprisingly, the kernel stack is not accessible from the user-mode and it’s used as security mechanism.  <br />
When a threads calls a syscall, all of the arguments provided to that syscall are copied from the thread’s user-mode stack to it’s kernel-mode stack. It is done this way because after a thread uses a syscall, the CPU switches to the kernel mode and then the kernel-mode code validates those arguments to see if all the pointers, structures, etc that are passed are valid or not and since this stack is not accessible from the user-mode, a thread can not manipulate the arguments after they have been validated and this way, having two stacks works as a strong security measure.</p>

<p><strong>Thread Local Storage</strong>: The thread local storage is a data structure that is used to store data that is specific to each thread. This data is stored in the thread’s context and is not shared between threads.</p>

<p><strong>Thread ID</strong>: Just like every process has a unique identifier, every thread also has a unique identifier called a thread ID (TID).</p>

<p><strong>Thread Environment Block</strong>: Like processes, threads also have most of their information stored in a data structure called the Thread Environment Block (TEB). This structure contains information such as pointer to the TLS, the <code class="language-plaintext highlighter-rouge">LastErrorValue</code> (this has to be this way because if two threads called <code class="language-plaintext highlighter-rouge">GetLastError</code> and one thread gets the <code class="language-plaintext highlighter-rouge">LastErrorValue</code> of some other thread then it can lead to total chaos), pointer to PEB, etc. TEB is also not documented by Microsoft.  <br />
This structure can be found <a href="iframe.php?url=https%3A%2F%2Fgist.github.com%2FHACKE-RC%2F687fdae74f80a83f32e24a9b593106a8">here</a></p>

<p><strong>Affinity</strong>: Setting affinity for a thread forces Windows to run a thread only on a specific CPU. For example, let’s say your machine has for CPU and you set the affinity of process <code class="language-plaintext highlighter-rouge">linux.exe</code> to CPU 3 then that thread will only run on CPU 3 until it finishes execution or it’s affinity is changed.</p>

<p><strong>ETHREAD structure</strong>: The <code class="language-plaintext highlighter-rouge">ETHREAD</code> structure (Executive Thread) is the kernel representation of the thread object. Similar to <code class="language-plaintext highlighter-rouge">EPROCESS</code>, this structure also contains every possible bit of information about a thread, such as a pointer to the PEB, LastErrorValue, if this thread is the initial thread (main thread) of the process or not, etc. This structure is also not documented by Microsoft.  <br />
This structure can be found <a href="iframe.php?url=https%3A%2F%2Fgist.github.com%2FHACKE-RC%2F25cceb6d5eded8c447381f2b9eda0068">here</a></p>

<p><strong>KTHREAD structure</strong>: The <code class="language-plaintext highlighter-rouge">KTHREAD</code> data structure (Kernel Thread) is also one of the important data structure inside <code class="language-plaintext highlighter-rouge">ETHREAD</code> data structure. It includes information such as the pointer to the kernel stack, a lot of information about it’s scheduling (when and for how long this thread will run on the CPU), pointer to TEB, how much time the thread has spent in the user-mode, etc. This structure is also not documented by Microsoft.  <br />
This structure can be found <a href="iframe.php?url=https%3A%2F%2Fgist.github.com%2FHACKE-RC%2F7d5f031abf50cc9cfcbeb8dc0a5f3619">here</a></p>

<p>This diagram shows the components of a process:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2FThread-Components.png" width="500px" height="600px" class="align-center" /></p>

<h2 id="using-threads">Using Threads</h2>
<p>Using threads is very simple. We just need to create a thread using the <code class="language-plaintext highlighter-rouge">CreateThread</code> function. The thread will start executing at the address of the specified function.<br />
The function that we want to run in the thread is called the thread’s entry point. The entry point is the function that is called when the thread is created.</p>

<p>Here’s the signature of the <code class="language-plaintext highlighter-rouge">CreateThread</code> function:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">HANDLE</span> <span class="nf">CreateThread</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span>  <span class="n">LPSECURITY_ATTRIBUTES</span>   <span class="n">lpThreadAttributes</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span>            <span class="n">SIZE_T</span>                  <span class="n">dwStackSize</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span>            <span class="n">LPTHREAD_START_ROUTINE</span>  <span class="n">lpStartAddress</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span>  <span class="n">__drv_aliasesMem</span> <span class="n">LPVOID</span> <span class="n">lpParameter</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span>            <span class="n">DWORD</span>                   <span class="n">dwCreationFlags</span><span class="p">,</span>
  <span class="p">[</span><span class="n">out</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span> <span class="n">LPDWORD</span>                 <span class="n">lpThreadId</span>
<span class="p">);</span>
</code></pre></div></div>
<p>The first parameter is the security attributes. This is a pointer to a <code class="language-plaintext highlighter-rouge">SECURITY_ATTRIBUTES</code> structure that contains information about the security of the thread. This is optional and can be <code class="language-plaintext highlighter-rouge">NULL</code> for default security.<br />
The second parameter is the stack size. This is the size of the stack that the thread will use. This is optional and can be <code class="language-plaintext highlighter-rouge">0</code> for default stack size.<br />
The third parameter is the address of the function that will be executed in the thread. This is the entry point of the thread.<br />
The fourth parameter is the parameter that will be passed to the thread. This is optional and can be <code class="language-plaintext highlighter-rouge">NULL</code> for no parameter.<br />
The fifth parameter is the creation flags. This is a set of flags that determines how the thread will be created. This is optional and can be <code class="language-plaintext highlighter-rouge">0</code> if we want the thread to directly execute after being created.<br />
The sixth parameter is the thread ID. This is a pointer to a variable that will receive thread ID after it’s created. This is optional and can be <code class="language-plaintext highlighter-rouge">NULL</code> if we do not want to store the thread’s ID.</p>

<h2 id="fibers">Fibers</h2>
<p>Fibers are unit of execution that allow us to manually schedule (define our own scheduling algorithm) them rather than being automatically scheduled by the scheduler. Fibers run in the context of the threads that created them. Every thread can have multiple fibers and a thread can run one fiber at a time (we decide which). Fibers are often called lightweight threads.<br />
Fibers are invisible to the kernel as they are implemented in the user-mode in Kernel32.dll.</p>

<h3 id="using-fibers">Using Fibers</h3>
<p>The first step when using fiber is to convert our own thread into a fiber. This is done by calling the <code class="language-plaintext highlighter-rouge">ConvertThreadToFiber</code> function. This is the signature for the function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">LPVOID</span> <span class="nf">ConvertThreadToFiber</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span> <span class="n">LPVOID</span> <span class="n">lpParameter</span>
<span class="p">);</span>
</code></pre></div></div>

<p>This function returns the memory address of the fiber’s context that was created. This address is useful later when performing operations on the fiber. The fiber’s context is similar to than that of a thread but it has a few more elements than just registers, these include:</p>
<ul>
  <li>The value of <code class="language-plaintext highlighter-rouge">lpParameter</code> that was passed to <code class="language-plaintext highlighter-rouge">ConvertThreadToFiber</code>.</li>
  <li>The top and bottom memory addresses of the fiber’s stack.<br />
and more.</li>
</ul>

<p>After this function is called our thread gets converted into a fiber and it starts running on our thread. This fiber may exit either when it’s done executing or when it calls <code class="language-plaintext highlighter-rouge">ExitThread</code> (in this case, the thread and fiber both get terminated).</p>

<p>Now, to create a fiber, we need to call the <code class="language-plaintext highlighter-rouge">CreateFiber</code> function. This is the signature for the function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">LPVOID</span> <span class="nf">CreateFiber</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span>           <span class="n">SIZE_T</span>                <span class="n">dwStackSize</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span>           <span class="n">LPFIBER_START_ROUTINE</span> <span class="n">lpStartAddress</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span> <span class="n">LPVOID</span>                <span class="n">lpParameter</span>
<span class="p">);</span>
</code></pre></div></div>

<p>The first argument is used to specify the size of the fiber’s stack, generally, 0 is specified, which uses the default value and creates a stack that can scale grow up to 1 MB. The second argument is the address of the function that will be executed when the fiber is scheduled. The third argument is the parameter that will be passed to the function that will be executed.<br />
This function also returns the memory address of the fiber’s context that was created with this context having one additional element: the address of the function that will be executed.<br />
Remember that calling this function only creates the fiber and doesn’t start it. To start the fiber, we need to call the <code class="language-plaintext highlighter-rouge">SwitchToFiber</code> function. This is the signature for the function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">SwitchToFiber</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">LPVOID</span> <span class="n">lpFiber</span>
<span class="p">);</span>
</code></pre></div></div>
<p>This function takes only one argument, the address of the fiber’s context that was previously returned by <code class="language-plaintext highlighter-rouge">CreateFiber</code>. This function actuall starts the execution of the fiber.</p>

<p>To destroy a fiber, we need to call the <code class="language-plaintext highlighter-rouge">DeleteFiber</code> function. This is the signature for the function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">DeleteFiber</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">LPVOID</span> <span class="n">lpFiber</span>
<span class="p">);</span>
</code></pre></div></div>
<p>It only takes one argument, the address of the fiber’s context that we want to delete.</p>

<h1 id="createprocess-internals">CreateProcess internals</h1>
<p>Usually, when a thread wants to create another process, it calls the Windows API function <code class="language-plaintext highlighter-rouge">CreateProcess</code> and specifies the parameters accordingly to create a process with required attributes. This function is takes a lot of arguments and is quite flexible and can be used in almost all cases.<br />
However, sometimes the capabilities of this functions are not enough so other functions (sometimes just a wrapper of this function) are used, here are some of them:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">CreateProcessAsUser</code> allows you to create a process on the behalf another user by allowing you to specify the handle to that user’s primary token.</li>
  <li><code class="language-plaintext highlighter-rouge">CreateProcessWithTokenW</code> gives you the same capabilities as the previous function but this one just requires a few different privileges.</li>
  <li><code class="language-plaintext highlighter-rouge">CreateProcessWithLogonW</code> allows you to provide the credentials of the user in whose context you want to create a process.</li>
  <li><code class="language-plaintext highlighter-rouge">ShellExecute</code> is a very unique function. All the previous functions that we talked about work with any valid Portable Executable (PE) file and they do not care about the file extension of the file that you specified, i.e, you can rename the original <code class="language-plaintext highlighter-rouge">notepad.exe</code> to <code class="language-plaintext highlighter-rouge">notepad.txt</code> and give it to any of those functions and they would still create a process from it.<br />
However, the <code class="language-plaintext highlighter-rouge">ShellExecute</code> and <code class="language-plaintext highlighter-rouge">ShellExecuteEx</code> are a bit different. These functions accept any file format and then they look inside the <code class="language-plaintext highlighter-rouge">HKLM\SOFTWARE\Classes</code> and <code class="language-plaintext highlighter-rouge">HKCU\SOFTWARE\Classes</code> registry keys to find the program which is associated with the file format of the file you gave it as an argument and then they eventually call the <code class="language-plaintext highlighter-rouge">CreateProcess</code> function with the appropriate executable name/path along with the file name appended, for example you can provide this function a txt file and it will launch notepad with the filename as an argument (<code class="language-plaintext highlighter-rouge">notepad.exe filename.txt</code>).</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">CreateProcess</code> and <code class="language-plaintext highlighter-rouge">CreateProcessAsUser</code> both are exported by <code class="language-plaintext highlighter-rouge">Kernel32.dll</code> and both of them eventually call <code class="language-plaintext highlighter-rouge">CreateProcessInternal</code> (also exported by <code class="language-plaintext highlighter-rouge">Kernel32.dll</code>) which also ends up calling the <code class="language-plaintext highlighter-rouge">NtCreateUserProcess</code> function which is exported by <code class="language-plaintext highlighter-rouge">ntdll.dll</code>. <code class="language-plaintext highlighter-rouge">NtCreateUserProcess</code> is the last part of the user-mode code of all user-mode process creation functions, after this function is done with it’s work, it makes a syscall and transforms into kernel mode. Both <code class="language-plaintext highlighter-rouge">CreateProcessInternal</code> and <code class="language-plaintext highlighter-rouge">NtCreateUserProcess</code> are officially undocumented by Microsoft at the time of writing this post.<br />
However, the <code class="language-plaintext highlighter-rouge">CreateProcessWithTokenW</code> and <code class="language-plaintext highlighter-rouge">CreateProcessWithLogonW</code> functions are exported by <code class="language-plaintext highlighter-rouge">Advapi32.dll</code>. Both of these functions make a Remote Procedure Call (RPC) to the Secondary Login Service (<code class="language-plaintext highlighter-rouge">seclogon.dll</code> hosted in <code class="language-plaintext highlighter-rouge">svchost.exe</code>), this service allows processes to be started with different user’s credentials and then Secondary Logon Service executes this call in its <code class="language-plaintext highlighter-rouge">SlrCreateProcessWithLogon</code> function which eventually calls <code class="language-plaintext highlighter-rouge">CreateProcessAsUser</code>.</p>

<h2 id="arguments">Arguments</h2>
<p>The arguments for all the <code class="language-plaintext highlighter-rouge">CreateProcess*</code> functions are almost completely similar with a only a few differences. The explanation of all the <code class="language-plaintext highlighter-rouge">CreateProcess*</code> functions would be tedious to write as well as very boring to read, so here is the brief overview of the description of different arguments:</p>

<ul>
  <li>The first argument for <code class="language-plaintext highlighter-rouge">CreateProcessAsUser</code> and <code class="language-plaintext highlighter-rouge">CreateProcessWithTokenW</code> are the handle to the token under which the process will be started. However, in the case of <code class="language-plaintext highlighter-rouge">CreateProcessWithLogonW</code>, the first arguments include the username, domain and password of the user on whose behalf the process will be started.</li>
  <li>The next <em>important</em> argument <code class="language-plaintext highlighter-rouge">lpApplicationName</code>, which is the full path to the executable to run. This argument can be left <code class="language-plaintext highlighter-rouge">NULL</code> and instead the next argument can be used.</li>
  <li>
    <p>The next argument after <code class="language-plaintext highlighter-rouge">lpApplicationName</code> is <code class="language-plaintext highlighter-rouge">lpCommandLine</code>. This argument doesn’t require us to put the provide the full path of the executable we want create a process of (we can provide it full path but it’s optional), the reason behind this is that when we provide it an executable’s name without a path in this argument, the function searches through several pre-defined paths in an order to find that file’s path. This is the order defined in msdn:<br />
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fexe_search_sequence.png" width="600px" /></p>
  </li>
  <li>The next <em>important</em> arguments are <code class="language-plaintext highlighter-rouge">lpProcessAttributes</code> and <code class="language-plaintext highlighter-rouge">lpThreadAttributes</code>. Both of them take a pointer to <code class="language-plaintext highlighter-rouge">SECURITY_ATTRIBUTES</code> structure and both of them can be <code class="language-plaintext highlighter-rouge">NULL</code>, and when this argument is specified <code class="language-plaintext highlighter-rouge">NULL</code> then the default security attributes are used. we can specify whether we want to make the handle of the process that is about to be created (in <code class="language-plaintext highlighter-rouge">lpProcessAttributes</code>) and it’s primary thread (in <code class="language-plaintext highlighter-rouge">lpProcessAttributes</code>) inheritable by all the other child processes that the caller of <code class="language-plaintext highlighter-rouge">CreateProcess*</code> creates or not in the <code class="language-plaintext highlighter-rouge">bInheritHandle</code> member of <code class="language-plaintext highlighter-rouge">SECURITY_ATTRIBUTES</code>.</li>
  <li>The next <em>important</em> argument is <code class="language-plaintext highlighter-rouge">bInheritHandles</code>. This argument specifies whether we want the process that is about to be created to inherit all the inheritable handles from the handle table of the parent process or not.</li>
  <li>The next <em>important</em> argument is <code class="language-plaintext highlighter-rouge">dwCreationFlags</code>. This argument allow us to specify different flags that affect the creation of the process, such as:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">CREATE_SUSPENDED</code>: The initial thread of the process being created is started in suspended state (paused state, it doesn’t directly run after it’s created). A call to <code class="language-plaintext highlighter-rouge">ResumeThread</code> can be used thereafter to resume the execution of the thread.</li>
      <li><code class="language-plaintext highlighter-rouge">DEBUG_PROCESS</code>: The calling process declares itself as a debugger and creates the process under it’s control.</li>
    </ul>
  </li>
  <li>The next argument is <code class="language-plaintext highlighter-rouge">lpEnvironment</code>. This argument is optional and is used to provide a pointer to the an environment variables’ block. Since it’s optional, we can specify it <code class="language-plaintext highlighter-rouge">NULL</code> and it will inherit it’s environment variables from it’s parent process.</li>
  <li>The next argument is <code class="language-plaintext highlighter-rouge">lpCurrentDirectory</code>. This argument is also optional and is used if we want the process about to be created will have a different current directory than the parent process. If left <code class="language-plaintext highlighter-rouge">NULL</code>, the new process will use the current directory of the parent process.</li>
  <li>The next argument is <code class="language-plaintext highlighter-rouge">lpStartupInfo</code>. This argument is used to specify a pointer to <code class="language-plaintext highlighter-rouge">STARTUPINFO</code> or <code class="language-plaintext highlighter-rouge">STARTUPINFOEX</code> structures. The <code class="language-plaintext highlighter-rouge">STARTUPINFO</code> structure contains some more configuration related for the new process. <code class="language-plaintext highlighter-rouge">STARTUPINFOEX</code> structure has an extra field which is used to specify some more attributes for the new process.</li>
  <li>The last argument is <code class="language-plaintext highlighter-rouge">lpProcessInformation</code>. This argument is used to specify a pointer to <code class="language-plaintext highlighter-rouge">PROCESS_INFORMATION</code> structure. The <code class="language-plaintext highlighter-rouge">CreateProcess*</code> functions returned the information of the new process in this structure, this information includes the process id of the new process, the thread id of the primary thread, a handle to the new process, etc.</li>
</ul>

<h1 id="classification-of-processes">Classification of Processes</h1>
<p>Windows provides some (almost) completely different attributes for processes that require extra security or have a special purpose. These processes are not launched like normal processes and they also have different attributes.</p>

<h2 id="protected-processes">Protected Processes</h2>
<p>The concept of protected processes was initially introduced to imply with Digital Rights Management (DRM) requirements which were imposed by the media industry for protection of content such as HD-DVD media.<br />
Normally, threads of any process which as debug privilege (usually processes started by the administrator account) could read or write data and code into the memory of any process running on the system. This behavior is very useful in a lot of cases. However, this behavior violates the DRM requirements and for this reason, Windows uses protected processes.<br />
These process exist with normal Windows process, but they provide with little to no access to other processes on the system (even the one’s running with administrator privileges).<br />
These processes can be created by any application on the system with whatever rights they have, but for an executable to be able to run as a protected process, it must be signed with a special Windows Media Certificate. This certificate is a digital signature that is used to identify the executable as a protected process.<br />
These process also only load DLLs that are signed with a special certificate and the data of these processes are only accessible to either kernel or other protected processes.<br />
Examples of protected process are:</p>
<ul>
  <li>The Audio Graph Device process (Audiodg.exe) that is used by Windows to decode protected DRM audio content.</li>
  <li>The Media Foundation Protected Media Path (Mfpmp.exe) process used by Windows to decode DRM video content.</li>
  <li>The Windows Error Reporting (WER, Werfaultsecure.exe) for reporting crashes of protected apps. This the protected version of WER is required because the normal WER process executes as a normal process and therefore it can’t access the data inside the crashed protected processes.</li>
  <li>The system process.</li>
</ul>

<h3 id="protected-processes-light-ppl">Protected Processes Light (PPL)</h3>
<p>PPL is the extended version of Protected Processes introduced allow third party processes, such as Antivirus programs to have same privileges as protected processes. However, PPLs comes with a slight difference, i.e., how much protected a PPL will be depends upon it’s signature, which results in some PPLs having more or less protection than others.<br />
Most system processes on Windows are PPL protected, such as <code class="language-plaintext highlighter-rouge">smss.exe</code>, <code class="language-plaintext highlighter-rouge">csrss.exe</code>, <code class="language-plaintext highlighter-rouge">services.exe</code>, etc.</p>

<h2 id="minimal-processes">Minimal Processes</h2>
<p>These are essentially empty processes. These processes have empty user-mode address space, ntdll.dll or other subsystem DLLs are not loaded, no PEB or TEB or any related structure are created, no initial thread is created and no executable image is mapped. There processes are created and managed by the kernel and the kernel provides no way to create such processes from the user-mode since these are not meant to be used by the user, but rather by the system to perform special tasks.<br />
These process can have threads and these threads are called minimal threads. These threads don’t have any Thread Environment Block (TEB) or stack.</p>

<p>An example of this is the memory compression process which stores compressed memory of active processes, this process is used to keep more processes memory without paging them out to the disk (this process is hidden from task manager because since it stores compressed memory, it has a lot of memory usage and average users used to get suspicious about this process). You can view this process in process explorer, if you just sort the processes by their working set (amount of physical memory currently being used), this process should appear on top (it might not, if you have some program eating so much of your ram). This process also has no threads or code.  <br />
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fcompression_image.png" width="600px" /></p>

<h2 id="pico-processes">Pico Processes</h2>
<p>Windows introduced the concept of pico processes based on their research called the Project Drawbridge. These are minimal processes with a supporting driver called the pico provider. This driver can manage almost everything related to the execution of the pico process it’s managing and this property of pico providers allow them it can act like a separate kernel for that process without the process having any sense of the original system it’s running on, however, the management of memory, I/O and thread scheduling is still done by the original Windows kernel.<br />
A pico provider is able to intercept all the operations that of the pico process that require any handling by the kernel, this includes things such as system calls, exceptions, etc and respond accordingly.<br />
Pico processes can have pico threads (minimal threads for pico processes) and also normal threads. The pico threads also have a context which is stored in the <code class="language-plaintext highlighter-rouge">PicoContext</code> member of <code class="language-plaintext highlighter-rouge">ETHREAD</code> structure.</p>

<h3 id="windows-subsystem-for-linux">Windows Subsystem for Linux</h3>
<p>The Windows Subsystem for Linux (WSL) is built on this idea of pico processes. WSL is able to run whole linux system nearly perfectly on Windows without having a single line of code from the linux kernel. This is made possible by the incredible control that pico providers allow.  <br />
The pico providers for WSL are <code class="language-plaintext highlighter-rouge">lxss.sys</code> and <code class="language-plaintext highlighter-rouge">lxcore.sys</code>. These drivers emulate the behavior of the linux kernel by converting all the linux syscalls made from the WSL pico process to NT APIs or by calling specific components that are implemented from scratch.<br />
This implementation of WSL on Windows is a very interesting topic and complicated topic, I might cover it later in some other blog post!</p>

<h2 id="trustlets-secure-processes">Trustlets (Secure Processes)</h2>
<p>Trustlets are another type of processes that provide strong security. Trustlets can not be directly created by the user. They are created by the Windows kernel when a user-mode application requests to create a secure process.<br />
Trustlets use Virtual Trust Levels provided by Hyper-V Hypervisor to isolate themselves in the system. These levels are used to provide the security of the trustlet. The trustlet can only import DLLs that are signed with a certificate that is trusted by the system and other system trusted DLLs such as C/C++ runtime libraries, Kernelbase, Advapi, RPC runtime, CNG base Crypto, and other mathematical libraries that do no require any syscall to work.<br />
The way truslets work is a bit complex as it requires the understanding of how Hypervisors work so I am not covering that here. However, you can read more about them <a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fprocthread%2Fisolated-user-mode--ium--processes">here</a> on msdn.</p>

<h1 id="jobs">Jobs</h1>
<p>Jobs are a Windows mechanism to group and manage processes together and have them share the same security context. This can be used to run a bunch of processes that are related to each other, for example if you want to manage multiple processes that are the part of same application.<br />
Jobs are shareable, securable and nameable. Any change to the job will affect all the processes in the job. Jobs are used to impose limits on a set of processes, for example if you want to limit the number of processes of an application that can be running at the same time.<br />
Once a process is assigned to a job, it can not leave that job. Child processes created by the processes inside a job will also be a part of that job unless <code class="language-plaintext highlighter-rouge">CREATE_BREAKAWAY_FROM_JOB</code> was specified to <code class="language-plaintext highlighter-rouge">CreateProcess</code> and the job itself allows processes to break out from it (a job can deny processes inside it from breaking out of it).</p>

<h2 id="job-limits">Job limits</h2>
<p>Here are few of the limits that we can set in a job:</p>
<ul>
  <li><strong>Max active processes</strong>: This is used to limit the amount of processes that can exist in a job. When this limit is reached, no new processes are allowed to assign to that job and creation of child processes is blocked.</li>
  <li><strong>Processor Affinity</strong>: This is used to limit all the processes inside a job to only on a specific CPU.</li>
  <li><strong>Priority Class</strong>: This is used to set the priority class for all the members of a job. If the thread of any process that is the member of a job that has it’s priority class set tries to increase it’s priority class, it’s request will be ignored and no error will be returned (to <code class="language-plaintext highlighter-rouge">SetThreadPriority</code>).</li>
  <li><strong>Virtual Memory Limit</strong>: This is used to restrict the maximum amount of virtual memory that can be committed by single processes or the entire job.</li>
  <li><strong>Clipboard R/W</strong>: This is used to disallow all the members of a job from accessing or writing to the clipboard.</li>
</ul>

<h2 id="api-functions-for-working-with-jobs">API functions for working with Jobs</h2>
<p>The Windows API provides us all the important functions that are required to manage and work with job objects. Here are few of the important functions:</p>

<ul>
  <li><strong>CreateJobObject</strong>: Used to create a job object. It can also be used to open a job object.</li>
  <li><strong>OpenJobObject</strong>: Used to open an already existing job object.</li>
  <li><strong>AssignProcessToJobObject</strong>: Used to assign a process to a job object.</li>
  <li><strong>SetInformationJobObject</strong>: Used to set limits for the processes inside a job object.</li>
  <li><strong>QueryInformationJobObject</strong>: Used to retrieve information about the a job object.</li>
  <li><strong>TerminateJobObject</strong>: Used to terminate all the processes inside a job object.</li>
  <li><strong>IsProcessInJob</strong>: Used to check if a process is a member of a job object.</li>
</ul>

<h2 id="using-jobs">Using Jobs</h2>
<p>Working with jobs is also quite simple. You can create a job object, assign processes to it and set limits on the processes inside the job. You can also use the API functions to query and set the limits on the processes inside the job.<br />
To create a job object, you can use the <code class="language-plaintext highlighter-rouge">CreateJobObject</code> function. This function returns a handle to the job object. Here is the function signature:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">HANDLE</span> <span class="nf">CreateJobObjectA</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span> <span class="n">LPSECURITY_ATTRIBUTES</span> <span class="n">lpJobAttributes</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">,</span> <span class="n">optional</span><span class="p">]</span> <span class="n">LPCSTR</span>                <span class="n">lpName</span>
<span class="p">);</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">lpJobAttributes</code> parameter is a pointer to a <code class="language-plaintext highlighter-rouge">SECURITY_ATTRIBUTES</code> structure that can be used to set the security attributes for the job object. It can be <code class="language-plaintext highlighter-rouge">NULL</code> if you want the job object to have default security attributes.<br />
The <code class="language-plaintext highlighter-rouge">lpName</code> parameter is a pointer to a string that can be used to name the job object. This parameter can also be <code class="language-plaintext highlighter-rouge">NULL</code> which will result in the job object being unnamed. If the name matches the name of an existing mutex, file-mapping object or waitable object, the function will fail.</p>

<p>After creating an empty job object, you can assign processes to it. To do this, you can use the <code class="language-plaintext highlighter-rouge">AssignProcessToJobObject</code> function. Here is the function signature:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">BOOL</span> <span class="nf">AssignProcessToJobObject</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">HANDLE</span> <span class="n">hJob</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">HANDLE</span> <span class="n">hProcess</span>
<span class="p">);</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">hJob</code> parameter is a handle to the job object.<br />
The <code class="language-plaintext highlighter-rouge">hProcess</code> parameter is a handle to the process that you want to assign to the job object.<br />
To get the handle of the current process, you can use the <code class="language-plaintext highlighter-rouge">GetCurrentProcess</code> function.</p>

<p>To set the limits on the processes inside the job, you can use the <code class="language-plaintext highlighter-rouge">SetInformationJobObject</code> function. Here is the function signature:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">BOOL</span> <span class="nf">SetInformationJobObject</span><span class="p">(</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">HANDLE</span>             <span class="n">hJob</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">JOBOBJECTINFOCLASS</span> <span class="n">JobObjectInformationClass</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">LPVOID</span>             <span class="n">lpJobObjectInformation</span><span class="p">,</span>
  <span class="p">[</span><span class="n">in</span><span class="p">]</span> <span class="n">DWORD</span>              <span class="n">cbJobObjectInformationLength</span>
<span class="p">);</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">hJob</code> parameter is a handle to the job object.<br />
The <code class="language-plaintext highlighter-rouge">JobObjectInformationClass</code> parameter is a value that specifies the type of information that you want to set. The next parameter is used to specify the actual information that you want to set.<br />
The <code class="language-plaintext highlighter-rouge">lpJobObjectInformation</code> parameter is a pointer to the structure containing information that you want to set.</p>

<h1 id="code-examples">Code Examples</h1>
<p>Now that you know the basics of working with processes, jobs, threads and fibers let’s see some code examples.</p>

<h2 id="creating-a-process">Creating a Process</h2>
<p>Let’s start by looking at how to create a process.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;windows.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="n">STARTUPINFOA</span> <span class="n">si</span><span class="p">;</span>
    <span class="n">PROCESS_INFORMATION</span> <span class="n">pi</span><span class="p">;</span>

    <span class="n">ZeroMemory</span><span class="p">(</span> <span class="o">&amp;</span><span class="n">si</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">si</span><span class="p">)</span> <span class="p">);</span>
    <span class="n">si</span><span class="p">.</span><span class="n">cb</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">si</span><span class="p">);</span>
    <span class="n">ZeroMemory</span><span class="p">(</span> <span class="o">&amp;</span><span class="n">pi</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">pi</span><span class="p">)</span> <span class="p">);</span>
    <span class="n">LPSTR</span> <span class="n">lpCommandLine</span> <span class="o">=</span> <span class="s">"notepad.exe"</span><span class="p">;</span>

    <span class="c1">// Start the child process. </span>
    <span class="k">if</span><span class="p">(</span> <span class="o">!</span><span class="n">CreateProcessA</span><span class="p">(</span> <span class="nb">NULL</span><span class="p">,</span>   <span class="c1">// No module name (use command line)</span>
        <span class="n">lpCommandLine</span><span class="p">,</span>        <span class="c1">// Command line</span>
        <span class="mi">0</span><span class="p">,</span>           <span class="c1">// Process handle not inheritable</span>
        <span class="mi">0</span><span class="p">,</span>           <span class="c1">// Thread handle not inheritable</span>
        <span class="mi">0</span><span class="p">,</span>          <span class="c1">// Set handle inheritance to FALSE</span>
        <span class="mi">0</span><span class="p">,</span>              <span class="c1">// No creation flags</span>
        <span class="mi">0</span><span class="p">,</span>           <span class="c1">// Use parent's environment block</span>
        <span class="mi">0</span><span class="p">,</span>           <span class="c1">// Use parent's starting directory </span>
        <span class="o">&amp;</span><span class="n">si</span><span class="p">,</span>            <span class="c1">// Pointer to STARTUPINFO structure</span>
        <span class="o">&amp;</span><span class="n">pi</span> <span class="p">)</span>           <span class="c1">// Pointer to PROCESS_INFORMATION structure</span>
    <span class="p">){</span>
        <span class="n">printf</span><span class="p">(</span> <span class="s">"CreateProcess failed (%d).</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">GetLastError</span><span class="p">()</span> <span class="p">);</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Process Created!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>

    <span class="c1">// Sleep for 5 seconds</span>
    <span class="n">Sleep</span><span class="p">(</span><span class="mi">5000</span><span class="p">);</span>

    <span class="c1">// Close process and thread handles. </span>
    <span class="n">CloseHandle</span><span class="p">(</span> <span class="n">pi</span><span class="p">.</span><span class="n">hProcess</span> <span class="p">);</span>
    <span class="n">CloseHandle</span><span class="p">(</span> <span class="n">pi</span><span class="p">.</span><span class="n">hThread</span> <span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This code should open notepad.exe and exit after 5 seconds.<br />
Process creation is pretty easy, you just need to know the name of the executable and the command line arguments if you want to pass any.</p>

<h2 id="creating-a-thread">Creating a Thread</h2>
<p>Now that you know how to create a process, let’s look at how to create a thread.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;windows.h&gt;</span><span class="cp">
</span>
<span class="c1">// Function to create a thread</span>
<span class="kt">int</span> <span class="nf">EthicalFunction</span><span class="p">(</span><span class="n">LPVOID</span> <span class="n">lpParam</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Print a message</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Thread created</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"For educational purposes only*</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="c1">// Return success</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// Create a thread</span>
    <span class="n">HANDLE</span> <span class="n">hThread</span> <span class="o">=</span> <span class="n">CreateThread</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="p">(</span><span class="n">LPTHREAD_START_ROUTINE</span><span class="p">)</span><span class="n">EthicalFunction</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
    <span class="c1">// Wait for thread to finish</span>
    <span class="n">WaitForSingleObject</span><span class="p">(</span><span class="n">hThread</span><span class="p">,</span> <span class="n">INFINITE</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Thread returned</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Exiting...</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="c1">// Close thread handle</span>
    <span class="n">CloseHandle</span><span class="p">(</span><span class="n">hThread</span><span class="p">);</span>
    <span class="c1">// Return success</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This code is creating a thread for the <code class="language-plaintext highlighter-rouge">EthicalFunction</code> function and waiting for it to finish and then exiting after printing a message.<br />
You can create multiple threads for multiple functions like this, for example if you want to create a thread a background thread that runs in the background and does not block the main thread until it is finished with its work.</p>

<h2 id="creating-a-fiber">Creating a Fiber</h2>
<p>Next, let’s look at how to create a fiber.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;windows.h&gt;</span><span class="cp">
</span>
<span class="c1">// fiber function</span>
<span class="kt">void</span> <span class="nf">fiber_function</span><span class="p">(</span><span class="kt">void</span><span class="o">*</span> <span class="n">lpParam</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Print a message</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Fiber created</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"For educational purposes only*</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="c1">// Converting back into the main thread as fiber will not return to the main thread by itself</span>
    <span class="n">SwitchToFiber</span><span class="p">(</span><span class="n">lpParam</span><span class="p">);</span>

<span class="p">}</span>

<span class="c1">// main function</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// Converting thread to fiber</span>
    <span class="n">LPVOID</span> <span class="n">Context</span> <span class="o">=</span> <span class="n">ConvertThreadToFiber</span><span class="p">(</span><span class="nb">NULL</span><span class="p">);</span>
    <span class="c1">// Creating fiber</span>
    <span class="n">LPVOID</span> <span class="n">lpFiber</span> <span class="o">=</span> <span class="n">CreateFiber</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="p">(</span><span class="n">LPFIBER_START_ROUTINE</span><span class="p">)</span><span class="n">fiber_function</span><span class="p">,</span> <span class="n">Context</span><span class="p">);</span>
    <span class="c1">// Switching to fiber (executing fiber function)</span>
    <span class="n">SwitchToFiber</span><span class="p">(</span><span class="n">lpFiber</span><span class="p">);</span>
    <span class="c1">// Printing a message</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Fiber returned</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="c1">// Deleting fiber</span>
    <span class="n">DeleteFiber</span><span class="p">(</span><span class="n">lpFiber</span><span class="p">);</span>
    <span class="c1">// Return success</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Exiting...</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This code will create a fiber and execute it and then switch back to the main thread and the main thread will print a message and delete the fiber.</p>

<h2 id="creating-a-job-object">Creating a Job Object</h2>
<p>Let’s look at how to create a job object and assign a processes to it.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;windows.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// Creating a job with default security attributes</span>
    <span class="n">HANDLE</span> <span class="n">hJob</span> <span class="o">=</span> <span class="n">CreateJobObject</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="s">"Unemployed"</span><span class="p">);</span>
    <span class="c1">// Setting the job to terminate when all processes in it terminate</span>
    <span class="n">JOBOBJECT_EXTENDED_LIMIT_INFORMATION</span> <span class="n">jeli</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span>
    <span class="n">jeli</span><span class="p">.</span><span class="n">BasicLimitInformation</span><span class="p">.</span><span class="n">LimitFlags</span> <span class="o">=</span> <span class="n">JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE</span><span class="p">;</span>
    <span class="n">SetInformationJobObject</span><span class="p">(</span><span class="n">hJob</span><span class="p">,</span> <span class="n">JobObjectExtendedLimitInformation</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">jeli</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">jeli</span><span class="p">));</span>
    <span class="c1">// Creating structures for notepad, cmd and powershell</span>
    <span class="n">STARTUPINFOA</span> <span class="n">si</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span>
    <span class="n">si</span><span class="p">.</span><span class="n">cb</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">si</span><span class="p">);</span>
    <span class="n">PROCESS_INFORMATION</span> <span class="n">pi</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span>
    <span class="n">STARTUPINFOA</span> <span class="n">si1</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span>
    <span class="n">si1</span><span class="p">.</span><span class="n">cb</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">si1</span><span class="p">);</span>
    <span class="n">PROCESS_INFORMATION</span> <span class="n">pi1</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span>

    <span class="c1">// Creating notepad, and Windows media player in suspended state and adding them to the job and checking for errors</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">CreateProcessA</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="p">(</span><span class="n">LPSTR</span><span class="p">)</span><span class="s">"notepad.exe"</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">FALSE</span><span class="p">,</span> <span class="n">CREATE_SUSPENDED</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">si</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">pi</span><span class="p">)</span> <span class="o">||</span> <span class="o">!</span><span class="n">CreateProcessA</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="p">(</span><span class="n">LPSTR</span><span class="p">)</span><span class="s">"dvdplay.exe"</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">FALSE</span><span class="p">,</span> <span class="n">CREATE_SUSPENDED</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">si1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">pi1</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"Error creating processes</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"Error code: %d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">GetLastError</span><span class="p">());</span>
        <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    
    <span class="n">AssignProcessToJobObject</span><span class="p">(</span><span class="n">hJob</span><span class="p">,</span> <span class="n">pi</span><span class="p">.</span><span class="n">hProcess</span><span class="p">);</span>
    <span class="n">AssignProcessToJobObject</span><span class="p">(</span><span class="n">hJob</span><span class="p">,</span> <span class="n">pi1</span><span class="p">.</span><span class="n">hProcess</span><span class="p">);</span>

    <span class="c1">// Resuming processes</span>
    <span class="n">ResumeThread</span><span class="p">(</span><span class="n">pi</span><span class="p">.</span><span class="n">hThread</span><span class="p">);</span>
    <span class="n">ResumeThread</span><span class="p">(</span><span class="n">pi1</span><span class="p">.</span><span class="n">hThread</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Job created and processes added!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    
    <span class="c1">// SLeeping for 1 minutes to let the processes run</span>
    <span class="n">Sleep</span><span class="p">(</span><span class="mi">60000</span><span class="p">);</span>
    <span class="c1">// Terminating the job</span>
    <span class="n">TerminateJobObject</span><span class="p">(</span><span class="n">hJob</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="c1">// Closing handles</span>
    <span class="n">CloseHandle</span><span class="p">(</span><span class="n">pi</span><span class="p">.</span><span class="n">hProcess</span><span class="p">);</span>
    <span class="n">CloseHandle</span><span class="p">(</span><span class="n">pi</span><span class="p">.</span><span class="n">hThread</span><span class="p">);</span>
    <span class="n">CloseHandle</span><span class="p">(</span><span class="n">hJob</span><span class="p">);</span>

    <span class="c1">// Return success</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Exiting...</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This code will create a job object named <code class="language-plaintext highlighter-rouge">Unemployed</code> and add two notepad and Windows Media Player processes to it and then terminate the job after 1 minutes.<br />
To confirm that the processes are running inside the <code class="language-plaintext highlighter-rouge">Unemployed</code> job, you can use Process Explorer to view the Properties -&gt; Job of either <code class="language-plaintext highlighter-rouge">notepad.exe</code> or <code class="language-plaintext highlighter-rouge">wmplayer.exe</code> (not <code class="language-plaintext highlighter-rouge">dvdplay.exe</code> as it immediately launches this as the child process, it can also be <code class="language-plaintext highlighter-rouge">setup_wm.exe</code> if you do not have your Windows Media Player setup).<br />
Here’s an example image:<br />
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fjob_process_exp.png" width="500" height="600" /></p>

<h1 id="summary">Summary</h1>
<p>This post covered an overview of the internals of processes, threads, fibers and jobs as well the classification of processes into different types. We also looked at the different components of a process. Later, we looked at how to create a process, thread, fiber and job objects.<br />
I hope you enjoyed this post and found it useful.<br />
Thank you for reading!</p>

<h1 id="resources">Resources</h1>
<ul>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fprocthread%2Fprocesses-and-threads">Process and Threads - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fprocessthreadsapi%2Fnf-processthreadsapi-createprocessa">CreateProcess - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fwinbase%2Fnf-winbase-createjobobjecta">CreateJobObject - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fjobapi2%2Fnf-jobapi2-assignprocesstojobobject">AssignProcessToJobObject - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F89588%2Fassignprocesstojobobject-fails-with-access-denied-error-when-running-under-the">AssignProcessToJobObject fails with “Access Denied” error when running under the debugger</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fwinbase%2Fnf-winbase-terminatejobobject">TerminateJobObject - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fprocessthreadsapi%2Fnf-processthreadsapi-createthread">CreateThread - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fwinbase%2Fnf-winbase-createfiber">CreateFiber - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fwinbase%2Fnf-winbase-switchtofiber">SwitchToFiber - msdn</a></li>
</ul>]]></content><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><category term="WinAPI" /><category term="Windows API Series" /><category term="Windows Internals Series" /><summary type="html"><![CDATA[This blog post covers a brief overview of Processes, Threads, Fibers, Jobs and their components on Windows and how the Windows API can be used to work with them.]]></summary></entry><entry><title type="html">Understanding SMT solvers: An Introduction to Z3</title><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FSMT-Solvers%2F" rel="alternate" type="text/html" title="Understanding SMT solvers: An Introduction to Z3" /><published>2022-08-03T05:00:00+00:00</published><updated>2022-08-03T05:00:00+00:00</updated><id>https://de-engineer.github.io/SMT-Solvers</id><content type="html" xml:base="https://de-engineer.github.io/SMT-Solvers/"><![CDATA[<p>Satisfiability Modulo Theories (SMT) solvers are one of the most interesting topics to learn about in Computer Science. They can reduce a big chunk of time that would otherwise be spent on statically or dynamically analyzing the binary.
While SMT solvers have their limits, when they work, they work like magic. You might already have heard of or seen someone use a SMT solver like Z3 for solving CTF challenges or Program Analysis. By the end of this blog, you’ll have a good grasp of all the required knowledge to get started with SMT solvers and use Z3.</p>

<p>This post does not use any complicated mathematics to explain these solvers and will deal with only required theory and examples to get started. To go deep into SMT solvers and Program Analysis check out #resources.</p>

<p class="notice--info"><strong>Info: If you want to watch a video version, which I made for GuidedHacking (covers 50% of this blog): <a href="iframe.php?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEacYNe7moSs">Watch Here</a></strong></p>

<p>Table of contents:</p>
<ul id="markdown-toc">
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23sat-solvers" id="markdown-toc-sat-solvers">SAT Solvers</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23relation-with-smt-solvers" id="markdown-toc-relation-with-smt-solvers">Relation with SMT solvers</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23terminologies" id="markdown-toc-terminologies">Terminologies</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23symbolic-execution" id="markdown-toc-symbolic-execution">Symbolic Execution</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23high-iq-facebook-problem" id="markdown-toc-high-iq-facebook-problem">High IQ Facebook problem</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23example-with-z3" id="markdown-toc-example-with-z3">Example with z3</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23another-example" id="markdown-toc-another-example">Another example</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23problems-with-smt-solvers" id="markdown-toc-problems-with-smt-solvers">Problems with SMT solvers</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23path-explosions" id="markdown-toc-path-explosions">Path explosions</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23summary" id="markdown-toc-summary">Summary</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources" id="markdown-toc-resources">Resources</a></li>
</ul>

<h1 id="sat-solvers">SAT Solvers</h1>
<p>SMT solvers leverage the powers of another type of solvers called Boolean Satisfiability Problem solvers (SAT solvers). As the name suggests, they have something to do with Boolean variables.</p>

<p>These solvers basically take a Boolean expressions as input and output whether there are possible values for the Boolean variables which result in the expression returning <code class="language-plaintext highlighter-rouge">true</code> (or <code class="language-plaintext highlighter-rouge">satisfiable</code>). When there are no such variables SAT solver outputs <code class="language-plaintext highlighter-rouge">false</code> (or <code class="language-plaintext highlighter-rouge">unsatisifable</code>). 
If the expression is satisfiable then the SAT solver can also output the values for the variables which satisfy the expression.</p>

<h2 id="relation-with-smt-solvers">Relation with SMT solvers</h2>
<p>Satisfiability Modulo Theory (SMT) solvers essentially combine the powers of SAT solvers and some other type of solvers but SAT solvers are the primary backend of SMT solvers.
SMT solvers like SAT are able to find not only the satisfiability but also the satisfying inputs for Boolean expressions but they are not limited to just Boolean expressions. SMT solvers are capable of other inputs such as integer, bitvector, arrays and arithmetic operations.</p>

<h3 id="terminologies">Terminologies</h3>
<p>There are few terms that you’ll need to know when navigating through the smt solver territory.
<strong>Concrete values</strong>: Concrete values are simply constant values. For example <code class="language-plaintext highlighter-rouge">5</code> is a concrete value. It’s that simple.
<strong>Symbolic values</strong>: Symbolic values are like the unknown variables which you have when dealing with an algebraic expression. These are have are used to represent values which are not yet known. 
Example: <code class="language-plaintext highlighter-rouge">3x + 2y = 1</code>, in this expression <code class="language-plaintext highlighter-rouge">x</code> and <code class="language-plaintext highlighter-rouge">y</code> are symbolic values.</p>

<h1 id="symbolic-execution">Symbolic Execution</h1>
<p>Symbolic Execution is a technique which essentially reduces the conditions inside given program into mathematical equations and tries to solve them using SMT and SAT solvers.</p>

<p>Instead of just theoretical explanation, let us look at an example in order to understand the the essence of Symbolic Execution.
Consider the following C program:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="n">getUserInput</span><span class="p">();</span>
  <span class="kt">int</span> <span class="n">k</span> <span class="o">=</span> <span class="n">j</span> <span class="o">*</span> <span class="mi">2</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">k</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">k</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">8</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">printf</span><span class="p">(</span><span class="s">"Correct input!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
      <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>When compiled and executed normally, this program would take an concrete integer input (<em>lets say 7</em>) from the user and evaluate and run into the path which is satisfiable which would result in the program calling the exit function in this case.
However, when run with symbolic execution:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">j</code> will be assigned a symbolic value (<em>e.g. <code class="language-plaintext highlighter-rouge">γ</code></em>)</li>
  <li>k will be assigned <code class="language-plaintext highlighter-rouge">γ * 2</code></li>
  <li>At the if statement, the symbolic execution engine will remember the condition as a constraint (<em>i.e. <code class="language-plaintext highlighter-rouge">γ * 2 &gt; 0</code></em>) and execute the if branch and at the same time remember the else branch and add it’s constraint (<em><code class="language-plaintext highlighter-rouge">γ * 2 &lt; 0</code></em>) and execute that too symbolically with a copy of the program’s current state just like what the if branch has except with a different constraint.
    <ul>
      <li>The path that the if branch takes has another if condition whose constraint (<em><code class="language-plaintext highlighter-rouge">γ * 2 * 2 == 8</code></em>) is again remembered along with the existing constraint (<em><code class="language-plaintext highlighter-rouge">γ * 2 &gt; 0</code></em>) and also symbolically executes the else branch at the same time with the opposite constraints.
        <ul>
          <li>The if branch then proceeds and executes the code which essentially leads the program to exit normally after printing “Correct Input!”, the symbolic execution engine then solves the remembered constraints [<code class="language-plaintext highlighter-rouge"> * 2 &gt; 0</code>, <code class="language-plaintext highlighter-rouge">γ * 2 * == 8</code>] which results in a concrete value and remembers the paths it leads to.</li>
        </ul>
      </li>
      <li>The path that the else branch takes simply exits so the concrete value to this path is solved and remembered.</li>
    </ul>
  </li>
  <li>The path that the else branch takes leads to an exit after which the symbolic execution engine solves the constraints and get’s the concrete value which will satisfy the constraints (<em>i.e. γ * 2 &lt; 0</em>) and remembers the path it leads to. 
After the execution is complete, the symbolic execution engine will output all the possible inputs or the requested inputs and tell where they will lead.</li>
</ul>

<p>Let us first label all the code paths so it will be easier for us to understand:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="n">getUserInput</span><span class="p">();</span>
  <span class="kt">int</span> <span class="n">k</span> <span class="o">=</span> <span class="n">j</span> <span class="o">*</span> <span class="mi">2</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">k</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
    <span class="nl">path_if_1:</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">k</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">8</span><span class="p">)</span> <span class="p">{</span>
      <span class="nl">path_if_2:</span>
      <span class="n">printf</span><span class="p">(</span><span class="s">"Correct input!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">else</span> <span class="p">{</span>
      <span class="nl">path_else_2:</span>
      <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span>
  <span class="k">else</span> <span class="p">{</span>
    <span class="nl">path_else_1:</span>
    <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Here’s what we assume the Symbolic Execution engine will tell us:</p>

<table>
  <thead>
    <tr>
      <th>Constraint</th>
      <th style="text-align: left">Path</th>
      <th style="text-align: center">Solution</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>k &gt; 0</td>
      <td style="text-align: left">path_if_1</td>
      <td style="text-align: center">All numbers greater than 0 (n &gt; 0)</td>
    </tr>
    <tr>
      <td>k &lt; 0</td>
      <td style="text-align: left">path_else_1</td>
      <td style="text-align: center">All numbers are smaller than 0 (n &lt; 0)</td>
    </tr>
    <tr>
      <td>[k &gt; 0, k * 2 == 8]</td>
      <td style="text-align: left">path_if_2</td>
      <td style="text-align: center">2 (n=2)</td>
    </tr>
    <tr>
      <td>[k &gt; 0, k * 2 != 8]</td>
      <td style="text-align: left">path_if_2</td>
      <td style="text-align: center">Any number greater than 0 except +2 (n &gt; 0, n != 2)</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td><em>Consider n to contain all possible inputs.</em></td>
      <td style="text-align: left"> </td>
      <td style="text-align: center"> </td>
    </tr>
  </tfoot>
</table>

<p>And now, we know of all the possible inputs and the path they will lead to and now, we can input a specific value and get to the desired path. This desired path is usually a piece of unexplored code region that requires some input that we do not know and as you can see, we can figure that out with the power of symbolic execution.</p>

<h1 id="high-iq-facebook-problem">High IQ Facebook problem</h1>
<p>All of us have seen those social media posts where it’s a math puzzle type question which states that 99% people fail at solving them, I’m not sure about the source of this statistic but what I’m sure about is that you’ll be capable of solving those problems in seconds after learning about z3, which is what we’ll do in this part of the blog and learn how this relates with symbolic execution later.
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2FQuestion+1.png" />
This is one such graphic with a question (I redesigned the original problem so it looks nice), if we use symbols, we can represent the problem like this:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">=</span> <span class="mi">16</span>
<span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">=</span> <span class="mi">27</span>
<span class="n">triangle</span> <span class="o">*</span> <span class="n">square</span> <span class="o">=</span> <span class="mi">6</span>

<span class="n">square</span> <span class="o">*</span> <span class="n">circle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">=</span> <span class="o">?</span>
</code></pre></div></div>
<p>Upon reading the problem question, we know the following things for sure:</p>
<ul>
  <li>There are 3 unknown variables - square, triangle and circle.</li>
  <li>There are total 3 known concrete result values of the expressions made of these 3 unknown variables.</li>
  <li>All three unknown variables hold integer values.</li>
</ul>

<p>These three <em>known concrete values</em> of the <em>expressions</em> of these <em>unknown values</em> are essentially the constraints required to reach the required values for square, circle and triangle. If you do not understand this right now, you’ll get it soon.</p>

<h1 id="example-with-z3">Example with z3</h1>
<p>To get started with z3, install it with the following command:</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pip <span class="nb">install </span>z3_solver
</code></pre></div></div>

<p>Now, import everything from z3 to get started:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>
</code></pre></div></div>

<p>Let me bring the problem question here so you don’t have to scroll.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">=</span> <span class="mi">16</span>
<span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">=</span> <span class="mi">27</span>
<span class="n">triangle</span> <span class="o">*</span> <span class="n">square</span> <span class="o">=</span> <span class="mi">6</span>

<span class="n">square</span> <span class="o">*</span> <span class="n">circle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">=</span> <span class="err">?</span>
</code></pre></div></div>

<p>From our previous analysis, we know that all three unknown variables hold integer values, so we’ll define all three of these as <code class="language-plaintext highlighter-rouge">Ints</code>:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="n">square</span> <span class="o">=</span> <span class="n">Int</span><span class="p">(</span><span class="s">"square"</span><span class="p">)</span>
<span class="n">circle</span> <span class="o">=</span> <span class="n">Int</span><span class="p">(</span><span class="s">"circle"</span><span class="p">)</span>
<span class="n">triangle</span> <span class="o">=</span> <span class="n">Int</span><span class="p">(</span><span class="s">"triangle"</span><span class="p">)</span>

<span class="c1"># Alternatively you can define all of them in one line
# square, circle, triangle = Ints("square, circle, triangle")
</span></code></pre></div></div>

<p>Now, we’ll have to create a solver object to which we will add all of our constraints:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="n">square</span> <span class="o">=</span> <span class="n">Int</span><span class="p">(</span><span class="s">"square"</span><span class="p">)</span>
<span class="n">circle</span> <span class="o">=</span> <span class="n">Int</span><span class="p">(</span><span class="s">"circle"</span><span class="p">)</span>
<span class="n">triangle</span> <span class="o">=</span> <span class="n">Int</span><span class="p">(</span><span class="s">"triangle"</span><span class="p">)</span>

<span class="n">solver</span> <span class="o">=</span> <span class="n">Solver</span><span class="p">()</span>
</code></pre></div></div>
<p>Let us now define our first constraint, which is <code class="language-plaintext highlighter-rouge">square * square + circle = 16</code>:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="p">...</span>

<span class="n">solver</span> <span class="o">=</span> <span class="n">Solver</span><span class="p">()</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">==</span> <span class="mi">16</span><span class="p">)</span> <span class="c1"># z3 requires us to use '==' for showing equality.
</span></code></pre></div></div>
<p>Simple, right? Now add the rest of the constraints:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="p">...</span>

<span class="n">solver</span> <span class="o">=</span> <span class="n">Solver</span><span class="p">()</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">==</span> <span class="mi">16</span><span class="p">)</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">==</span> <span class="mi">27</span><span class="p">)</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">square</span> <span class="o">==</span> <span class="mi">6</span><span class="p">)</span>
</code></pre></div></div>
<p>Now after defining all the constraints, the next for us is to check whether these set of equations (or constraints) are satisfiable or not, which can be done by calling the <code class="language-plaintext highlighter-rouge">check</code> method on the <code class="language-plaintext highlighter-rouge">solver</code> object after defining the constraints:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="p">...</span>

<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">==</span> <span class="mi">16</span><span class="p">)</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">==</span> <span class="mi">27</span><span class="p">)</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">square</span> <span class="o">==</span> <span class="mi">6</span><span class="p">)</span>

<span class="c1"># sat stands for sastisfiable, meaning that the set of constraints are satisfiable
</span><span class="k">if</span> <span class="n">solver</span><span class="p">.</span><span class="n">check</span><span class="p">()</span> <span class="o">==</span> <span class="n">sat</span><span class="p">:</span>
	<span class="c1"># do stuff	
</span></code></pre></div></div>
<p>After calling the <code class="language-plaintext highlighter-rouge">check</code> method, we call the <code class="language-plaintext highlighter-rouge">model</code> method to retrieve a satisfying model which we can later use to get the values of the unknown variables:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="p">...</span>

<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">==</span> <span class="mi">16</span><span class="p">)</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">==</span> <span class="mi">27</span><span class="p">)</span>
<span class="n">solver</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">square</span> <span class="o">==</span> <span class="mi">6</span><span class="p">)</span>

<span class="c1"># sat stands for sastisfiable, meaning that the set of constraints are satisfiable
</span><span class="k">if</span> <span class="n">solver</span><span class="p">.</span><span class="n">check</span><span class="p">()</span> <span class="o">==</span> <span class="n">sat</span><span class="p">:</span>
	<span class="n">m</span> <span class="o">=</span> <span class="n">solver</span><span class="p">.</span><span class="n">model</span><span class="p">()</span>
</code></pre></div></div>
<p>If you want to keep things easier, you can simply print <code class="language-plaintext highlighter-rouge">m</code> and it’ll return the values for square, circle and triangle.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="p">...</span>

<span class="c1"># sat stands for sastisfiable, meaning that the set of constraints are satisfiable
</span><span class="k">if</span> <span class="n">solver</span><span class="p">.</span><span class="n">check</span><span class="p">()</span> <span class="o">==</span> <span class="n">sat</span><span class="p">:</span>
	<span class="n">m</span> <span class="o">=</span> <span class="n">solver</span><span class="p">.</span><span class="n">model</span><span class="p">()</span>
	<span class="k">print</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
</code></pre></div></div>
<p>This will output the values which satisfy our constraint, which are:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">circle</span> <span class="o">=</span> <span class="mi">12</span><span class="p">,</span> <span class="n">triangle</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">square</span> <span class="o">=</span> <span class="mi">2</span><span class="p">]</span>
</code></pre></div></div>
<p>Now you could manually do solve question with just these values or write code which can do it itself:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>manually:

square * circle * triangle = ?
2 * 12 * 3 = 72
</code></pre></div></div>
<p>The other way is this:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">z3</span> <span class="kn">import</span> <span class="o">*</span>

<span class="p">...</span>

<span class="c1"># sat stands for sastisfiable, meaning that the set of constraints are satisfiable
</span><span class="k">if</span> <span class="n">solver</span><span class="p">.</span><span class="n">check</span><span class="p">()</span> <span class="o">==</span> <span class="n">sat</span><span class="p">:</span>
	<span class="n">m</span> <span class="o">=</span> <span class="n">solver</span><span class="p">.</span><span class="n">model</span><span class="p">()</span>

	<span class="c1"># eval method returns the numbers with the type z3.z3.IntNumRef
</span>	<span class="c1"># as_long method is used to convert that type to int
</span>	<span class="n">square_value</span> <span class="o">=</span> <span class="n">m</span><span class="p">.</span><span class="nb">eval</span><span class="p">(</span><span class="n">square</span><span class="p">).</span><span class="n">as_long</span><span class="p">()</span>
	<span class="n">circle_value</span> <span class="o">=</span> <span class="n">m</span><span class="p">.</span><span class="nb">eval</span><span class="p">(</span><span class="n">circle</span><span class="p">).</span><span class="n">as_long</span><span class="p">()</span>
	<span class="n">triangle_value</span> <span class="o">=</span> <span class="n">m</span><span class="p">.</span><span class="nb">eval</span><span class="p">(</span><span class="n">triangle</span><span class="p">).</span><span class="n">as_long</span><span class="p">()</span>

	<span class="n">result</span> <span class="o">=</span> <span class="n">square_value</span> <span class="o">*</span> <span class="n">circle_value</span> <span class="o">*</span> <span class="n">triangle_value</span>
	<span class="k">print</span><span class="p">(</span><span class="s">"The answer is: "</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
</code></pre></div></div>
<p>That’s it, it wasn’t the smallest of the explanation but was meant for people with any level of experience with z3 to understand it. The full code can be found <a href="iframe.php?url=https%3A%2F%2Fgist.github.com%2FHACKE-RC%2Fa758a8516d4a2ecf5172e53b76d0ae57">here</a>.</p>

<p>Now, look at this piece of code:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
</span>
<span class="kt">void</span> <span class="nf">win</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"You win!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
  <span class="n">exit</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">lose</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"You lose!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
  <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">check</span><span class="p">(</span><span class="kt">int</span> <span class="n">square</span><span class="p">,</span> <span class="kt">int</span> <span class="n">circle</span><span class="p">,</span> <span class="kt">int</span> <span class="n">triangle</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">square</span> <span class="o">*</span> <span class="n">square</span> <span class="o">+</span> <span class="n">circle</span> <span class="o">==</span> <span class="mi">16</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">*</span> <span class="n">triangle</span> <span class="o">==</span> <span class="mi">27</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">triangle</span> <span class="o">*</span> <span class="n">square</span> <span class="o">==</span> <span class="mi">6</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">win</span><span class="p">();</span>
      <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">}</span>
  <span class="n">lose</span><span class="p">();</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">square</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">circle</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">triangle</span><span class="p">;</span>

  <span class="n">printf</span><span class="p">(</span><span class="s">"Enter the value of square: "</span><span class="p">);</span>
  <span class="n">scanf</span><span class="p">(</span><span class="s">"%d"</span><span class="p">,</span> <span class="o">&amp;</span> <span class="n">square</span><span class="p">);</span>

  <span class="n">printf</span><span class="p">(</span><span class="s">"Enter the value of circle: "</span><span class="p">);</span>
  <span class="n">scanf</span><span class="p">(</span><span class="s">"%d"</span><span class="p">,</span> <span class="o">&amp;</span> <span class="n">circle</span><span class="p">);</span>

  <span class="n">printf</span><span class="p">(</span><span class="s">"Enter the value of triangle: "</span><span class="p">);</span>
  <span class="n">scanf</span><span class="p">(</span><span class="s">"%d"</span><span class="p">,</span> <span class="o">&amp;</span> <span class="n">triangle</span><span class="p">);</span>

  <span class="n">check</span><span class="p">(</span><span class="n">square</span><span class="p">,</span> <span class="n">circle</span><span class="p">,</span> <span class="n">triangle</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Looks familiar? <br />
Well, this is the same problem but framed as a C program where the objective is to get the program to call the <code class="language-plaintext highlighter-rouge">win</code> function. Obviously, we can get the valid inputs for this program from the same script as before.
And this is how you’ll write scripts - by first reading the decompiled or source code of the program and then figuring out all the constraints (or conditions) that are needed to be satisfied in order to reach a specific path.</p>

<p>Now that we’ve gone through this one, you can surely try another simple problem that I found today on Twitter:
<a href="iframe.php?url=https%3A%2F%2Ftwitter.com%2Fgunsnrosesgirl3%2Fstatus%2F1687158247881392137">Here</a>  <br />
Solution <a href="iframe.php?url=https%3A%2F%2Ftwitter.com%2Fcoder_rc%2Fstatus%2F1687430938761027584">here</a></p>

<h1 id="another-example">Another example</h1>
<p>Let’s try another example from a recent challenge from amateurs ctf, it’s name was “volcano”.</p>
<ul>
  <li><strong>Given file:</strong> <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fassets%2Fexecutables%2Fvolcano">volcano</a></li>
  <li><strong>Description:</strong> Inspired by recent “traumatic” events.</li>
</ul>

<p>Here’s the decompilation of the <code class="language-plaintext highlighter-rouge">main</code> function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">__int64</span> <span class="kr">__fastcall</span> <span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">a1</span><span class="p">,</span> <span class="kt">char</span> <span class="o">**</span><span class="n">a2</span><span class="p">,</span> <span class="kt">char</span> <span class="o">**</span><span class="n">a3</span><span class="p">)</span>
<span class="p">{</span>
  <span class="p">...</span>

  <span class="n">v13</span> <span class="o">=</span> <span class="n">__readfsqword</span><span class="p">(</span><span class="mh">0x28u</span><span class="p">);</span>
  <span class="n">setbuf</span><span class="p">(</span><span class="n">stdin</span><span class="p">,</span> <span class="mi">0LL</span><span class="p">);</span>
  <span class="n">setbuf</span><span class="p">(</span><span class="n">stdout</span><span class="p">,</span> <span class="mi">0LL</span><span class="p">);</span>
  <span class="n">setbuf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="mi">0LL</span><span class="p">);</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"Give me a bear: "</span><span class="p">);</span>
  <span class="n">v7</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="n">__isoc99_scanf</span><span class="p">(</span><span class="s">"%llu"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">v7</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="kr">__int8</span><span class="p">)</span><span class="n">sub_0_12BB</span><span class="p">(</span><span class="n">v7</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
  <span class="p">{</span>
    <span class="n">puts</span><span class="p">(</span><span class="s">"That doesn't look like a bear!"</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">1LL</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">else</span>
  <span class="p">{</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Give me a volcano: "</span><span class="p">);</span>
    <span class="n">v8</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
    <span class="n">__isoc99_scanf</span><span class="p">(</span><span class="s">"%llu"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">v8</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="kr">__int8</span><span class="p">)</span><span class="n">sub_0_13D9</span><span class="p">(</span><span class="n">v8</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
    <span class="p">{</span>
      <span class="n">puts</span><span class="p">(</span><span class="s">"That doesn't look like a volcano!"</span><span class="p">);</span>
      <span class="k">return</span> <span class="mi">1LL</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">else</span>
    <span class="p">{</span>
      <span class="n">printf</span><span class="p">(</span><span class="s">"Prove to me they are the same: "</span><span class="p">);</span>
      <span class="n">v9</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
      <span class="n">v10</span> <span class="o">=</span> <span class="mi">4919LL</span><span class="p">;</span>
      <span class="n">__isoc99_scanf</span><span class="p">(</span><span class="s">"%llu"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">v9</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="n">v9</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">v9</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
      <span class="p">{</span>
        <span class="n">v4</span> <span class="o">=</span> <span class="n">sub_0_1209</span><span class="p">(</span><span class="n">v8</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span> <span class="n">v4</span> <span class="o">==</span> <span class="n">sub_0_1209</span><span class="p">(</span><span class="n">v7</span><span class="p">)</span>
          <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v5</span> <span class="o">=</span> <span class="n">sub_0_124D</span><span class="p">(</span><span class="n">v8</span><span class="p">),</span> <span class="n">v5</span> <span class="o">==</span> <span class="n">sub_0_124D</span><span class="p">(</span><span class="n">v7</span><span class="p">))</span>
          <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v6</span> <span class="o">=</span> <span class="n">sub_0_1430</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">v8</span><span class="p">,</span> <span class="n">v9</span><span class="p">),</span> <span class="n">v6</span> <span class="o">==</span> <span class="n">sub_0_1430</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">v7</span><span class="p">,</span> <span class="n">v9</span><span class="p">))</span> <span class="p">)</span>
        <span class="p">{</span>
          <span class="n">puts</span><span class="p">(</span><span class="s">"That looks right to me!"</span><span class="p">);</span>
          <span class="n">stream</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"flag.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">);</span>
          <span class="n">fgets</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="n">stream</span><span class="p">);</span>
          <span class="n">puts</span><span class="p">(</span><span class="n">s</span><span class="p">);</span>
          <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
        <span class="p">}</span>
		<span class="p">...</span>
</code></pre></div></div>
<!-- <img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fmain_func_SMT.png">     -->
<p>So, the program first asks for a integer input (<em>llu stands for long long unsigned</em>) and then calls the <code class="language-plaintext highlighter-rouge">sub_0_012BB</code> function to check for something and if the check fails, it prints an error message and exits. <br />
Let’s rename this function to <code class="language-plaintext highlighter-rouge">check_input</code> and look into the function to see what it’s doing:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">_BOOL8</span> <span class="nf">check_input</span><span class="p">(</span><span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a1</span><span class="p">)</span>
<span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="n">a1</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span> <span class="p">)</span>
    <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span> <span class="n">a1</span> <span class="o">%</span> <span class="mi">3</span> <span class="o">!=</span> <span class="mi">2</span> <span class="p">)</span>
    <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span> <span class="n">a1</span> <span class="o">%</span> <span class="mi">5</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
    <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span> <span class="n">a1</span> <span class="o">%</span> <span class="mi">7</span> <span class="o">==</span> <span class="mi">3</span> <span class="p">)</span>
    <span class="k">return</span> <span class="n">a1</span> <span class="o">%</span> <span class="mh">0x6D</span> <span class="o">==</span> <span class="mi">55</span><span class="p">;</span>
  <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<!-- <img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fcheck_bear_func.png">     -->
<p>Looks like it’s just checking for some conditions… or constraints?
These constraints can be easily defined through z3, so let’s do that, here’s what it’ll result in:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">z3</span>  
  
<span class="c1"># 64 bit bitvector (includes printable/non-printable, all characaters)
</span><span class="n">inp1</span> <span class="o">=</span> <span class="n">z3</span><span class="p">.</span><span class="n">BitVec</span><span class="p">(</span><span class="s">'inp1'</span><span class="p">,</span> <span class="mi">64</span><span class="p">)</span>

<span class="n">s</span> <span class="o">=</span> <span class="n">z3</span><span class="p">.</span><span class="n">Solver</span><span class="p">()</span>  
<span class="c1"># conditions based on checks  
</span><span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">((</span><span class="n">inp1</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>  
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mi">3</span> <span class="o">==</span> <span class="mi">2</span><span class="p">)</span>  
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mi">5</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span>  
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mi">7</span> <span class="o">==</span> <span class="mi">3</span><span class="p">)</span>  
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mh">0x6D</span> <span class="o">==</span> <span class="mi">55</span><span class="p">)</span>
</code></pre></div></div>
<p>Now, let’s see what the code does if the checks are passed and keep updating our script:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">...</span>
<span class="k">else</span>
  <span class="p">{</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Give me a volcano: "</span><span class="p">);</span>
    <span class="n">input2</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
    <span class="n">__isoc99_scanf</span><span class="p">(</span><span class="s">"%llu"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">input2</span><span class="p">);</span>
	<span class="c1">// renamed for readability "input2"</span>
    <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="kr">__int8</span><span class="p">)</span><span class="n">sub_0_13D9</span><span class="p">(</span><span class="n">input2</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
    <span class="p">{</span>
      <span class="n">puts</span><span class="p">(</span><span class="s">"That doesn't look like a volcano!"</span><span class="p">);</span>
      <span class="k">return</span> <span class="mi">1LL</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="p">...</span>
</code></pre></div></div>

<p>It’s clear that the program takes another such integer input (<em>lets call it inp2</em>) and then calls a function similar to the previous if statement, let’s also look up this function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">_BOOL8</span> <span class="nf">check_input_2</span><span class="p">(</span><span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a1</span><span class="p">)</span>
<span class="p">{</span>
  <span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">v2</span><span class="p">;</span>

  <span class="n">v2</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span> <span class="n">a1</span> <span class="p">)</span>
  <span class="p">{</span>
    <span class="n">v2</span> <span class="o">+=</span> <span class="n">a1</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">;</span>
    <span class="n">a1</span> <span class="o">&gt;&gt;=</span> <span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="n">v2</span> <span class="o">&gt;</span> <span class="mh">0x10</span> <span class="o">&amp;&amp;</span> <span class="n">v2</span> <span class="o">&lt;=</span> <span class="mh">0x1A</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Nothing quite complex, it seems to be looping <code class="language-plaintext highlighter-rouge">a1</code> times and then doing some some boolean operations - these can be easily reimplemented in Python. Let’s add it to our script:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">z3</span>
<span class="p">...</span>
<span class="c1"># the program asks for a "volcano" so we named it after that
</span><span class="k">def</span> <span class="nf">check_volcano</span><span class="p">(</span><span class="n">a1</span><span class="p">):</span>  
	<span class="n">v2</span> <span class="o">=</span> <span class="mi">0</span>  
	<span class="k">while</span> <span class="n">a1</span><span class="p">:</span>  
		<span class="n">v2</span> <span class="o">+=</span> <span class="n">a1</span> <span class="o">&amp;</span> <span class="mi">1</span> 
		<span class="c1"># &gt;&gt;== is same as: var = var &gt;&gt; 1 
</span>		<span class="n">a1</span> <span class="o">=</span> <span class="n">a1</span> <span class="o">&gt;&gt;</span> <span class="mi">1</span>  

	<span class="c1"># just rewrote it more cleanly
</span>	<span class="k">return</span> <span class="mh">0x10</span> <span class="o">&lt;</span> <span class="n">v2</span> <span class="o">&lt;=</span> <span class="mh">0x1A</span>
</code></pre></div></div>
<p>Perfect!
Let’s look further to see what the program does when this input also passes through the second function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">...</span>
<span class="k">else</span><span class="p">{</span>
      <span class="n">printf</span><span class="p">(</span><span class="s">"Prove to me they are the same: "</span><span class="p">);</span>
      <span class="n">input3</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
      <span class="n">v10</span> <span class="o">=</span> <span class="mh">0x1337LL</span><span class="p">;</span>
      <span class="n">__isoc99_scanf</span><span class="p">(</span><span class="s">"%llu"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">input3</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="n">input3</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">input3</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
      <span class="p">{</span>
		<span class="c1">// function cluster</span>
        <span class="n">v4</span> <span class="o">=</span> <span class="n">sub_0_1209</span><span class="p">(</span><span class="n">input2</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span> <span class="n">v4</span> <span class="o">==</span> <span class="n">sub_0_1209</span><span class="p">(</span><span class="n">input</span><span class="p">)</span>
          <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v5</span> <span class="o">=</span> <span class="n">sub_0_124D</span><span class="p">(</span><span class="n">input2</span><span class="p">),</span> <span class="n">v5</span> <span class="o">==</span> <span class="n">sub_0_124D</span><span class="p">(</span><span class="n">input</span><span class="p">))</span>
          <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v6</span> <span class="o">=</span> <span class="n">sub_0_1430</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">input2</span><span class="p">,</span> <span class="n">input3</span><span class="p">),</span> <span class="n">v6</span> <span class="o">==</span> <span class="n">sub_0_1430</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">input</span><span class="p">,</span> <span class="n">input3</span><span class="p">))</span> <span class="p">)</span>
        <span class="p">{</span>
          <span class="n">puts</span><span class="p">(</span><span class="s">"That looks right to me!"</span><span class="p">);</span>
          <span class="n">stream</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"flag.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">);</span>
          <span class="n">fgets</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="n">stream</span><span class="p">);</span>
          <span class="n">puts</span><span class="p">(</span><span class="n">s</span><span class="p">);</span>
          <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
        <span class="p">}</span>
		<span class="p">...</span>
</code></pre></div></div>
<p>Another input is taken (<em>call it inp3</em>) and then it is checked whether the <code class="language-plaintext highlighter-rouge">and</code> of this input and <code class="language-plaintext highlighter-rouge">1</code> is not equal to zero and the number itself is not 1, if that is true the input is then put into a cluster of functions whose output determines whether the input is correct or not. One possible value for <code class="language-plaintext highlighter-rouge">input3</code> would be <code class="language-plaintext highlighter-rouge">3</code>, remember it for later.
Alright, let’s have a look into each function one by one:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// function is called with input2 as a parameter</span>
<span class="n">__int64</span> <span class="nf">sub_0_1209</span><span class="p">(</span><span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a1</span><span class="p">)</span>
<span class="p">{</span>
  <span class="n">__int64</span> <span class="n">v3</span><span class="p">;</span> <span class="c1">// [rsp+10h] [rbp-8h]</span>

  <span class="n">v3</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span> <span class="n">a1</span> <span class="p">)</span>
  <span class="p">{</span>
    <span class="o">++</span><span class="n">v3</span><span class="p">;</span>
    <span class="n">a1</span> <span class="o">/=</span> <span class="mh">0xAuLL</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="n">v3</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This is another simple function, it’s just counting the number of digits in the input <code class="language-plaintext highlighter-rouge">a1</code>. I can easily tell because it’s incrementing <code class="language-plaintext highlighter-rouge">v3</code> for each digit in <code class="language-plaintext highlighter-rouge">a1</code> returning it (no changes made to <code class="language-plaintext highlighter-rouge">a1</code> because the function is using it’s local copy). I’m not reimplementing few functions after this right now, you’ll know why soon.   <br />
Now observe this pattern of how this function is called:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="n">input3</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">input3</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
      <span class="p">{</span>
        <span class="n">digits_of_inp1</span> <span class="o">=</span> <span class="n">count_digits</span><span class="p">(</span><span class="n">input2</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span> <span class="n">digits_of_inp1</span> <span class="o">==</span> <span class="n">count_digits</span><span class="p">(</span><span class="n">input1</span><span class="p">)</span>
</code></pre></div></div>
<p>So, it’s just checking if the number of digits in <code class="language-plaintext highlighter-rouge">input1</code> is equal to the number of digits in <code class="language-plaintext highlighter-rouge">input2</code>.<br />
Let’s move forward and look at the function calls after this:</p>

<p>After this, another function is called with both <code class="language-plaintext highlighter-rouge">input1</code> and <code class="language-plaintext highlighter-rouge">input2</code> and then checked in same way:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span> <span class="n">digits_of_inp1</span> <span class="o">==</span> <span class="n">count_digits</span><span class="p">(</span><span class="n">input1</span><span class="p">)</span>
          <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v5</span> <span class="o">=</span> <span class="n">sub_0_124D</span><span class="p">(</span><span class="n">input2</span><span class="p">),</span> <span class="n">v5</span> <span class="o">==</span> <span class="n">sub_0_124D</span><span class="p">(</span><span class="n">input1</span><span class="p">))</span>
		<span class="p">...</span>
</code></pre></div></div>
<p>Lets look inside the function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">__int64</span> <span class="kr">__fastcall</span> <span class="nf">sub_0_124D</span><span class="p">(</span><span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a1</span><span class="p">)</span>
<span class="p">{</span>
  <span class="n">__int64</span> <span class="n">v3</span><span class="p">;</span> <span class="c1">// [rsp+10h] [rbp-8h]</span>

  <span class="n">v3</span> <span class="o">=</span> <span class="mi">0LL</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span> <span class="n">a1</span> <span class="p">)</span>
  <span class="p">{</span>
    <span class="n">v3</span> <span class="o">+=</span> <span class="n">a1</span> <span class="o">%</span> <span class="mi">10</span><span class="p">;</span>    <span class="c1">// abc % 10 = c, gets the last number of a sequence of digits</span>
    <span class="n">a1</span> <span class="o">/=</span> <span class="mi">10</span><span class="p">;</span>    <span class="c1">// abc // 10 = ab, removes the last digit so it can operate on the next digit</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="n">v3</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>The function is simply adding every digit of a1 in reverse and returning it. On every iteration, if the number is let’s say <code class="language-plaintext highlighter-rouge">123</code>, it’ll add get <code class="language-plaintext highlighter-rouge">3</code> by doing the <code class="language-plaintext highlighter-rouge">% 10</code> operation and then it adds it to v3, then it removes the last digit, which is <code class="language-plaintext highlighter-rouge">3</code> in this case by the <code class="language-plaintext highlighter-rouge">/= 10</code> operation and continues till there are no digits left in the input. Let’s rename it to <code class="language-plaintext highlighter-rouge">sum</code>. 
Looking at how it’s used, it’s clear that it’s checking the sum of both of these inputs to be the same:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">...</span>
<span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v5</span> <span class="o">=</span> <span class="n">sum</span><span class="p">(</span><span class="n">input2</span><span class="p">),</span> <span class="n">v5</span> <span class="o">==</span> <span class="n">sum</span><span class="p">(</span><span class="n">input1</span><span class="p">))</span>
<span class="p">...</span>
</code></pre></div></div>
<p>Let’s now look at the last function in this if statement:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">...</span>
<span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v6</span> <span class="o">=</span> <span class="n">sub_0_1430</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">input2</span><span class="p">,</span> <span class="n">input3</span><span class="p">),</span> <span class="n">v6</span> <span class="o">==</span> <span class="n">sub_0_1430</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">input1</span><span class="p">,</span> <span class="n">input3</span><span class="p">))</span> <span class="p">)</span>
<span class="p">...</span>
</code></pre></div></div>
<p>This last function is now called with three inputs, the variable which holds the constant 0x1337 (<code class="language-plaintext highlighter-rouge">v10</code>), <code class="language-plaintext highlighter-rouge">input2</code> and <code class="language-plaintext highlighter-rouge">input3</code>, and it’s compared with the call to the same function with just <code class="language-plaintext highlighter-rouge">input1</code> in place of <code class="language-plaintext highlighter-rouge">input2</code>:
Let’s look inside the function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">__int64</span> <span class="kr">__fastcall</span> <span class="nf">sub_0_1430</span><span class="p">(</span><span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a1</span><span class="p">,</span> <span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a2</span><span class="p">,</span> <span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">a3</span><span class="p">)</span>
<span class="p">{</span>
  <span class="kt">unsigned</span> <span class="n">__int64</span> <span class="n">v5</span><span class="p">;</span> <span class="c1">// [rsp+10h] [rbp-18h]</span>
  <span class="n">__int64</span> <span class="n">v6</span><span class="p">;</span> <span class="c1">// [rsp+20h] [rbp-8h]</span>

  <span class="n">v6</span> <span class="o">=</span> <span class="mi">1LL</span><span class="p">;</span>
  <span class="n">v5</span> <span class="o">=</span> <span class="n">a1</span> <span class="o">%</span> <span class="n">a3</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span> <span class="n">a2</span> <span class="p">)</span>
  <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="n">a2</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span> <span class="p">)</span>
      <span class="n">v6</span> <span class="o">=</span> <span class="n">v5</span> <span class="o">*</span> <span class="n">v6</span> <span class="o">%</span> <span class="n">a3</span><span class="p">;</span>
    <span class="n">a2</span> <span class="o">&gt;&gt;=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="n">v5</span> <span class="o">=</span> <span class="n">v5</span> <span class="o">*</span> <span class="n">v5</span> <span class="o">%</span> <span class="n">a3</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="n">v6</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This function is essentially implementing <code class="language-plaintext highlighter-rouge">(a1^a2) % a3</code> (^ for exponent, not for xor). I can easily spot this because I’ve seen this pattern before, it doesn’t matter if you don’t understand it completely because we can just reimplement it in python for our z3 script if we need to.
If the output of this function with these different outputs remains same, we get the flag:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span> <span class="p">(</span><span class="n">input3</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">input3</span> <span class="o">!=</span> <span class="mi">1</span> <span class="p">)</span>
      <span class="p">{</span>
        <span class="n">digits_of_inp1</span> <span class="o">=</span> <span class="n">count_digits</span><span class="p">(</span><span class="n">input2</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span> <span class="n">digits_of_inp1</span> <span class="o">==</span> <span class="n">count_digits</span><span class="p">(</span><span class="n">input1</span><span class="p">)</span>
        <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v5</span> <span class="o">=</span> <span class="n">sum</span><span class="p">(</span><span class="n">input2</span><span class="p">),</span> <span class="n">v5</span> <span class="o">==</span> <span class="n">sum</span><span class="p">(</span><span class="n">input1</span><span class="p">))</span>
        <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">v6</span> <span class="o">=</span> <span class="n">exponent_modulo</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">input2</span><span class="p">,</span> <span class="n">input3</span><span class="p">),</span> <span class="n">v6</span> <span class="o">==</span> <span class="n">exponent_modulo</span><span class="p">(</span><span class="n">v10</span><span class="p">,</span> <span class="n">input1</span><span class="p">,</span> <span class="n">input3</span><span class="p">)))</span>
        <span class="p">{</span>
          <span class="n">puts</span><span class="p">(</span><span class="s">"That looks right to me!"</span><span class="p">);</span>
          <span class="n">stream</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"flag.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">);</span>
          <span class="n">fgets</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="n">stream</span><span class="p">);</span>
          <span class="n">puts</span><span class="p">(</span><span class="n">s</span><span class="p">);</span>
          <span class="k">return</span> <span class="mi">0LL</span><span class="p">;</span>
        <span class="p">}</span>
		<span class="p">...</span>
</code></pre></div></div>
<p>After playing a bit with the solution that I originally came up with, I realized that if I just pass the volcano check with the same inputs (<code class="language-plaintext highlighter-rouge">input1 == input2</code>), I won’t have to deal with all the other checks in that cluster. 
Due to this, I did not reimplement any function after <code class="language-plaintext highlighter-rouge">volcano_check</code> in my final script to save time, however I included the explanations for the sake of completeness and to teach just how to approach challenges like this.
Here’s the final script:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">z3</span>

<span class="c1"># 64 bit input
</span><span class="n">inp1</span> <span class="o">=</span> <span class="n">z3</span><span class="p">.</span><span class="n">BitVec</span><span class="p">(</span><span class="s">"inp1"</span><span class="p">,</span> <span class="mi">64</span><span class="p">)</span>

<span class="c1"># function translated from decompiled c code
</span><span class="k">def</span> <span class="nf">volcano_check</span><span class="p">(</span><span class="n">a1</span><span class="p">):</span>
    <span class="n">v2</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">a1</span><span class="p">:</span>
        <span class="n">v2</span> <span class="o">+=</span> <span class="n">a1</span> <span class="o">&amp;</span> <span class="mi">1</span>
        <span class="n">a1</span> <span class="o">=</span> <span class="n">a1</span> <span class="o">&gt;&gt;</span> <span class="mi">1</span>
    <span class="k">return</span> <span class="mh">0x10</span> <span class="o">&lt;</span> <span class="n">v2</span> <span class="o">&lt;=</span> <span class="mh">0x1A</span>

<span class="n">s</span> <span class="o">=</span> <span class="n">z3</span><span class="p">.</span><span class="n">Solver</span><span class="p">()</span>
<span class="c1"># conditions based on checks from the first function
</span><span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">((</span><span class="n">inp1</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mi">3</span> <span class="o">==</span> <span class="mi">2</span><span class="p">)</span>
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mi">5</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mi">7</span> <span class="o">==</span> <span class="mi">3</span><span class="p">)</span>
<span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">%</span> <span class="mh">0x6D</span> <span class="o">==</span> <span class="mi">55</span><span class="p">)</span>

<span class="c1"># while there are valid solutions
</span><span class="k">while</span> <span class="n">s</span><span class="p">.</span><span class="n">check</span><span class="p">()</span> <span class="o">==</span> <span class="n">z3</span><span class="p">.</span><span class="n">sat</span><span class="p">:</span>
    <span class="n">inp1_solution</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">.</span><span class="n">model</span><span class="p">()[</span><span class="n">inp1</span><span class="p">].</span><span class="n">as_long</span><span class="p">())</span>
    <span class="c1"># checking if any of the solution that passes the constraints
</span>    <span class="c1"># from the first function also passes them for the volcano check func.
</span>    <span class="k">if</span> <span class="n">volcano_check</span><span class="p">(</span><span class="n">inp1_solution</span><span class="p">):</span>
        <span class="c1"># input1 and input 2 can be the same
</span>        <span class="k">print</span><span class="p">(</span><span class="s">"input 1 &amp; 2: "</span><span class="p">,</span> <span class="n">inp1_solution</span><span class="p">)</span>

        <span class="c1"># i &amp; 1 != 0, remember 3?
</span>        <span class="k">print</span><span class="p">(</span><span class="s">"input 3: "</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
        <span class="k">break</span>

	<span class="c1"># if an input is already found but does not pass the check
</span>	<span class="c1"># this prevents it  from using it again 
</span>    <span class="n">s</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">inp1</span> <span class="o">!=</span> <span class="n">s</span><span class="p">.</span><span class="n">model</span><span class="p">()[</span><span class="n">inp1</span><span class="p">])</span>
</code></pre></div></div>
<p>Running this script, we get the value for input 1 and 2: <code class="language-plaintext highlighter-rouge">389970145857386</code> and input 3 is any number whose &amp; with 1 is not zero e.g. 3. 
Now try executing the binary, give it the input and see :o
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fsmt_solved.png" /></p>

<p>And here we go! We’ve solved the challenge using Z3! :D</p>

<h1 id="problems-with-smt-solvers">Problems with SMT solvers</h1>
<p>While SMT solvers may seem very powerful, which they imo, they have their own share of flaws. The major one being something known as path explosions. These are not the only limitations of SMT solvers, there are others too but this is the major bottleneck.</p>

<h2 id="path-explosions">Path explosions</h2>
<p>As the number of variables and constraints from a program grows, the search space grows exponentially, leading to a “explosion” in the number of possible paths the solver has to explore. This makes it difficult for SMT solvers to scale to large, complex programs which take huge inputs of take inputs in loops. 
This problem makes SMT solvers quite unusable in real world software analysis scenarios, there are many workarounds and developments in this area for sure but there’s still a lot of work to be done.</p>

<p>Due to this, SMT solvers may not always be the best tool to use for your specific job, they are not yet a one-size-fits-all thing yet.</p>

<h1 id="summary">Summary</h1>
<p>This post was an overview of SMT solvers with the practical example of a CTF challenge and we also touched a bit on their limitations. I’m not an expert on the topic, I tried to cover all the introductory knowledge that I could put in without increasing the complexity of the blog. There is indeed far more to learn about and you can do so by checking all the links in the resources section.</p>

<h1 id="resources">Resources</h1>
<ul>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyRVZPvHYHzw">Symbolic Execution Lecture from MIT</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fpwn.umasscybersec.org%2Flectures%2Findex.html">Symbolic Execution with Triton Engine</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkZd1Hi0ZBYc">HexRays CTF solution with Z3</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fp.ost2.fyi%2Fcourses%2Fcourse-v1%3AOpenSecurityTraining2%2BRE3201_symexec%2B2021_V1%2Fcourse%2F">OST2 Course on Symbolic Analysis (teaches angr)</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fz3prover.github.io%2Fpapers%2F">Papers by Z3 team</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fstudenttheses.uu.nl%2Fbitstream%2Fhandle%2F20.500.12932%2F35856%2Fthesis.pdf%3Fsequence%3D1%26amp%3BisAllowed%3Dy">The Path Explosion Problem in Symbolic Execution - Paper</a></li>
</ul>]]></content><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><category term="WinAPI" /><category term="Windows API Series" /><category term="Windows Internals Series" /><summary type="html"><![CDATA[A short overview of SMT solvers with an introduction to Z3 with examples.]]></summary></entry><entry><title type="html">Exploring the process of virtual memory address translation and structure of a page table entry.</title><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FVirtual-Address-Translation-and-structure-of-PTE%2F" rel="alternate" type="text/html" title="Exploring the process of virtual memory address translation and structure of a page table entry." /><published>2022-04-15T03:33:00+00:00</published><updated>2022-04-15T03:33:00+00:00</updated><id>https://de-engineer.github.io/Virtual-Address-Translation-and-structure-of-PTE</id><content type="html" xml:base="https://de-engineer.github.io/Virtual-Address-Translation-and-structure-of-PTE/"><![CDATA[<p>We learned about the fundamentals of virtual memory management in the last post, as well as two Windows API functions that allow us to allocate virtual memory (<code class="language-plaintext highlighter-rouge">VirtualAlloc</code>) and free it (<code class="language-plaintext highlighter-rouge">VirtualFree</code>).  <br />
In this blog, we’ll continue our exploration of virtual memory management in Windows by learning about the how does a virtual memory address translate to a physical address, the structure of a page table in memory (explained later), what information it contains, and how we can use Window API functions to query that information and some other internals regarding the workings of virtual memory in Windows.</p>

<p>Table of contents:</p>

<ul id="markdown-toc">
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23translation-of-virtual-memory-address" id="markdown-toc-translation-of-virtual-memory-address">Translation of virtual memory address</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23understanding-the-structure-of-a-pte" id="markdown-toc-understanding-the-structure-of-a-pte">Understanding the structure of a PTE</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23hardware-bits-vs-software-bits-in-page-table-entries" id="markdown-toc-hardware-bits-vs-software-bits-in-page-table-entries">Hardware bits vs. Software bits in Page Table Entries</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23understanding-the-bits" id="markdown-toc-understanding-the-bits">Understanding the bits</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23getlasterror" id="markdown-toc-getlasterror">GetLastError</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%231-virtualquery" id="markdown-toc-1-virtualquery">1. VirtualQuery</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23function-signature" id="markdown-toc-function-signature">Function signature</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23arguments" id="markdown-toc-arguments">Arguments</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23return-value" id="markdown-toc-return-value">Return value</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23examples" id="markdown-toc-examples">Examples</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23example-1" id="markdown-toc-example-1">Example #1</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23results-1" id="markdown-toc-results-1">Results #1</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23example-2" id="markdown-toc-example-2">Example #2</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23result-2" id="markdown-toc-result-2">Result #2</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23summary" id="markdown-toc-summary">Summary</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources" id="markdown-toc-resources">Resources</a></li>
</ul>

<h1 id="translation-of-virtual-memory-address">Translation of virtual memory address</h1>
<p>When a virtual memory address gets translated, it goes through several different translation layers where each time it’s translated, it points to a new table (which can be thought of as a structure) which also points to another table and this process is repeated until it finally gets translated into an address in the actual physical memory (RAM). The <strong>translation</strong> of these pages is done by the Memory Management Unit (MMU) of the CPU and their <strong>management</strong> is done by the Memory Manager (a component of the Windows OS). On x64 Windows, there are four tables that do this job, namely:</p>
<ul>
  <li>Page Map Level 4 (PML4)</li>
  <li>Page Directory Pointer Table (PDPT)</li>
  <li>Page Directory Table (PDT)</li>
  <li>Page Table (PT)</li>
</ul>

<p>Each of these tables contain indexes that point to the start of the next paging structure. Each of these paging structures have 512 entries. These indexes are called Page Frame Numbers (PFN) and the entries themselves are called as PxE, where x is the name of the table and E means entry, so entries inside the PML4 will be called PML4E (x = ML4), for Page Tables it will be PTE and so on.   <br />
This can be visually understood by looking at this diagram:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fvirtual_memory_translation_on_x64.png" alt="Virtual Memory Translation on x64 Windows" width="800" class="align-center" />  <br />
This image is probably more confusing than what you read before watching this, but let me explain so you can feel cool and get some dopamine hits.  <br />
This is <del>simply</del> the translation process of a virtual memory address. On the top, you can see the distribution of 48 bits (0 to 47) into division of 9 bits with one exception of 12 bits (explained later), and since we already know that on x64 systems, the addressing only happens for 48 bits, this makes sense. This explains that this top part of this <del>fancy looking</del> image is basically showing you the distribution of those bits. <br />
Below them are the tables that I just talked about, you can see how each of them are pointing to some other table in coordination with the information inside the virtual memory address to finally translate to a physical memory address.</p>

<p>You might now have a guess of where this is going and how does the address translation takes place. Different bits inside a virtual memory address are distributed into parts and those parts contains data that tells the MMU where to look for the next entry in the next table until it finds a physical page after looking at finding the entry in the Page Table.</p>

<p>Now, let’s look into this distribution of bits and understand it’s work.  <br />
The first division starts from the 39th bit to 47th bit, which is a index inside the Page Map Level 4 paging structure (the address of this structure is stored in a special register, will be deeply described in a later post) and the entry at that index contains a PFN that tells the MMU where PDPT is and similarly, the bits from 30th position to 38th position tells the MMU the index of the entry inside PDPT that points to the next paging structure and this process continues until we reach the Page Table.  <br />
Once the translation process has reached the point where it has found the entry inside the Page Table which points to the address of a physical page in the RAM, the left 12 bits are used to index a specific byte in the physical page to get the exact needed data that was requested.</p>

<h1 id="understanding-the-structure-of-a-pte">Understanding the structure of a PTE</h1>
<p>Each Page Table entry has some status and protection bits set, which store information regarding the page itself. These entries tell the MMU how these pages should be managed and what is their current status.  <br />
This is how a x64 PTE looks like:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fpage-table-entry.png" alt="A Page Table entry on x64 Windows" width="800" class="align-center" />  <br />
As you can see, there are multiple bits (some are grouped others are not) and each of have some information regarding the page itself or it’s status. Let us understand each of them one by one so we can have a clear understanding of a Page Table entry’s structure.</p>

<h2 id="hardware-bits-vs-software-bits-in-page-table-entries">Hardware bits vs. Software bits in Page Table Entries</h2>
<p>Before talking about these bits themselves, let us understand the types of bits that are inside a PTE.  <br />
<strong>Hardware</strong> bits: Hardware bits are the bits that the MMU actually takes in consideration while translating a virtual address into a physical address.  <br />
<strong>Software</strong> and <strong>Reserved</strong> bits: These are the bits that are totally ignored by the MMU and actually used by the Memory Manager to manage pages. If you look in the diagram, you will find that bit 9 to 11 are marked as Software bits which means they are used by the Memory Manager.</p>

<h1 id="understanding-the-bits">Understanding the bits</h1>
<p><code class="language-plaintext highlighter-rouge">Valid</code> bit: The bit at the 0th index is the <code class="language-plaintext highlighter-rouge">Valid</code> bit which tells the MMU that the page for which this page table entry is, actually exists somewhere in the physical RAM and it is not paged out (explained in part one of this blog). This bit is useful because as we know, Windows uses demand paging and since some pages might not be used by a process but they might still be allocated then it’s certain that the Memory Manager will page out the unused pages from the memory to the disk. This bit helps the Memory Manager to keep track of paged and non paged memory pages.</p>

<p><code class="language-plaintext highlighter-rouge">Write</code> bit: The bit at the 1st index is the <code class="language-plaintext highlighter-rouge">Write</code> bit which tells the MMU that whether the page is writeable or not. When this bit is clear (set to 0), the page is read-only and when this bit is set, we are allowed to write to that page. You can relate this with the information from the last blog post, we used the <code class="language-plaintext highlighter-rouge">flProtect</code> argument of the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function to specify the memory protections that we wanted while allocating a page and if we use any protection that allows writing of the page then this bit will be set to 1.</p>

<p><code class="language-plaintext highlighter-rouge">Owner</code> bit: The bit at the 2nd index is the <code class="language-plaintext highlighter-rouge">Owner</code> bit which tells the MMU whether the page is allowed to be accessed from the user mode or if it’s access is limited to the kernel mode. If this bit is set in the pte of a page then that page will be accessible from the user mode and if it’s not set then that page will only be accessible in the kernel mode.</p>

<p><code class="language-plaintext highlighter-rouge">Write Through</code> bit: The bit at the 3rd index is the <code class="language-plaintext highlighter-rouge">Write Through</code> bit which tells the MMU to enable write through on the page. Write through is a storage method in which data is written into the cache and the corresponding main memory location at the same time. The cached data allows for fast retrieval on demand, while the same data in main memory ensures that nothing will get lost if a crash, power failure, or other system disruption occurs.</p>

<p><code class="language-plaintext highlighter-rouge">Cache Disabled</code> bit: The bit at the 4th index is the <code class="language-plaintext highlighter-rouge">Cache Disabled</code> bit which tells the MMU that this page should not be cached.</p>

<p><code class="language-plaintext highlighter-rouge">Accessed</code> bit: The bit at the 5th index is the <code class="language-plaintext highlighter-rouge">Accessed</code> bit which tells the MMU that this page has been accessed at least once after being mapped.</p>

<p><code class="language-plaintext highlighter-rouge">Dirty</code> bit: The bit at the 6th index is the <code class="language-plaintext highlighter-rouge">Dirty</code> bit which tells the MMU that this page has been written to (there has been a write operation on this page).</p>

<p><code class="language-plaintext highlighter-rouge">Large</code> bit: The bit at the 7th index is the <code class="language-plaintext highlighter-rouge">Large</code> bit which tells the MMU that this page is a large page and it maps to a page that is larger than 4KB.</p>

<p><code class="language-plaintext highlighter-rouge">Global</code> bit: The bit at the 8th index is the <code class="language-plaintext highlighter-rouge">Global</code> bit which tells the MMU that this page should not be flushed to the Translation Lookaside Buffer (a caching system for recently used pages).</p>

<p><code class="language-plaintext highlighter-rouge">Copy-on-write</code> bit (Software): The bit at the 9th index is the <code class="language-plaintext highlighter-rouge">Copy-on-write</code> bit, which is a Software bit and it has a special purpose. When a thread tries to access a page that is read-only (has the write bit set to 0), a memory-management exception occurs. Along with this, the Memory Manager’s fault handler checks if the <code class="language-plaintext highlighter-rouge">Copy-on-write</code> bit is set, if it is set then it makes a copy of that page and gives that thread the access of that copy and this copy has write access enabled so that thread will now be able to write to that data but those writes won’t affect the original page which doesn’t has the write bit set. However, if a thread tries to access a read-only page and this bit is not set then it raises the access violation exception.</p>

<p><code class="language-plaintext highlighter-rouge">Prototype</code> bit (Software): The bit at the 10th index is the <code class="language-plaintext highlighter-rouge">Prototype</code> bit, which is also a Software bit and this bit is used to mark a page as a “Prototype”. This is a bit complex concept and to better understand it, you can check the <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources">resources</a> section.</p>

<p><code class="language-plaintext highlighter-rouge">Write</code> bit (Software): The bit at the 11th index is the <code class="language-plaintext highlighter-rouge">Write</code> bit, which is the last Software bit in a x64 PTE and this bit also has a quite unique usage. This may feel strange to know after everything you have learned but actually, when a page is allocated, whether it was supposed to be writeable or not, the Memory Manager <strong>initially</strong> sets the write (hardware) bit to 0, which means that all the pages are not writeable on the time of initialization and the actual way the Memory Manager knows that if a page is writeable or not is by using the 11th bit (Software <code class="language-plaintext highlighter-rouge">Write</code> bit). Since, the hardware write bit is set 0, every time a thread tries to write to any page for the first time, a Memory Management exception occurs and the Memory Manager checks if the bit 11 (Software <code class="language-plaintext highlighter-rouge">Write</code> bit) is set, if it is then it gets to know that this page is actually writeable, then it sets the <code class="language-plaintext highlighter-rouge">Dirty</code> bit and <code class="language-plaintext highlighter-rouge">Write</code> hardware bit to 1 and updates some other Memory Management information and then it dismisses the exception and then the write operation happens normally. This happens only on the first write operation on a page as the hardware write bit gets set to 1 after this process is done.  <br />
The reason it is implemented in this way is related to the existence of multiprocessors and can be understood better by reading the “Address translation” section of the Windows Internals, Part 1 7th edition book.</p>

<p><code class="language-plaintext highlighter-rouge">PFN</code>: The 36 bits from the 12th index to the 47th index are the page frame number that we talked about earlier.</p>

<p><code class="language-plaintext highlighter-rouge">Reserved</code>: These bits from 47th index to 62nd index are completely ignored by the MMU and only used by the Memory Manager for special purposes.</p>

<p><code class="language-plaintext highlighter-rouge">NX</code> bit: The last and 63rd bit in a pte is the <code class="language-plaintext highlighter-rouge">NX</code> bit. <code class="language-plaintext highlighter-rouge">NX</code> stands for “no-execute” and it tells the MMU whether this page can be executed or not.</p>

<p>Now, since you now have the knowledge of the translation process of a virtual memory address as well the structure of a hardware PTE and you know what information it stores, it’s time for you to learn about another Windows API function which allows us to query information about a page.</p>

<h1 id="getlasterror">GetLastError</h1>
<hr />
<p>Before we start, I would like to introduce you to a function from the Windows API, it is <code class="language-plaintext highlighter-rouge">GetLastError</code>. It is used to get <strong>the <em>error code</em> of the last error that occurred</strong> and we can get more information about the error code by looking at the error code list which is available at msdn here :
<a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fdebug%2Fsystem-error-codes%23system-error-codes-1">System Error Codes - Win32 apps</a>  <br />
We will be using this function in the code examples to see if there are any errors in our code.</p>

<h1 id="1-virtualquery">1. VirtualQuery</h1>
<hr />
<p>This function is used to query the information of a virtual memory region (page).</p>

<h4 id="function-signature">Function signature</h4>
<p>This is the syntax for <code class="language-plaintext highlighter-rouge">VirtualQuery</code> function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">SIZE_T</span> <span class="nf">VirtualQuery</span><span class="p">(</span>
  <span class="n">LPCVOID</span>                   <span class="n">lpAddress</span><span class="p">,</span>
  <span class="n">PMEMORY_BASIC_INFORMATION</span> <span class="n">lpBuffer</span><span class="p">,</span>
  <span class="n">SIZE_T</span>                    <span class="n">dwLength</span>
<span class="p">);</span>
</code></pre></div></div>
<h4 id="arguments">Arguments</h4>
<p>The function’s return type is <code class="language-plaintext highlighter-rouge">SIZE_T</code>, it’s basically an <code class="language-plaintext highlighter-rouge">unsigned int</code>.</p>

<p><strong>lpAddress</strong>: You might already know the use of this argument if you have read the part one of this blog, it’s basically the base address of Virtual Memory region that we allocated which is returned by <code class="language-plaintext highlighter-rouge">VirtualAlloc</code>.</p>

<p><strong>lpBuffer</strong>: This argument is a pointer to a struct. The name of this struct is <code class="language-plaintext highlighter-rouge">_MEMORY_BASIC_INFORMATION</code>,  it is defined in <code class="language-plaintext highlighter-rouge">winint.h</code>. Here is how it looks like:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="n">_MEMORY_BASIC_INFORMATION</span> <span class="p">{</span>
  <span class="n">PVOID</span>  <span class="n">BaseAddress</span><span class="p">;</span>
  <span class="n">PVOID</span>  <span class="n">AllocationBase</span><span class="p">;</span>
  <span class="n">DWORD</span>  <span class="n">AllocationProtect</span><span class="p">;</span>
  <span class="n">WORD</span>   <span class="n">PartitionId</span><span class="p">;</span>
  <span class="n">SIZE_T</span> <span class="n">RegionSize</span><span class="p">;</span>
  <span class="n">DWORD</span>  <span class="n">State</span><span class="p">;</span>
  <span class="n">DWORD</span>  <span class="n">Protect</span><span class="p">;</span>
  <span class="n">DWORD</span>  <span class="n">Type</span><span class="p">;</span>
<span class="p">}</span> <span class="n">MEMORY_BASIC_INFORMATION</span><span class="p">,</span> <span class="o">*</span><span class="n">PMEMORY_BASIC_INFORMATION</span><span class="p">;</span>
</code></pre></div></div>
<p>I’ll explain it’s members later.</p>

<p><code class="language-plaintext highlighter-rouge">dwLength</code>: This argument is the <code class="language-plaintext highlighter-rouge">size of</code> the struct from the last argument.</p>

<h2 id="return-value">Return value</h2>
<p>Instead of returning anything, the function just updates the struct that we had created.</p>

<h1 id="examples">Examples</h1>
<p>As we have learned enough about the function, let’s take a look at some examples and see the function and it’s working in action.</p>

<h2 id="example-1">Example #1</h2>
<p>Now as we have done with understanding of the function, we’ll see some code examples of the function. We are going to make a program that will give us the information about a memory region that we’ll allocate using the functions that we learned about in the last blog post. Let me show you the code first, then I will explain it:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;Windows.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">MEMORY_BASIC_INFORMATION</span> <span class="n">info</span><span class="p">;</span> 
    <span class="kt">int</span> <span class="n">ret</span><span class="p">;</span>
    <span class="kt">int</span> <span class="o">*</span><span class="n">vm</span> <span class="o">=</span> <span class="n">VirtualAlloc</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_COMMIT</span><span class="p">,</span> <span class="n">PAGE_READONLY</span><span class="p">);</span> <span class="c1">// 8 byte allocation.</span>
    <span class="n">ret</span> <span class="o">=</span> <span class="n">VirtualQuery</span><span class="p">(</span><span class="n">vm</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">info</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">info</span><span class="p">));</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ret</span><span class="p">)</span> <span class="c1">// error checking.</span>
    <span class="p">{</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"VirtualQuery failed</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"The error code for the last error was %d"</span><span class="p">,</span> <span class="n">GetLastError</span><span class="p">());</span>
        <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">switch</span> <span class="p">(</span><span class="n">info</span><span class="p">.</span><span class="n">AllocationProtect</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">case</span> <span class="n">PAGE_EXECUTE_READ</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Protection type : EXECUTE + READ</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">PAGE_READWRITE</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Protection type : READ + WRITE</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">PAGE_READONLY</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Protection type : READ</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="nl">default:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Not found"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">switch</span> <span class="p">(</span><span class="n">info</span><span class="p">.</span><span class="n">State</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">case</span> <span class="n">MEM_COMMIT</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Region State : Committed"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">MEM_FREE</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Region State : Free"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">MEM_RESERVE</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Region State : Reserve"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="nl">default:</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">VirtualFree</span><span class="p">(</span><span class="n">vm</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_RELEASE</span><span class="p">);</span> <span class="c1">// free the allocated memory.</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>I have used <code class="language-plaintext highlighter-rouge">Windows.h</code> instead of using any other header file because <code class="language-plaintext highlighter-rouge">Windows.h</code> contains almost everything that we need for doing Windows API programming. <br />
Let’s now understand the code.   <br />
First, we have declared a struct of type <code class="language-plaintext highlighter-rouge">MEMORY_BASIC_INFORMATION</code>, which is the struct that we talked about, then we committed eight <em>bytes</em> of virtual memory which is read-only.  <br />
After that, we have used <code class="language-plaintext highlighter-rouge">VirtualQuery</code> function to get information about that memory region.  <br />
We gave it the address of the allocated memory region as our first parameter, then we gave the address of the <code class="language-plaintext highlighter-rouge">info</code> struct that will hold all the returned data from this function, then we gave it the <code class="language-plaintext highlighter-rouge">size of</code> our info struct.  <br />
Then, we are doing a check if the function is failed, If it’s failed then the error code can be found by using the <code class="language-plaintext highlighter-rouge">GetLastError</code> function.  <br />
Then, we have a switch-case clause, where we are checking the value of <code class="language-plaintext highlighter-rouge">AllocationProtect</code> member of our <code class="language-plaintext highlighter-rouge">info</code> struct. This switch-case clause will check for the protection type of the virtual memory region that was specified as the first parameter.  <br />
The constants that are being used to compare in the switch-case clause are defined in the <code class="language-plaintext highlighter-rouge">Windows.h</code> header file that we included. <br />
We are then checking the value of <code class="language-plaintext highlighter-rouge">State</code> member from our <code class="language-plaintext highlighter-rouge">info</code> struct. This switch-case clause is comparing the state of the allocated virtual memory region. Then, we are just printing information according to the statements. One thing to note is that we cannot compare the value with every type of protection type or every type of memory state, I have tried doing so but I was unsuccessful, so I am have just used the types that can be compared.  <br />
Then we just free the allocated memory.</p>

<h2 id="results-1">Results #1</h2>
<p>Here’s the output that I get after running the example:</p>
<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>./vquery-example
<span class="go">Protection type : READ
Region State : Committed
</span></code></pre></div></div>

<p>The results are expected, we had hardcoded the page protection to be read-only and the page state to committed and the result by the function is precise.</p>

<h2 id="example-2">Example #2</h2>
<p>This example will be quite fun. Here, I am asking the user to select which page state and page protection they want for the page and then using <code class="language-plaintext highlighter-rouge">VirtualQuery</code> to query the information of the allocated page and then printing it to verify with the input user gave. Here’s the code for it:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;Windows.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">MEMORY_BASIC_INFORMATION</span> <span class="n">info</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">ret</span><span class="p">;</span>

    <span class="kt">char</span> <span class="n">state</span><span class="p">;</span>         <span class="c1">// used for input</span>
    <span class="kt">char</span> <span class="n">protection</span><span class="p">;</span>    <span class="c1">// used for input</span>
    <span class="kt">int</span> <span class="n">MEM_STATE</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">MEM_PROTECTION</span><span class="p">;</span>

    <span class="n">printf</span><span class="p">(</span><span class="s">"Choose the page state you want to use: </span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"1. MEM_COMMIT</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"2. MEM_RESERVE</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">scanf</span><span class="p">(</span><span class="s">"%c"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">state</span><span class="p">);</span>
    <span class="n">getchar</span><span class="p">();</span>

    <span class="k">switch</span> <span class="p">(</span><span class="n">state</span><span class="p">)</span>      <span class="c1">// checking user input.</span>
    <span class="p">{</span>
    <span class="k">case</span> <span class="sc">'1'</span><span class="p">:</span>
        <span class="n">MEM_STATE</span> <span class="o">=</span> <span class="n">MEM_COMMIT</span><span class="p">;</span>  
        <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="sc">'2'</span><span class="p">:</span>
        <span class="n">MEM_STATE</span> <span class="o">=</span> <span class="n">MEM_RESERVE</span><span class="p">;</span>        
        <span class="k">break</span><span class="p">;</span>
    <span class="nl">default:</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"Invalid choice!"</span><span class="p">);</span>
        <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>
    
    <span class="n">printf</span><span class="p">(</span><span class="s">"Choose the page protection you want to use: </span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"1. PAGE_READONLY</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"2. PAGE_READWRITE</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"3. PAGE_EXECUTE_READ</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">scanf</span><span class="p">(</span><span class="s">"%c"</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">protection</span><span class="p">);</span>

    <span class="k">switch</span> <span class="p">(</span><span class="n">protection</span><span class="p">)</span> 
    <span class="p">{</span>
    <span class="k">case</span> <span class="sc">'1'</span><span class="p">:</span>
        <span class="n">MEM_PROTECTION</span> <span class="o">=</span> <span class="n">PAGE_READONLY</span><span class="p">;</span>        
        <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="sc">'2'</span><span class="p">:</span>
        <span class="n">MEM_PROTECTION</span> <span class="o">=</span> <span class="n">PAGE_READWRITE</span><span class="p">;</span>        
        <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="sc">'3'</span><span class="p">:</span>
        <span class="n">MEM_PROTECTION</span> <span class="o">=</span> <span class="n">PAGE_EXECUTE_READ</span><span class="p">;</span>        
        <span class="k">break</span><span class="p">;</span>
    <span class="nl">default:</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"Invalid choice!"</span><span class="p">);</span>
        <span class="n">exit</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">// allocating memory.</span>
    <span class="kt">int</span> <span class="o">*</span><span class="n">vm</span> <span class="o">=</span> <span class="n">VirtualAlloc</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_STATE</span><span class="p">,</span> <span class="n">MEM_PROTECTION</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Address of memory returned by VirtualAlloc is %lu</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">vm</span><span class="p">);</span>

    <span class="c1">//querying data about that memory.  </span>
    <span class="n">ret</span> <span class="o">=</span> <span class="n">VirtualQuery</span><span class="p">(</span><span class="n">vm</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">info</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">info</span><span class="p">));</span>
    
    <span class="c1">// error checking.</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ret</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"VirtualQuery failed</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"The error code for the last error was %d"</span><span class="p">,</span> <span class="n">GetLastError</span><span class="p">());</span>
        <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">printf</span><span class="p">(</span><span class="s">"Protection type : "</span><span class="p">);</span>
    
    <span class="k">switch</span> <span class="p">(</span><span class="n">info</span><span class="p">.</span><span class="n">AllocationProtect</span><span class="p">)</span> <span class="c1">// comparing protection.</span>
    <span class="p">{</span>
        <span class="k">case</span> <span class="n">PAGE_EXECUTE_READ</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"EXECUTE + READ</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">PAGE_READWRITE</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"READ + WRITE</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">PAGE_READONLY</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"READ ONLY</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">PAGE_GUARD</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Guard Page</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="nl">default:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"%x</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">info</span><span class="p">.</span><span class="n">AllocationProtect</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">printf</span><span class="p">(</span><span class="s">"Region State : "</span><span class="p">);</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">info</span><span class="p">.</span><span class="n">State</span><span class="p">)</span> <span class="c1">// comparing state.</span>
    <span class="p">{</span>
        <span class="k">case</span> <span class="n">MEM_COMMIT</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Committed"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">MEM_FREE</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Free"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">MEM_RESERVE</span><span class="p">:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Reserve"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
        <span class="nl">default:</span>
            <span class="n">printf</span><span class="p">(</span><span class="s">"Unknown"</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">VirtualFree</span><span class="p">(</span><span class="n">vm</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_DECOMMIT</span><span class="p">);</span> <span class="c1">// free the allocated memory.</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Most part of the code is similar to the code from the last example, but there are some major changes.</p>

<p>First, we are asking the user to choose which page state they want to allocate, then we are storing their input in a character variable <code class="language-plaintext highlighter-rouge">state</code>, then we are taking that input variable <code class="language-plaintext highlighter-rouge">state</code> and comparing it in a switch-case clause to find out which page state the user asked for, then we are setting an integer variable <code class="language-plaintext highlighter-rouge">MEM_STATE</code> to the constant of the page state which the user asked for and then we did the same for page protection by using the <code class="language-plaintext highlighter-rouge">protection</code> character variable for input and <code class="language-plaintext highlighter-rouge">MEM_PROTECTION</code> for storing the constant.   <br />
Next, we are allocating memory using those variables (<code class="language-plaintext highlighter-rouge">MEM_STATE</code> and <code class="language-plaintext highlighter-rouge">MEM_PROTECTION</code>) as parameters for <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> and then we are taking the address returned by <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> and querying the information about it from <code class="language-plaintext highlighter-rouge">VirtualQuery</code>, then comparing it possible constants and printing it’s state and protection.</p>

<h3 id="result-2">Result #2</h3>
<p>Here’s the output of the program:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Choose</span> <span class="n">the</span> <span class="n">page</span> <span class="n">state</span> <span class="n">you</span> <span class="n">want</span> <span class="n">to</span> <span class="n">use</span><span class="o">:</span> 
<span class="mf">1.</span> <span class="n">MEM_COMMIT</span> 
<span class="mf">2.</span> <span class="n">MEM_RESERVE</span>
<span class="mi">1</span>
<span class="n">Choose</span> <span class="n">the</span> <span class="n">page</span> <span class="n">protection</span> <span class="n">you</span> <span class="n">want</span> <span class="n">to</span> <span class="n">use</span><span class="o">:</span> 
<span class="mf">1.</span> <span class="n">PAGE_READONLY</span>
<span class="mf">2.</span> <span class="n">PAGE_READWRITE</span>
<span class="mf">3.</span> <span class="n">PAGE_EXECUTE_READ</span>
<span class="mi">2</span>
<span class="n">Address</span> <span class="n">of</span> <span class="n">memory</span> <span class="n">returned</span> <span class="n">by</span> <span class="n">VirtualAlloc</span> <span class="n">is</span> <span class="mi">131072</span>
<span class="n">Protection</span> <span class="n">type</span> <span class="o">:</span> <span class="n">READ</span> <span class="o">+</span> <span class="n">WRITE</span>
<span class="n">Region</span> <span class="n">State</span> <span class="o">:</span> <span class="n">Committed</span>
</code></pre></div></div>
<p>Cool!, it works as expected.</p>

<h1 id="summary">Summary</h1>
<p>In this post, we have learned about a lot of complex things related to Windows Virtual Memory Management. We learned about the four paging structures that are used during the translation process of a virtual memory address and the process of translation itself, then we learned about the complex structure of a Page Table Entry and then finally we learned about how we can get the error code of the last error using the <code class="language-plaintext highlighter-rouge">GetLastError</code> function, then we learned about the <code class="language-plaintext highlighter-rouge">VirtualQuery</code> function and how we can use it to query the information of a virtual memory region and then we made two small projects to see that in action. I hope you enjoyed the blog post and learned something new!  <br />
Thank you for reading!</p>

<h1 id="resources">Resources</h1>
<ul>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fmemoryapi%2Fnf-memoryapi-virtualquery">VirtualQuery - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fmemoryapi%2F">memoryapi.h - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fdebug%2Fsystem-error-codes%23system-error-codes-1">System Error Codes - Win32 apps</a></li>
  <li><a href="iframe.php?url=http%3A%2F%2Fresidentmemory.blogspot.com%2F2011%2F06%2Fprototype-pte-and-sharing-memory.html">Prototype PTE in Windows</a></li>
</ul>]]></content><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><category term="WinAPI" /><category term="Windows API Series" /><category term="Windows Internals Series" /><summary type="html"><![CDATA[We will explore the process of address translation of VAs, what information they store and how can we use Windows API functions to query information of pages. Part 2 of last blog post.]]></summary></entry><entry><title type="html">Exploring Virtual Memory and the Virtual Memory Management API.</title><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FUnderstanding-Virtual-Memory-Paging-and-other-memory-related-concepts%2F" rel="alternate" type="text/html" title="Exploring Virtual Memory and the Virtual Memory Management API." /><published>2022-01-26T03:33:00+00:00</published><updated>2022-01-26T03:33:00+00:00</updated><id>https://de-engineer.github.io/Understanding-Virtual-Memory-Paging-and-other-memory-related-concepts</id><content type="html" xml:base="https://de-engineer.github.io/Understanding-Virtual-Memory-Paging-and-other-memory-related-concepts/"><![CDATA[<p>If you have ever explored Windows Internals or just the internal workings of an Operating System or Computer, you must have heard of the term “Virtual Memory” or “Paging” somewhere because these are some of the most important concepts of an Operating System and these are the concepts which we are going to explore in this blog post. Of course, I won’t be able to cover the whole concepts but I’ll try to give you basic understanding of every concept I talk about and I will also link to the resources that explain each concept in detail in the <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources">resources</a> section.</p>

<p>Table of contents:</p>

<ul id="markdown-toc">
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23virtual-memory" id="markdown-toc-virtual-memory">Virtual Memory</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23paging" id="markdown-toc-paging">Paging</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23page-states" id="markdown-toc-page-states">Page states</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23memory-manager-in-windows" id="markdown-toc-memory-manager-in-windows">Memory Manager in Windows</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23memory-mapped-files" id="markdown-toc-memory-mapped-files">Memory-Mapped files</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23page-sharing" id="markdown-toc-page-sharing">Page sharing</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-virtual-memory-management-api" id="markdown-toc-the-virtual-memory-management-api">The Virtual Memory Management API</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%231-virtualalloc" id="markdown-toc-1-virtualalloc">1. VirtualAlloc</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23function-signature" id="markdown-toc-function-signature">Function signature</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23arguments" id="markdown-toc-arguments">Arguments</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23what-does-committing-memory-actually-means" id="markdown-toc-what-does-committing-memory-actually-means">What does committing memory actually means?</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23return-value" id="markdown-toc-return-value">Return value</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%232-virtualfree" id="markdown-toc-2-virtualfree">2. VirtualFree</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23function-signature-1" id="markdown-toc-function-signature-1">Function signature</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23arguments-1" id="markdown-toc-arguments-1">Arguments</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23return-value-1" id="markdown-toc-return-value-1">Return value</a></li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23examples" id="markdown-toc-examples">Examples</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23example-1" id="markdown-toc-example-1">Example #1</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23results-1" id="markdown-toc-results-1">Results #1</a></li>
        </ul>
      </li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23example-2" id="markdown-toc-example-2">Example #2</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23results-2" id="markdown-toc-results-2">Results #2</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23summary" id="markdown-toc-summary">Summary</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources" id="markdown-toc-resources">Resources</a></li>
</ul>

<h1 id="virtual-memory">Virtual Memory</h1>
<p>We often use the term “memory” (in context of computers) to refer to the RAM or some data stored in the RAM but behind the scenes, there is a lot going on that actually makes memory a thing and one of the many component behind this is the concept of virtual memory.    <br />
If you are familiar with pointers or assembly, you might already have seen memory addresses like this:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">0</span><span class="nf">xFFFFDEADC0DE</span>
</code></pre></div></div>
<p>This is an example of a virtual memory address (or simply a virtual address). These virtual memory addresses don’t <strong>point</strong> to a place in the physical RAM installed on your computer, in reality they only contain information which is used to translate (convert) this address into physical memory address (addresses which point to physical memory). This is achieved by the combined workings of both the CPU and the Memory Manager.</p>

<h1 id="paging">Paging</h1>
<p>Paging is a mechanism that is used by Windows to implement virtual memory. In paging, Virtual memory and physical memory both are divided into 4KB chunks (regions/parts), these chunks are called Pages (virtual memory chunks) and page frames (physical memory chunks). There are also large pages and huge pages but I won’t cover them in this blog post.  <br />
Windows uses two types of paging which are known as <strong>Disc Paging</strong> and <strong>Demand Paging</strong> with clustering.  <br />
In disc paging, whenever there is requirement of more physical memory (RAM) than what is actually available on the system, the memory manager (explained later) moves pages from the RAM (which are unused) to special files called page files into the disk to free up memory. This process of moving data from RAM to disc is called paging out memory or swapping. Paging out a memory region does not delete it from the memory, it’s addresses are still valid and whenever some code (instruction) tries to access some data that is not in the physical memory but is paged out (moved to the paging file), the Memory Manager generates a <em>page fault</em> (an exception which says that the memory region is not accessible) which is then handled by the OS, the OS takes that page from the disk (paging file) and moves it back into the physical memory and restarts (re-excutes) the instruction that wanted to access that memory. However, in clustering, instead of bringing back only the page that the fault requested, the memory manager also brings the pages surrounding the page that the fault requested.  <br />
In demand paging, whenever a process tries to allocate memory, the memory manager doesn’t really allocate any memory but it still returns a pointer to some memory, which is actually not yet allocated, it gets allocated only when after it is accessed. Memory is not allocated -&gt; Process accesses the non existent memory so page fault happens -&gt; Windows allocates the memory and allows you to use it. This method is used because programs may allocate memory that they will never access or use and having this kind of pages in the memory will only waste the demand paging allows the system to save unused memory.  <br />
Each 64 bit process on Windows is allowed to use 256 TB of virtual memory addresses but this memory is divided into different sized regions, some of which is used by the system and some of it is allowed to be used by a process. Here is a diagram of the division:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fmemory-division-x64.png" width="400px" /></p>

<h2 id="page-states">Page states</h2>
<p>A page can be in one of the three states:</p>

<p class="align-center"><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fpage-states.png" width="900px" /></p>

<h1 id="memory-manager-in-windows">Memory Manager in Windows</h1>
<p>All the management of the virtual memory and virtual addresses is done by the Memory Manager, which is a part of the Windows executive (kernel component). Here are the specific tasks of the memory manager:</p>
<ul>
  <li>Telling the MMU how to translate a virtual memory address to a physical memory address.</li>
  <li>Performing paging.</li>
  <li>Allocation, Reservation, Freeing of virtual memory.</li>
  <li>Handling page faults.</li>
  <li>Managing page files.</li>
  <li>Providing a userland API for allocation, reservation and freeing of virtual memory.</li>
</ul>

<h1 id="memory-mapped-files">Memory-Mapped files</h1>
<p>A memory-mapped file is a special region in virtual memory that contains the contents of a file, this allows processes to treat the the contents of a file like a normal region in the memory.  <br />
There are two types of memory-mapped files in Windows:</p>
<ul>
  <li>Persisted memory-mapped files: These are the files that are associated (connected) with an actual file on the disk. After the last process has done it’s work with the memory-mapped file, the mapped file is written to the original file to which the memory-mapped file was associated with.</li>
  <li>Non-Persisted memory mapped files: These files are not associated with any file on the disk and are mostly used for inter-process communications (IPC). After the last process had done it’s work with the memory-mapped file, it’s content is lost.</li>
</ul>

<h1 id="page-sharing">Page sharing</h1>
<p>There are pages that are shared with different processes and these pages are called shared pages. Shared pages are mostly used to share DLLs that most processes on Windows require which saves RAM as the system doesn’t have to allocate same DLLs for each process, an example of this is <code class="language-plaintext highlighter-rouge">kernel32.dll</code>. Shared pages are essentially just <em>shared memory-mapped pages</em> which are associated with DLLs or some other shareable data.</p>

<h1 id="the-virtual-memory-management-api">The Virtual Memory Management API</h1>
<p>This API is provided by the memory manager of Windows. This API allows us to allocate, free, reserve and secure virtual memory pages. All the memory related functions in the Windows API reside under the <code class="language-plaintext highlighter-rouge">memoryapi.h</code> header file. In this particular post, we will see the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> and <code class="language-plaintext highlighter-rouge">VirtualFree</code> functions in depth.</p>

<h1 id="1-virtualalloc">1. VirtualAlloc</h1>
<p>The <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function allows us to allocate private memory regions (blocks) and manage them, managing these regions means reserving, committing, changing their states (described later). The memory regions allocated by this function are called a “private memory regions” because they are only accessible (available) to the processes that allocate them. Memory regions allocated with this function are initialised to 0 by default.</p>

<h4 id="function-signature">Function signature</h4>
<p>This is the function signature of this function:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">LPVOID</span> <span class="nf">VirtualAlloc</span><span class="p">(</span>
  <span class="n">LPVOID</span> <span class="n">lpAddress</span><span class="p">,</span>
  <span class="n">SIZE_T</span> <span class="n">dwSize</span><span class="p">,</span>
  <span class="n">DWORD</span>  <span class="n">flAllocationType</span><span class="p">,</span>
  <span class="n">DWORD</span>  <span class="n">flProtect</span>
<span class="p">);</span>
</code></pre></div></div>

<h4 id="arguments">Arguments</h4>
<p>The return type of this function is <code class="language-plaintext highlighter-rouge">LPVOID</code>, which is basically a pointer to a void object. <code class="language-plaintext highlighter-rouge">LPVOID</code> is defined as <code class="language-plaintext highlighter-rouge">typedef void* LPVOID</code> in the <code class="language-plaintext highlighter-rouge">Windef.h</code>. In simple words, <code class="language-plaintext highlighter-rouge">LPVOID</code> is an alias for <code class="language-plaintext highlighter-rouge">void *</code>. <code class="language-plaintext highlighter-rouge">LP</code> in <code class="language-plaintext highlighter-rouge">LPVOID</code> stands for long pointer.</p>

<p><strong>lpAddress</strong>: This argument is used to specify the starting address of the memory region (page) to allocate. This address can be provided either from the return value of the previous call to this function or it can be specified as an arbitrary address but if there is memory already allocated at this address, then the Memory manager will decide where it should allocate the memory. If we don’t know where to allocate memory (as if we have not called this function previously), we can simply specify <code class="language-plaintext highlighter-rouge">NULL</code> and the system will decide where to allocate the memory. If the address specified is from a memory region that is inaccessible or if it’s an invalid address to allocate memory from, the function will fail with <code class="language-plaintext highlighter-rouge">ERROR_INVALID_ADDRESS</code> error.</p>

<p><strong>dwSize</strong>: This argument is used to specify the size of the memory region that we want to allocate in <em>bytes</em>. If the <code class="language-plaintext highlighter-rouge">lpAddress</code> argument was specified as <code class="language-plaintext highlighter-rouge">NULL</code> then this value will be rounded up to the next page boundary.</p>

<p><strong>fAllocationType</strong>: This argument is used to specify which type of memory allocation we need to use. Here are some valid types as defined in the Microsoft documentation:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2FfAllocationtypes-for-valloc.jpg" alt="Valid types for fAllocation" width="700px" class="align-center" /></p>

<p>If you are confused about the hex values which are written after every value, they are basically the real value of the constants (i.e. <code class="language-plaintext highlighter-rouge">MEM_COMMIT</code>, <code class="language-plaintext highlighter-rouge">MEM_RESERVE</code>, etc). For example, if we use <code class="language-plaintext highlighter-rouge">MEM_COMMIT</code>, then it will be converted to <code class="language-plaintext highlighter-rouge">0x00001000</code> and same with all other values.</p>

<h4 id="what-does-committing-memory-actually-means">What does committing memory actually means?</h4>
<p>In the table of types and definitions, I have described <code class="language-plaintext highlighter-rouge">MEM_COMMIT</code> (which is used to commit virtual memory) terribly, so let me explain what committing memory actually means in a better way.  <br />
When you commit a region of memory using <code class="language-plaintext highlighter-rouge">VirtualAlloc</code>, due to the use of demand paging, the memory manager doesn’t actually allocate the memory region, neither on the physical disk nor in the Virtual Memory, but, when you try to access that memory address returned by the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function, it causes a <a href="iframe.php?url=https%3A%2F%2Fwww.geeksforgeeks.org%2Fpage-fault-handling-in-operating-system%2F">page fault</a> which causes a series of events and eventually the system allocates that memory region and serves it to you. So, until there’s an access request to the memory, it’s not allocated, there’s just a guarantee by the memory manager that there exists some memory and you can use them whenever you want.</p>

<p>The types which are used rarely can be found <a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fmemoryapi%2Fnf-memoryapi-virtualalloc%23arguments">here</a>.</p>

<p><strong>flProtect</strong>: This argument is used to specify the memory protection that we want to use for the memory region that we are allocating.  <br />
These are the supported parameters:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fsome-memory-constants.png" alt="Some memory protection constants" width="700px" class="align-center" /></p>

<p>These are only the most used memory protection constants, the full list can be found <a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fmemory%2Fmemory-protection-constants">here</a>.</p>

<h2 id="return-value">Return value</h2>
<p>If the function succeeds, it will return the starting address of the memory region that was modified or allocated. If the function fails, it will return <code class="language-plaintext highlighter-rouge">NULL</code>.</p>

<h1 id="2-virtualfree">2. VirtualFree</h1>
<p>This function is basically used to free the virtual memory that was allocated using <code class="language-plaintext highlighter-rouge">VirtualAlloc</code>.</p>

<h2 id="function-signature-1">Function signature</h2>
<p>This is the syntax of <code class="language-plaintext highlighter-rouge">VirtualFree</code>:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">BOOL</span> <span class="nf">VirtualFree</span><span class="p">(</span>
  <span class="n">LPVOID</span> <span class="n">lpAddress</span><span class="p">,</span>
  <span class="n">SIZE_T</span> <span class="n">dwSize</span><span class="p">,</span>
  <span class="n">DWORD</span>  <span class="n">dwFreeType</span>
<span class="p">);</span>
</code></pre></div></div>
<p>As you can see, the return type of this function is <code class="language-plaintext highlighter-rouge">BOOL</code>, it means that it will either return true (success) or false (fail).</p>

<h2 id="arguments-1">Arguments</h2>
<p><strong>lpAddress</strong>: As we know, this argument is used to specify the starting address of the memory region (page) which we want to modify (free in this case), but unlike the first time, we cannot specify <code class="language-plaintext highlighter-rouge">NULL</code> as an argument because obviously, the function cannot free a memory region whose address it doesn’t know.</p>

<p><strong>dwSize</strong>: We also know about this argument, it is used to pass the size in <em>bytes</em> of the memory region which we want to modify. Here, we will use it specify the size of the memory region that we want to free.</p>

<p><strong>dwFreeType</strong>: This argument is used to specify the type which we want to use to free the memory. It may be a bit confusing to you but looking at these types and their definition will clear your confusion:   <br />
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fvirtualfree-free-types.png" alt="virtualfree() free types" width="700px" class="align-center" /></p>

<h2 id="return-value-1">Return value</h2>
<p>If the function does its job successfully, it returns a nonzero value. If the function fails, it will return a zero (0).</p>

<h1 id="examples">Examples</h1>
<p>As we have looked into all the explanation, now it’s time to write some code and clear the doubts.</p>

<h2 id="example-1">Example #1</h2>
<p>Let’s start with taking example of <code class="language-plaintext highlighter-rouge">VirtualAlloc</code>. We will write some code which will commit 8 bytes of virtual memory.  <br />
First we’ll start by including the needed libraries:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;memoryapi.h&gt;</span><span class="cp">
</span></code></pre></div></div>

<p>Now, we’ll define a main function that will use the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function to commit 8 bytes of Virtual Memory which will be rounded up to 4KB as it is the nearest page boundary to 8 bytes. We will specify the <code class="language-plaintext highlighter-rouge">lpAddress</code> argument as <code class="language-plaintext highlighter-rouge">NULL</code>, so that the system will determine from where to allocate the memory. Here is how the code looks like:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;memoryapi.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="o">*</span><span class="n">pointer_to_memory</span> <span class="o">=</span> <span class="n">VirtualAlloc</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_COMMIT</span><span class="p">,</span> <span class="n">PAGE_READWRITE</span><span class="p">);</span> <span class="c1">// commit 4KB of virtual memory (8 byte is rounded up to 4KB) with read write permissions </span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"%x"</span><span class="p">,</span> <span class="n">pointer_to_memory</span><span class="p">);</span> <span class="c1">// print the pointer to the start of the region.</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Do you think something is missing from the code?  <br />
It’s the <code class="language-plaintext highlighter-rouge">VirtualFree</code> function. Whenever we allocate any kind of memory, we have to free it so that it can be used by other processes on the system.</p>

<p>Now it’s time to implement the <code class="language-plaintext highlighter-rouge">VirtualFree</code> function, so here is it:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;memoryapi.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="o">*</span><span class="n">pointer_to_memory</span> <span class="o">=</span> <span class="n">VirtualAlloc</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_COMMIT</span><span class="p">,</span> <span class="n">PAGE_READWRITE</span><span class="p">);</span> <span class="c1">// commit 8 bytes of virtual memory with read write permissions. </span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"The base address of allocated memory is: %x"</span><span class="p">,</span> <span class="n">pointer_to_memory</span><span class="p">);</span> <span class="c1">// print the pointer to the start of the region.</span>
    <span class="n">VirtualFree</span><span class="p">(</span><span class="n">pointer_to_memory</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_DECOMMIT</span><span class="p">);</span> <span class="c1">// decommit the memory region.</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Until this point, the working of the code must be clear to you, but if it’s not, here’s the line-by-line explanation of the code.  <br />
First, there’s a variable which is pointing to the memory address returned by <code class="language-plaintext highlighter-rouge">VirtualAlloc</code>. We have passed four parameters to the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function.   <br />
The first parameter is <code class="language-plaintext highlighter-rouge">NULL</code>, by passing <code class="language-plaintext highlighter-rouge">NULL</code> as a parameter, we are telling the function that the starting point of the memory region should be decided by the system.  <br />
The second parameter is the size of the memory region that we want to allocate in bytes, which is <code class="language-plaintext highlighter-rouge">8</code> bytes.  <br />
The third parameter is the allocation type, we have specified that we want to commit the memory. After we commit a memory region, it is available to us for our use but it’s not actually allocated until we access it for the first time.  <br />
The last parameter is <code class="language-plaintext highlighter-rouge">PAGE_READWRITE</code>, which is telling it that we want the memory region to be readable and writeable.   <br />
The we are printing virtual memory address returned by <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function as a hex value.  <br />
In the end, we are decommitting the memory region that we allocated by using the <code class="language-plaintext highlighter-rouge">VirtualFree</code> function.  <br />
The first parameter is the base address of the memory region that we allocated.  <br />
The second parameter is the size of memory region in bytes, we specified <code class="language-plaintext highlighter-rouge">8</code> while allocating it so the we’ll specify <code class="language-plaintext highlighter-rouge">8</code> while deallocating it. <br />
Then we have specified the type of deallocation. As we are using <code class="language-plaintext highlighter-rouge">MEM_DECOMMIT</code>, the memory region will be reserved after it gets decommitted, which means that any other function will not be able to use it after you decommit it until you use <code class="language-plaintext highlighter-rouge">VirtualFree</code> function again with <code class="language-plaintext highlighter-rouge">MEM_RELEASE</code> to release the memory region.</p>

<h3 id="results-1">Results #1</h3>
<p>As we are almost done with everything, let’s compile and run the code. I suggest you to write the code by yourself and see the result. This is the that result that I got after I ran it:</p>
<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>./vmem-example.exe
<span class="go">The base address of allocated memory is: 61fe18
</span></code></pre></div></div>
<p>Cool, right?  <br />
We have just used the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function to allocate 8 bytes of virtual memory and we freed it by ourselves. Now let’s add some data to the allocated virtual memory and print it.</p>

<h2 id="example-2">Example #2</h2>
<p>Now let’s save some data inside the virtual memory that we allocated:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;memoryapi.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="o">*</span><span class="n">pointer_to_memory</span> <span class="o">=</span> <span class="n">VirtualAlloc</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_COMMIT</span><span class="p">,</span> <span class="n">PAGE_READWRITE</span><span class="p">);</span> <span class="c1">// commit 8 bytes of virtual memory with read write permissions. </span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"The base address of allocated memory is: %x"</span><span class="p">,</span> <span class="n">pointer_to_memory</span><span class="p">);</span> <span class="c1">// print the pointer to the start of the region.</span>
    <span class="n">memmove</span><span class="p">(</span><span class="n">pointer_to_memory</span><span class="p">,</span> <span class="p">(</span><span class="k">const</span> <span class="kt">void</span><span class="o">*</span><span class="p">)</span><span class="s">"1337"</span><span class="p">,</span> <span class="mi">4</span><span class="p">);</span> <span class="c1">// move "1337" string into the allocated memory.</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"The data which is stored in the memory is %s"</span><span class="p">,</span> <span class="n">pointer_to_memory</span><span class="p">);</span> <span class="c1">// print the data from the memory.</span>
    <span class="n">VirtualFree</span><span class="p">(</span><span class="n">pointer_to_memory</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="n">MEM_DECOMMIT</span><span class="p">);</span> <span class="c1">// decommit the memory region.</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">memmove</code> function is used to move data from one destination to other. The first argument to this function is the destination memory address where you want to move the data and the second argument is the data that will be moved and the last and third argument is the size of data, which in this case is 5 (length of the string + null byte). Here, we have copied “1337” to the memory our virtually allocated memory. If you’re confused about the type conversion, it’s used because <code class="language-plaintext highlighter-rouge">memmove</code> takes second argument as a <code class="language-plaintext highlighter-rouge">const void*</code> and we can’t directly pass <code class="language-plaintext highlighter-rouge">char</code> array to it.</p>

<h3 id="results-2">Results #2</h3>
<p>Let’s compile and run the code. This is the output that we’ll get:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>./vmem-example.exe
<span class="go">The base address of allocated memory is: 61fe18
The data which is stored in the memory is 1337
</span></code></pre></div></div>
<p>looks even more cool :D!</p>

<h1 id="summary">Summary</h1>
<p>We learned a lot about virtual memory in this post, we first looked at how it is basically “virtual” memory which points to “physical” memory then we learned about paging on windows and different paging schemes that Windows’ memory manager uses then we got to know that a page is basically a memory region of 4KB, then we had look at two memory management related functions which allow us to modify virtual memory by allowing us to allocate and free it. I hope you enjoyed the blog and it wasn’t boring, any suggestions and constructive criticism is welcome!  <br />
Thank you for reading!</p>

<h1 id="resources">Resources</h1>
<ul>
  <li><a href="iframe.php?url=https%3A%2F%2Fconnormcgarr.github.io%2Fpaging%2F">An awesome blog on virtual memory with explanation of the translation of virtual memory into physical memory</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fmedium.com%2F%40esmerycornielle%2Fmemory-management-paging-43b85abe6d2f">Memory Management : Paging</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fcirosantilli.com%2Fx86-paging">x86 paging tutorial</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F34072879%2Fwhy-are-programs-not-written-using-physical-addresses">Why are programs not written using physical addresses? - stackoverflow</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fmemoryapi%2Fnf-memoryapi-virtualalloc">VirtualAlloc - msdn</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fmemoryapi%2Fnf-memoryapi-virtualfree">VirtualFree - msdn</a></li>
</ul>]]></content><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><category term="WinAPI" /><category term="Windows Internals series" /><category term="Windows API series" /><summary type="html"><![CDATA[Introduction to Virtual Memory, Paging and Windows API functions that allow us to play with the virtual memory!]]></summary></entry><entry><title type="html">Understanding the booting process of a computer and trying to write own operating system.</title><link href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2FUnderstanding-booting-process-and-writing-own-os%2F" rel="alternate" type="text/html" title="Understanding the booting process of a computer and trying to write own operating system." /><published>2022-01-22T00:00:00+00:00</published><updated>2022-01-22T00:00:00+00:00</updated><id>https://de-engineer.github.io/Understanding-booting-process-and-writing-own-os</id><content type="html" xml:base="https://de-engineer.github.io/Understanding-booting-process-and-writing-own-os/"><![CDATA[<p>In this post, we are going to learn how can we write our own Operating System. Although, it won’t be a fully-fleged Operating system (like the one you are using right now to read this post), but it will be a part of an Operating System that would be able to boot and it will give you a brief if not full understanding of the booting process of an Operating System. If you want to take this post seriously, I suggest you to take notes as there is a lot of information combined in this single post and can be uncomfortable to grasp at the same time.  <br />
If you find something difficult to understand from my explanation, you can always check the <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources">resources</a> section to get a link to some alternative explanation of that topic.   <br />
I would start this post by introducing you to some important components of the booting process of an Computer.</p>

<p>Table of contents:</p>

<ul id="markdown-toc">
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23firmware" id="markdown-toc-firmware">Firmware</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-boot-process" id="markdown-toc-the-boot-process">The boot process</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23environment-setup" id="markdown-toc-environment-setup">Environment setup</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23writing-our-bootloader" id="markdown-toc-writing-our-bootloader">Writing our bootloader</a>    <ul>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23adding-some-data-to-our-bootloader" id="markdown-toc-adding-some-data-to-our-bootloader">Adding some data to our bootloader</a></li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23making-our-bootloader-bootable" id="markdown-toc-making-our-bootloader-bootable">Making our bootloader bootable</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-times-instruction" id="markdown-toc-the-times-instruction">The times instruction</a></li>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23booting-into-our-bootloader" id="markdown-toc-booting-into-our-bootloader">Booting into our bootloader</a></li>
        </ul>
      </li>
      <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-final-code" id="markdown-toc-the-final-code">The final code</a>        <ul>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-org-directive" id="markdown-toc-the-org-directive">The org directive</a></li>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23setting-up-the-registers" id="markdown-toc-setting-up-the-registers">Setting up the registers.</a></li>
          <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23interrupts" id="markdown-toc-interrupts">Interrupts.</a>            <ul>
              <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-most-popular-interrupt" id="markdown-toc-the-most-popular-interrupt">The most popular interrupt</a></li>
              <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23int-0x10" id="markdown-toc-int-0x10">int 0x10</a></li>
              <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23int-0x16" id="markdown-toc-int-0x16">int 0x16.</a>                <ul>
                  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23implementation-of-interrupts-into-something-useful" id="markdown-toc-implementation-of-interrupts-into-something-useful">Implementation of interrupts into something useful</a></li>
                  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23our-bootloader-in-action" id="markdown-toc-our-bootloader-in-action">Our bootloader in action</a></li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23summary" id="markdown-toc-summary">Summary</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23author-notes" id="markdown-toc-author-notes">Author notes</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources" id="markdown-toc-resources">Resources</a></li>
</ul>

<h1 id="firmware">Firmware</h1>

<p>Unless you live under a rock, you might have heard of the term <em>“Firmware”</em> several times, if you didn’t then let me introduce you to what a Firmware is.<br />
The most well known example of firmwares are Basic Input/Output System (BIOS) and Unified Extensible Firmware Interface (UEFI).<br />
The term itself is actually made up of two fancy words - <strong>FIRM softWARE</strong>. The word <em>“FIRM”</em> means <em>“something that doesn’t change or something that is not likely to change”</em> and I know you are a smart person and you know what a software is. The word is nice and all but you are here to learn about the cool technical stuff so let me explain the techincal part of it.
The firmware is stored inside non-volatile memory devices (devices which store sort of permanent data that doesn’t change after a system restart) as instructions or data and it is the first thing that the CPU runs after the computer is powered on. Everything that we are learning in this blog post is specific to the BIOS firmware type. Modern Operating Systems do not use BIOS, however, that doesn’t mean that the knowledge in this article is of no use as concepts of BIOS are simpler to understand still relavent to learn.</p>

<p>In order to understand the importance and the uses of a firmware, you would need to understand the boot process (<em>“boot”</em> refers to <em>“Bootstrap”</em>) of a computer.</p>

<h1 id="the-boot-process">The boot process</h1>

<p>The booting process is something like this:</p>

<ul>
  <li>Computer is powered on.</li>
  <li>The Central Processing Unit (CPU) runs the firmware from a specific Read-Only Memory (ROM) chip on your motherboard. The ROM from which your CPU is going to read the firmware depends upon the CPU your system is having.</li>
  <li>The firmware detects several (but not all) hardware components connected to the system, such as network interfaces, keyboards, mouse, and so on, and does some error checking (also known as Power-On Self Test or POST) before activating them.</li>
  <li>The firmware doesn’t know what are the properties and details of the Operating System that is about to be going to be ran on the system, So, it transfers it’s control to the Operating System and lets it do it’s setup. It starts with searching through the available/connected storage devices or network interfaces in a pre-defined order (this order is known as the <em>“boot device sequence”</em> or <em>“boot order”</em>) and attempts to find a bootable disk. A bootable disk is a disk whose first sector (a subdivision of a HDD which can hold 512 bytes of user-accessible data) contains the magic number <code class="language-plaintext highlighter-rouge">0xAA55</code> (big-endian). This magic number is also called as the <em>“boot signature”</em>. In this sector the byte at index 511 should be <code class="language-plaintext highlighter-rouge">0xAA</code> and the byte at index 512 should be <code class="language-plaintext highlighter-rouge">0x55</code>. This first sector is called the Master Boot Record (MBR) and the program stored inside it is called the MBR bootloader or simply bootloader. Remember that this bootloader is a part of the Operating System, so technically, this is part of the process where we are actually booted in the Operating System. This whole process is done after the firmware calls the interrupt 0x19 (more about this later).</li>
  <li>After the firmware has found the bootloader, it loads it into the address <code class="language-plaintext highlighter-rouge">0x7c00</code> in the RAM and hands over the control to it.</li>
  <li>Now, the bootloader can do whatever it is programmed to do, it may print a nihilist quote and tell you that your life has no meaning or it may just do nothing if it is programmed that way. Jokes aside, while it can be programmed to do anything, the main work it is supposed to be doing is performing several tasks that sets up the environment for the loading of next part (the kernel) of the OS. After performing some tasks like the initialisation of some registers, tables and so on. It reads the kernel from the disk and loads it somewhere in the RAM and handles over the control to it.</li>
  <li>Now, the kernel has the control over the system. Just like a bootloader, there is no pre-defined tasks for a kernel. Whatever it will do entirely depends upon what it has been programmed to do. For example, this can be seen in the Linux and Windows kernel, they are entirely different and what they will do is too entirely different but they will eventually start the User Interface and allow the user to have the control of the system. If you find this complex, here’s an example - Just like everyone in your company does different stuff after they wake up - they may reply drink a cup of chai, they may go for a walk or do anything they want but their end goal is to reach the office on time and start working, a kernel too has the end goal of successfully loading the easy-to-use User Interface part of the OS to the user. Note that this is not the only work of the kernel in the OS, the kernel is an essential part of an OS and also has a lot to do after it has served you the nice UI.</li>
</ul>

<hr />

<h1 id="environment-setup">Environment setup</h1>

<p>Before diving in, You should have <a href="iframe.php?url=https%3A%2F%2Fwww.nasm.us%2Fpub%2Fnasm%2Freleasebuilds%2F2.15rc12%2F">nasm</a> and <a href="iframe.php?url=https%3A%2F%2Fwww.qemu.org%2Fdownload%2F">qemu</a> installed. I know you probably do not have any of them, so go ahead and install them. Both are available for Windows and Linux.</p>

<p>In linux nasm and qemu can be installed through a single command:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span><span class="nb">sudo </span>apt <span class="nb">install </span>nasm<span class="p">;</span> <span class="nb">sudo </span>apt <span class="nb">install </span>qemu-system-x86
</code></pre></div></div>
<hr />

<h1 id="writing-our-bootloader">Writing our bootloader</h1>

<p>As writing a complete kernel from scratch and then writing our own user interface, software, compiler, etc. would be a lot of pain to write in single blog post and even for you to understand, I am going to not do it all in this post and instead of writing the whole OS, we would be only be writing a bootloader, and it actually worths trying to write it, as you will too learn a lot of new things related to bootloaders and Operating Systems.</p>

<p>For now, we will start by writing an endless loop which is not pointless <del>(unlike your life)</del>. It will be a function that does nothing more than jumping to itself (looping endlessly).</p>

<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">loop:</span>
    <span class="nf">jmp</span> <span class="nv">loop</span> 
</code></pre></div></div>
<p><br />
Here’s how you assemble it:</p>
<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nasm bootsector.asm <span class="nt">-f</span> bin <span class="nt">-o</span> bootloader.bin
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">-f</code> flag specifies the <code class="language-plaintext highlighter-rouge">format</code> which is <code class="language-plaintext highlighter-rouge">bin</code> (binary) in our case, and the <code class="language-plaintext highlighter-rouge">-o</code> flag is used to name the file in which we want our output to be saved.
<br />      <br />
hexdump of <code class="language-plaintext highlighter-rouge">bootloader.bin</code>:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">00000000:</span> <span class="nf">ebfe</span>                                     <span class="nv">..</span>
</code></pre></div></div>
<p>The opcode or the hex representaion of these instructions is <code class="language-plaintext highlighter-rouge">ebfe</code>, it is an infinite loop in assembly, which is exactly what we wanted.</p>

<h2 id="adding-some-data-to-our-bootloader">Adding some data to our bootloader</h2>
<p>Now that we are done with our endless loop, we will continue to write some more instructions to our bootloader and will eventually make it bootable.</p>

<p>We will first start by writing some data to our bootloader, here’s how you do it:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">loop:</span>
    <span class="nf">jmp</span> <span class="nv">loop</span>

<span class="kd">db</span> <span class="mh">0x10</span>
</code></pre></div></div>

<p>hexdump:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">00000000:</span> <span class="nf">ebfe</span> <span class="mi">10</span>                                  <span class="nv">...</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">db (data byte)</code> instruction is used to put a byte “literally” in the executable, that’s why you can see 10 being stored in the executable.</p>

<h2 id="making-our-bootloader-bootable">Making our bootloader bootable</h2>
<p>The first thing we need to do in order to make this an actual bootable device is to add the the magic bytes at the end of the our bootloader’s code (at 511 and 512 index), so that the firmware can actually know that this is a bootable device. This is how we do it:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">loop:</span>
    <span class="nf">jmp</span> <span class="nv">loop</span>						<span class="c1">; endless loop</span>
<span class="kd">db</span> <span class="mh">0x10</span>  						<span class="c1">; pointless data</span>
<span class="kd">db</span> <span class="err">"</span><span class="nv">You</span> <span class="nb">di</span><span class="nv">dn</span><span class="err">'</span><span class="nv">t</span> <span class="nb">ch</span><span class="nv">ose</span> <span class="nv">to</span> <span class="nv">exist.</span><span class="err">"</span> 			<span class="c1">; makes sense?</span>

<span class="kd">times</span> <span class="mh">0x1fe</span><span class="o">-</span><span class="p">(</span><span class="kc">$</span><span class="o">-</span><span class="kc">$$</span><span class="p">)</span> <span class="nv">db</span> <span class="mi">0</span>					<span class="c1">; explained later. 0x1fe = 510 in decimal.</span>
<span class="kd">dw</span> <span class="mh">0xaa55</span> 						<span class="c1">; the magic number.</span>
</code></pre></div></div>

<p>The instruction <code class="language-plaintext highlighter-rouge">times 0x1fe-($-$$) db 0</code> may look scary but it’s really easy to understand.  <br />
The instruction can be broken into two instructions: <code class="language-plaintext highlighter-rouge">times 0x1fe-($-$$)</code> and <code class="language-plaintext highlighter-rouge">db 0</code>. Let me explain the first one to you then you will be able to make sense of the second one too.</p>

<h3 id="the-times-instruction">The times instruction</h3>
<p>The <code class="language-plaintext highlighter-rouge">times</code> instruction tells the assembler (nasm in this case) to produce multiple (n) copies of a specified instruction. In order to understand this more clearly, let’s look at the syntax of <code class="language-plaintext highlighter-rouge">times</code> instruction:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">times</span> <span class="o">&lt;</span><span class="nv">n</span><span class="o">&gt;</span> <span class="o">&lt;</span><span class="nv">instruction</span><span class="o">&gt;</span> <span class="o">&lt;</span><span class="nv">operand</span><span class="o">&gt;</span> <span class="nv">...</span>		<span class="c1">; n = number of times.</span>
</code></pre></div></div>
<p>One thing you should know is the number of operands depends on the instruction being used.
Here’s a simpler use case example of the <code class="language-plaintext highlighter-rouge">times</code> instruction:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">times</span> <span class="mi">10</span> <span class="nv">db</span> <span class="s">'1337'</span> 
</code></pre></div></div>
<p>Here, <code class="language-plaintext highlighter-rouge">10</code> is n, <code class="language-plaintext highlighter-rouge">db</code> is the instruction and <code class="language-plaintext highlighter-rouge">'1337'</code> is an operand. This instruction will tell the assembler to make 10 copies of the instruction <code class="language-plaintext highlighter-rouge">db '1337'</code>.  <br />
Here’s the hexdump of the code:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">00000000</span>  <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span> <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span>  <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span> <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span>  <span class="err">|1337133713371337|</span>
<span class="err">00000010</span>  <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span> <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span>  <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span> <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span>  <span class="err">|1337133713371337|</span>
<span class="err">00000020</span>  <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span> <span class="err">31</span> <span class="err">33</span> <span class="err">33</span> <span class="err">37</span>                           <span class="err">|13371337|</span>
<span class="err">00000028</span>
</code></pre></div></div>
<p>As expected, we can notice the string <code class="language-plaintext highlighter-rouge">'1337'</code> repeated 10 times. It worked just fine.</p>

<hr />

<p>Now, let’s move to the original instruction and try to understand the subtraction it’s doing.  <br />
Let’s start with the subtraction under the bracket <code class="language-plaintext highlighter-rouge">($-$$)</code>. The <code class="language-plaintext highlighter-rouge">$</code> operator in assembly (nasm) denotes <del>money</del> the address of the current instruction and <code class="language-plaintext highlighter-rouge">$$</code> operator denotes the address of the first instruction (beginning of the current section), which in this case, is the address of the definition of the endless loop and whose address would be <code class="language-plaintext highlighter-rouge">0x7C00</code> (as we know, firmware loads the bootloader at address <code class="language-plaintext highlighter-rouge">0x7C00</code>).  <br />
It’s basically this:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">addr_of_current_instruction</span> <span class="o">-</span> <span class="nv">addr_of_first_instruction_0x7c00</span> 
</code></pre></div></div>

<p>This subtraction will return the number of bytes from the start of the program to the current line, which is just the size of the program and it is getting substracted from <code class="language-plaintext highlighter-rouge">0x1fe</code> (<code class="language-plaintext highlighter-rouge">510</code> in decimal). Why are we doing this subtraction?  <br />
We are doing this to get the value of bytes that aren’t used so that we can fill them with zeros (<code class="language-plaintext highlighter-rouge">db 0</code>) and then we will successfully be having the magic bytes at <code class="language-plaintext highlighter-rouge">511</code> and <code class="language-plaintext highlighter-rouge">512</code> index.  <br />
It can be understood like this:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">200</span> <span class="err">-</span> <span class="err">(</span><span class="nf">addr_of_current_instruction</span> <span class="o">-</span> <span class="nv">addr_of_first_instruction_0x7c00</span><span class="p">)</span> <span class="c1">; returns the no. of unused bytes.</span>
</code></pre></div></div>
<p>This value will be passed to <code class="language-plaintext highlighter-rouge">times</code> instruction as <code class="language-plaintext highlighter-rouge">n</code> and it already has the instruction (<code class="language-plaintext highlighter-rouge">db</code>) and operand (<code class="language-plaintext highlighter-rouge">0</code>), so it will tell the assembler to fill the bytes aren’t used with <code class="language-plaintext highlighter-rouge">0</code> until the 510 index.<br />
So, it will finally look like this:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">times</span> <span class="mi">200</span> <span class="o">-</span><span class="p">(</span><span class="nv">addr_of_current_instruction</span> <span class="o">-</span> <span class="nv">addr_of_first_instruction_0x7c00</span><span class="p">)</span> <span class="nv">db</span> <span class="mi">0</span>
<span class="c1">; times 0x1fe-($-$$) db 0</span>
<span class="c1">; fills the unused bytes with 0</span>
</code></pre></div></div>

<p>The only thing that is left is to actually put the magic number in the bootloader. It is done by using the <code class="language-plaintext highlighter-rouge">dw 0xaa55</code> instruction (<code class="language-plaintext highlighter-rouge">dw is same as db but dw is used for words and db is used for bytes</code>).  <br />
Now, that we are done with the understanding of the bootloader, let’s assemble it and look at the hexdump to actually see the result.</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">00000000:</span> <span class="nf">ebfe</span> <span class="mi">1059</span> <span class="mi">6</span><span class="nv">f75</span> <span class="mi">2064</span> <span class="mi">6964</span> <span class="mi">6</span><span class="nv">e27</span> <span class="mi">7420</span> <span class="mi">6368</span>  <span class="nv">...You</span> <span class="nb">di</span><span class="nv">dn</span><span class="err">'</span><span class="nv">t</span> <span class="nb">ch</span>
<span class="err">00000010:</span> <span class="err">6</span><span class="nf">f73</span> <span class="mi">6520</span> <span class="mi">746</span><span class="nv">f</span> <span class="mi">2065</span> <span class="mi">7869</span> <span class="mi">7374</span> <span class="mi">2</span><span class="nv">e00</span> <span class="mi">0000</span>  <span class="nv">ose</span> <span class="nv">to</span> <span class="nv">exist....</span>
<span class="err">00000020:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000030:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000040:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000050:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000060:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000070:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000080:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000090:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000000</span><span class="nl">a0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000000</span><span class="nl">b0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000000</span><span class="nl">c0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000000</span><span class="nl">d0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000000</span><span class="nl">e0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000000</span><span class="nl">f0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000100:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000110:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000120:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000130:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000140:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000150:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000160:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000170:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000180:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">00000190:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000001</span><span class="nl">a0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000001</span><span class="nl">b0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000001</span><span class="nl">c0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000001</span><span class="nl">d0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000001</span><span class="nl">e0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span>  <span class="nf">................</span>
<span class="err">000001</span><span class="nl">f0:</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">0000</span> <span class="err">55</span><span class="nf">aa</span>  <span class="nv">..............U.</span>
</code></pre></div></div>
<p>As expected, we have filled the unused bytes with zeros and the last two bytes with the magic number (the order is different due to endianness). Now our bootloader and actually a bootloader and ready to work.</p>

<h3 id="booting-into-our-bootloader">Booting into our bootloader</h3>
<p>To boot into it, make sure you have assembled your bootloader code with nasm.</p>

<p>Run this command:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>qemu-system-x86_64 bootsector.bin
</code></pre></div></div>
<p class="no_toc">After you run this, if will see a window of qemu which has some initialization text and then it is blank it means your bootloader works perfectly because we just programmed it to loop so it just doing that.
Here’s how the window looks like:</p>
<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fqemu-boot-1.png" alt="QEMU screeenshot 1." width="700" class="align-center" /></p>

<hr />

<h2 id="the-final-code">The final code</h2>
<p>We are finally at almost the end of the blog post, and we will now add the final features to our bootloader. These features are not going to be anything fancy, we are only going to make it display the text that we are entering.  <br />
Here’s the code for it:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">[</span><span class="nf">org</span> <span class="mh">0x7c00</span><span class="p">]</span>

<span class="nf">mov</span> <span class="nb">bp</span><span class="p">,</span> <span class="mh">0xffff</span>
<span class="nf">mov</span> <span class="nb">sp</span><span class="p">,</span> <span class="nb">bp</span>

<span class="nf">call</span> <span class="nv">set_video_mode</span>
<span class="nf">call</span> <span class="nv">get_char_input</span>

<span class="nf">jmp</span> <span class="kc">$</span>

<span class="nl">set_video_mode:</span>
	<span class="nf">mov</span> <span class="nb">ah</span><span class="p">,</span> <span class="mh">0x00</span>
	<span class="nf">mov</span> <span class="nb">al</span><span class="p">,</span> <span class="mh">0x03</span>
	<span class="nf">int</span> <span class="mh">0x10</span>
	<span class="nf">ret</span>

<span class="nl">get_char_input:</span>
	<span class="nf">xor</span> <span class="nb">ah</span><span class="p">,</span> <span class="nb">ah</span> 		<span class="c1">; same as mov ah, 0x00</span>
	<span class="nf">int</span> <span class="mh">0x16</span>

	<span class="nf">mov</span> <span class="nb">ah</span><span class="p">,</span> <span class="mh">0x0e</span>
	<span class="nf">int</span> <span class="mh">0x10</span>

	<span class="nf">jmp</span> <span class="nv">get_char_input</span>

<span class="kd">times</span> <span class="mh">0x1fe</span><span class="o">-</span><span class="p">(</span><span class="kc">$</span><span class="o">-</span><span class="kc">$$</span><span class="p">)</span> <span class="nv">db</span> <span class="mi">0</span>
<span class="kd">dw</span> <span class="mh">0xaa55</span>
</code></pre></div></div>
<h3 id="the-org-directive">The org directive</h3>
<p>The difference between an instruction an directive is that An instruction is directly translated to something the CPU can execute. A directive is something the assembler can interpret and use it while assembling, it does not produce any machine code.  <br />
The first line may look a bit complex because unlike other instructions, it has brackets around it, but there’s nothing to worry about, you can just forget about the brackets and focus on the actual directive. It is <code class="language-plaintext highlighter-rouge">org 0x7C00</code>. Here’s the explanation:  <br />
As we know, bootloaders get loaded at the memory address <code class="language-plaintext highlighter-rouge">0x7C00</code> but the assembler don’t know this, that is why we use the <code class="language-plaintext highlighter-rouge">org</code> directive to tell the assembler to assume that the address of beginning of our code (base address) is <code class="language-plaintext highlighter-rouge">&lt;operand&gt;</code>, which is <code class="language-plaintext highlighter-rouge">0x7C00</code> in this case. After the assembler knows the base address of the program, every address that the assembler use while assembling the code will be relative to the base address that we have defined. For example, if we do not use this directive, the assembler will assume that the base address to be <code class="language-plaintext highlighter-rouge">0x00</code> and the address of every function and instruction will be calculated like this:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">0</span><span class="nf">x00</span><span class="o">+</span><span class="nv">relative_addr_of_function</span>
<span class="c1">; base_addr + relative_addr_of_function</span>
<span class="c1">; base_addr + relative_addr_of_instruction</span>
</code></pre></div></div>
<p>and these address won’t work on the runtime of our bootloader as it will not be loaded at that address, that is why we need to use the org directive.  <br />
Visual comparison of effects of using and not using the org directive:  <br />
<br />
<img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fwithout-org.png" alt="code without org directive" width="450px" style="padding-right: 50px" /><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fwith-org.png" alt="code with org directive" width="455px" style="padding-left: 50px" /></p>

<h3 id="setting-up-the-registers">Setting up the registers.</h3>
<p>The next thing we do is setting the correct values for registers.  <br />
The first register we set up is the <code class="language-plaintext highlighter-rouge">bp</code> (<code class="language-plaintext highlighter-rouge">base pointer</code>) register to the address <code class="language-plaintext highlighter-rouge">0xffff</code> and then copy it to <code class="language-plaintext highlighter-rouge">sp</code> (<code class="language-plaintext highlighter-rouge">stack pointer</code>). Hold up!, Why this address?  <br />
In order to understand this, we first need to look at the memory layout of the system when it’s in the booting process. Here is how it looks like:</p>

<p class="text-center"><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fboot-memory-layout.png" alt="Memory layout of the system while booting" height="600px" width="400px" class="align-center" /> 
<strong>Memory layout of the system while booting.</strong></p>
<p>As you can see, the memory address that we are setting the base pointer is in the free memory that is after the memory address where our bootloader will be loaded (<code class="language-plaintext highlighter-rouge">0x7e00</code>) and before the other section of memory which starts at <code class="language-plaintext highlighter-rouge">0x9cf00</code>. We have set it to <code class="language-plaintext highlighter-rouge">0xffff</code> because if we had set it anywhere else (in some non-free memory) then it could possibly overwrite the other data that is around it as the stack increases it’s size whenever data is pushed into it. Note that the address <code class="language-plaintext highlighter-rouge">0xffff</code> is arbitrary and you can use any address from the free space, just make sure that the address that you are choosing is not very closer to the boundaries of other regions inside memory because when you will put data inside your stack, it may expand (stack grows downwards) and overwrite the data inside those other regions.</p>

<h3 id="interrupts">Interrupts.</h3>
<p>The next line of code after the setting up of registers is of a <code class="language-plaintext highlighter-rouge">call</code> instruction which is calling the function <code class="language-plaintext highlighter-rouge">set_video_mode</code>. Here’s the code of the function:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">set_video_mode:</span>
	<span class="nf">mov</span> <span class="nb">al</span><span class="p">,</span> <span class="mh">0x03</span>
	<span class="nf">mov</span> <span class="nb">ah</span><span class="p">,</span> <span class="mh">0x00</span>
	<span class="nf">int</span> <span class="mh">0x10</span>
	<span class="nf">ret</span>
</code></pre></div></div>
<p>The first two lines are pretty basic, they are just moving the constant <code class="language-plaintext highlighter-rouge">0x03</code> and <code class="language-plaintext highlighter-rouge">0x00</code> into <code class="language-plaintext highlighter-rouge">al</code> and <code class="language-plaintext highlighter-rouge">ah</code> register but then we have a new instruction, which is the <code class="language-plaintext highlighter-rouge">int</code> instruction. The <code class="language-plaintext highlighter-rouge">int</code> instruction is used to generate a software interrupt. So, what is an interrupt?  <br />
Interrupts allow the CPU to temporarily halt (stop) what it is doing and run some other, higher-priority instructions before returning to the original task. An interrupt could be raised either by a software instruction (e.g. int 0x10) or by some hardware device that requires high-priority action (e.g. to read some incoming data from a network device.  <br />
Each interrupt has a different number assigned to it, which is an index in the Interrupt Vector Table  (IVR) which is basically a table that stores these interrupts as indexes to vectors (memory address or pointers) which point to Interrupt Service Routines (ISR). ISRs are initialised by the firmware and they are basically machine code that run differently for each interrupts, they have a sort of a long switch case statement with code to be used differently for different arguments. You can think IVT as a simple hash table (dictionary) in which each index holds a memory address to a function. Here’s an example:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">IVT</span> <span class="o">=</span> <span class="p">{</span>
	<span class="mi">1</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...,</span>
	<span class="mi">2</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...,</span>
	<span class="mi">3</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...,</span>
	<span class="mi">4</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...,</span>
	<span class="mi">5</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...,</span>
	<span class="mi">6</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...,</span>
	<span class="mi">7</span><span class="p">:</span> <span class="mh">0x0</span><span class="p">...</span>
	<span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="the-most-popular-interrupt">The most popular interrupt</h4>
<p>If you have ever debugged a program, you might already know what a breakpoint is, it’s simply you asking the debugger to stop the program at some point while it’s running and the debugger does it’s job. But, How do debuggers even make the program stop at while it’s running?  <br />
They use the interrupt 3, which is specially made for debuggers to stop a running process.</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">int</span> <span class="mi">3</span>
</code></pre></div></div>

<p>How do they use this interrupt to pause a program?  <br />
Debuggers replace the opcode of the first opcode of the currently running instruction with the opcode of <code class="language-plaintext highlighter-rouge">int 3</code> which is just a one-byte opcode <code class="language-plaintext highlighter-rouge">cc</code>.  <br />
Here’s an example:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fint-3-working.png" alt="int-3-instruction-usage" class="align-center" /></p>

<p>As <code class="language-plaintext highlighter-rouge">int 3</code> has just a single byte opcode, it makes the task very fast and easy for debuggers. When the <code class="language-plaintext highlighter-rouge">int 3</code> instruction is executed, it’s index is checked in the IVT and then it’s ISR is located and it starts running. The ISR then finds the process which needs to get paused, pauses it and notifies the debugger that the process has been stopped, and once the debugger gets this notification, it allows you to inspect the memory and the registers of the process which is getting debugged by the debugger. In order to allow the continuation of the process which was previously paused, the debugger replaces the <code class="language-plaintext highlighter-rouge">cc</code> opcode with the original opcode which it was replace with and the program continues from the place where it was stopped. Example:</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fint-3-reversed.png" alt="int-3-instruction-reversed" /></p>

<p>I hope this section helped you understand the real world usage and implementation of an software interrupt, and now you also know how a debugger makes the breakpoint a thing.</p>

<h4 id="int-0x10">int 0x10</h4>
<p>Now, you have a good understanding of interrupts and you have also seen an real world example of it, let’s now understand the usage of the interrupt that is present in the <code class="language-plaintext highlighter-rouge">set_video_mode</code> function, the interrupt <code class="language-plaintext highlighter-rouge">0x10</code>.
The interrupt <code class="language-plaintext highlighter-rouge">0x10</code> has video/screen related modification functions. In order to use different functions, we set the <code class="language-plaintext highlighter-rouge">ah</code> and <code class="language-plaintext highlighter-rouge">al</code> registers together to different values. These are the values that to which the <code class="language-plaintext highlighter-rouge">ah</code> register can be set:</p>
<ul>
  <li>AH=0x00: Video mode.</li>
  <li>AX=0x1003: Blinking mode.</li>
  <li>AH=0x13: Write string.</li>
  <li>AH=0x03: Get cursor position.</li>
  <li>AH=0x0e: Write Character in TTY Mode.</li>
</ul>

<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">set_video_mode:</span>
	<span class="nf">mov</span> <span class="nb">ah</span><span class="p">,</span> <span class="mh">0x00</span>
	<span class="nf">mov</span> <span class="nb">al</span><span class="p">,</span> <span class="mh">0x03</span>
	<span class="nf">int</span> <span class="mh">0x10</span>
	<span class="nf">ret</span>
</code></pre></div></div>
<p>Explanation: 
The <code class="language-plaintext highlighter-rouge">mov</code> instruction is setting the value of the <code class="language-plaintext highlighter-rouge">ah</code> register to <code class="language-plaintext highlighter-rouge">0x00</code>, which is basically asking it’s ISR to set the video mode to a mode which is specified in the <code class="language-plaintext highlighter-rouge">al</code> register, and these are the supported video modes with the values for <code class="language-plaintext highlighter-rouge">ah</code> register:</p>
<ul>
  <li>AL=0x00 - text mode. 40x25. 16 colors.</li>
  <li>AL=0x03 - text mode. 80x25. 16 colors.</li>
  <li>AL=0x13 - graphical mode. 40x25. 256 colors. 320x200 pixels.</li>
</ul>

<p>So, both registers combined are basically asking the ISR of interrupt <code class="language-plaintext highlighter-rouge">0x10</code> to set the video mode of the screen to text mode, which has the size <code class="language-plaintext highlighter-rouge">80x25</code> and supports 16 colors and that is the only motive of this function.</p>

<h4 id="int-0x16">int 0x16.</h4>
<p>The other function we are left with is <code class="language-plaintext highlighter-rouge">get_char_input</code>. In this function, we have another interrupt, which is interrupt <code class="language-plaintext highlighter-rouge">0x16</code>.  <br />
The interrupt <code class="language-plaintext highlighter-rouge">0x16</code> is used for basic keyboard related function. These are the some values that can be set in the <code class="language-plaintext highlighter-rouge">ah</code> register to use different keyboard functions:</p>
<ul>
  <li>AH = 0x00 - Read key press.</li>
  <li>AH = 0x01 - Get state of the keyboard buffer.</li>
  <li>AH = 0x02 - Get the State of the keyboard.</li>
  <li>AH = 0x03 - Establish repetition factor.</li>
  <li>AH = 0x05 - Simulate a keystroke</li>
  <li>AH = 0x0A - Get the ID of the keyboard.</li>
</ul>

<h5 id="implementation-of-interrupts-into-something-useful">Implementation of interrupts into something useful</h5>

<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">get_char_input:</span>
	<span class="nf">xor</span> <span class="nb">ah</span><span class="p">,</span> <span class="nb">ah</span>		<span class="c1">; same as mov ah, 0x00</span>
	<span class="nf">int</span> <span class="mh">0x16</span>

	<span class="nf">mov</span> <span class="nb">ah</span><span class="p">,</span> <span class="mh">0x0e</span>
	<span class="nf">int</span> <span class="mh">0x10</span>

	<span class="nf">jmp</span> <span class="nv">get_char_input</span>
</code></pre></div></div>
<p>The first thing done in the function’s code is the xoring of the <code class="language-plaintext highlighter-rouge">ah</code> register with itself, which is basically the same as <code class="language-plaintext highlighter-rouge">mov ah, 0x00</code> but xoring a register with itself is believed to be faster and less CPU expensive, so I used it.  <br />
After setting <code class="language-plaintext highlighter-rouge">ah</code> to zero, it will call the interrupt <code class="language-plaintext highlighter-rouge">0x16</code>, whose ISR will then read the keystroke from the keyboard and store it into the <code class="language-plaintext highlighter-rouge">al</code> register.  <br />
After that, it sets the <code class="language-plaintext highlighter-rouge">ah</code> register to <code class="language-plaintext highlighter-rouge">0x0e</code> and calls our good old interrupt <code class="language-plaintext highlighter-rouge">0x10</code>, but this time it is not setting the video mode to something as the <code class="language-plaintext highlighter-rouge">ah</code> register is not set to <code class="language-plaintext highlighter-rouge">0x00</code>. If you read the functions of the interrupt <code class="language-plaintext highlighter-rouge">0x10</code> again, you will find that <code class="language-plaintext highlighter-rouge">ah = 0x0e</code> asks it’s ISR to “write a character in tty mode” which basically means “write a character to the screen”. The character which this ISR will print will be taken from the <code class="language-plaintext highlighter-rouge">al</code> register. So, these two interrupts are together reading the character from the screen (using interrupt <code class="language-plaintext highlighter-rouge">0x10</code>) and printing it onto the screen (using intterupt <code class="language-plaintext highlighter-rouge">0x16</code>).  <br />
After this reading of character, the function is simply calling itself (like an infinite loop) to continue what it’s doing forever until it’s manually stopped.</p>

<h5 id="our-bootloader-in-action">Our bootloader in action</h5>
<p>The final thing we are left with is to see our bootloader in action, so let’s do it.
Assemble the code:</p>
<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nasm bootsector.asm <span class="nt">-f</span> bin <span class="nt">-o</span> bootloder.bin
</code></pre></div></div>
<p>Run it with qemu:</p>
<div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">qemu</span><span class="o">-</span><span class="nv">system</span><span class="o">-</span><span class="nv">x86_64</span> <span class="nv">bootsector.bin</span>
</code></pre></div></div>
<p>Now, you should have a blank window of qemu. You can now type anything and it’ll display it to the screen and that is all it has to it.</p>

<p><img src="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F..%2Fimages%2Fqemu-final.png" alt="final-bootloader-screenshot" /></p>

<h1 id="summary">Summary</h1>
<p>We started this blog post by understanding the <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-boot-process">boot process</a> of a computer, then we learnt about some new and assembly instructions and then we learned about what <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23interrupts">interrupts</a>, how they work and then we learnt about <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23the-most-popular-interrupt">how</a> debuggers implement breakpoints using interrupts and lastly we learnt how the <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23int-0x10">interrupt 0x10</a> and <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23int-0x16">interrupt 0x16</a> can be used and <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23implementation-of-interrupts-into-something-useful">how</a> can we implement them to read data from the screen and print it.</p>

<h1 id="author-notes">Author notes</h1>
<p>This post really took me so much of my time, efforts and understanding of different aspects of an Operating System. I tried the best way to explain everything and I hope that you also learnt so many new things throughout this blog post.  <br />
If you think this thing feels fascinating to you and you want to build your own fully-fledged Operating system, then you can continue learning OS dev and to make your lazy life easier, I have linked to different places where you can learn OS dev in the <a href="iframe.php?url=https%3A%2F%2Fde-engineer.github.io%2F%23resources">resources</a> section.</p>

<h1 id="resources">Resources</h1>
<ul>
  <li><a href="iframe.php?url=http%3A%2F%2Fwww.brokenthorn.com%2FResources%2FOSDev1.html">Operating system development series</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fraw.githubusercontent.com%2Ftuhdo%2Fos01%2Fmaster%2FOperating_Systems_From_0_to_1.pdf">Operating systems: from 0 to 1</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.cs.bham.ac.uk%2F%7Eexr%2Flectures%2Fopsys%2F10_11%2Flectures%2Fos-dev.pdf">Operating system development by Nick Blundell (University of Birmingham, UK)</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Flittleosbook.github.io%2F">Little book on Operating System development</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FFirmware">Firmware - wikipedia</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.freecodecamp.org%2Fnews%2Fuefi-vs-bios%2F">BIOS vs UEFI</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwiki.osdev.org%2FBoot_Sequence">Boot sequence (process) at osdev wiki</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.javatpoint.com%2Fbooting-in-operating-system">Booting in operating system</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FBooting">Booting - wikipedia</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fneosmart.net%2Fwiki%2Fmbr-boot-process%2F">MBR boot process</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwiki.osdev.org%2FBootloader">Bootloader - osdev wiki</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FBootloader">Bootloader wikipedia</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FPower-on_self-test">Power-on Self Test - POST</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F41912684%2Fwhat-is-the-purpose-of-the-rbp-register-in-x86-64-assembler">Purpose of base pointer - stackoverflow</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F17387492%2Fwhat-does-the-assembly-instruction-db-actually-do%3Frq%3D1">what does the assembly instruction ‘db’ actually do? - stackoverflow</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.quora.com%2FWhat-is-the-difference-between-an-instruction-and-a-directive-in-assembly-language">Difference between directive and instruction - quora</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.keil.com%2Fsupport%2Fman%2Fdocs%2Fa51%2Fa51_st_org.htm">The org directive in assembly</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fweb.archive.org%2Fweb%2F20190520163253%2Fhttp%3A%2F%2Fwww.ousob.com%2Fng%2Fasm%2Fng633bd.php">Interrupts guide</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fmicrocontrollerslab.com%2Fwhat-is-interrupt-vector-table%2F%23What_is_Interrupt_Vector_Table_IVT">Interrupt Vector Table</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FINT_%28x86_instruction%29">INT instruction x86</a></li>
  <li><a href="iframe.php?url=http%3A%2F%2Fwww.ctyme.com%2Fintr%2Fint-10.htm">Guide to interrupt 0x10</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2F4beginner.com%2F8086-assembly-language-int-10h-video-interrupt">Interrupt 0x10 assembly</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeI7Orib5giw">Interrupts and Interrupt Service Routines</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fwiki.osdev.org%2FInterrupt_Service_Routines">Interrupt Service Routines osdev wiki</a></li>
  <li><a href="iframe.php?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F30187367%2Fdifferences-between-int-10h-int-16h-int-21h">Differences between: INT 10H , INT 16H, INT 21H - stackoverflow</a></li>
</ul>]]></content><author><name>Mr. Rc</name><email>cr.retsim@gmail.com</email></author><category term="Programming" /><category term="Operating System Internals" /><summary type="html"><![CDATA[There are a lot of things that happen under the hood when we start a computer, we will be exploring those as well as trying to a small part of an OS.]]></summary></entry></feed>