<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Srinath Shrestha</title>
    <link>https://srinathshrestha.xyz</link>
    <description>rawdog dev notes</description>
    <item>
      <title>Is it in Swap or RAM</title>
      <link>https://srinathshrestha.xyz/blogs/swapvram</link>
      <guid>https://srinathshrestha.xyz/blogs/swapvram</guid>
      <pubDate>Sat, 26 Sep 2026 21:37:26 GMT</pubDate>
      <description>In the last piece I talked about how, upon a page fault, the kernel first asks two questions: does this address belong to you, and is this kind of access allowed? If both answers are yes, it grabs the page…</description>
      <content:encoded><![CDATA[<p>In the last piece I talked about how, upon a page fault, the kernel first asks two questions: does this address belong to you, and is this kind of access allowed? If both answers are yes, it grabs the page from wherever it lives and lets the program continue. (<a href="https://srinathshrestha.xyz/blogs/page-fault">The Fault That Isn&#39;t ?</a>)</p>
<p>This time I want to get specific about that <em>wherever</em>.</p>
<p><em>zest</em> :<br>When you run an executable from your SSD, the OS creates a process and its virtual address space, reads the ELF metadata, and learns which file ranges should correspond to which virtual-memory ranges. However it does not immediately copy every mapped section into RAM; pages are generally brought into physical frames as they are actually being accessed.</p>
<p>Then, while the program runs, it creates data that may not exist anywhere in the original files: heap data, stack data, computed values, or privately modified file-backed pages. If RAM gets tight and the kernel wants to evict one of those pages, it cannot simply throw it away because there may be no ordinary file from which those exact bytes can be recreated. So it can write the page’s contents to swap, which itself lives on storage</p>
<hr>
<p>Say I have a 100 GB game sitting on my SSD and I run:</p>
<pre class="code-block"><code>./game
</code></pre>
<p>Obviously 100 GB does not suddenly get copied into RAM. Ahhh! remember , Before I ran it, the game was just a collection of files sitting on storage: executable code, textures, models, sounds, libraries, configuration, etc . Once I execute it, the kernel creates a process and gives that process a virtual address space. Some ranges of that virtual address space are now <em>mapped</em>.</p>
<p>something like this ,</p>
<pre class="code-block"><code>some VA range → executable code
some VA range → initialized data
some VA range → heap
some VA range → shared libraries
some VA range → stack
</code></pre>
<p>and further more a mapped range does <strong>not</strong> mean every page in that range already has a physical frame in RAM. It important to understand , out the huge Virtual address space any few are actually being used in the program&#39;s code by the programmer , and also the executable bin, and from those few , only a few are there in the your RAM in an instance.</p>
<p>So, upon seeing a VA that is new, the kernel needs two answers: does this virtual address belong to some valid region, and does this virtual page currently have a physical frame in RAM? The first can be yes while the second is no. And that is the kernel&#39;s cue to go fetch or create the page&#39;s contents, place them into a physical frame, update the page table, and resume the process. Oh, and by the way, this whole idea of bringing a page into RAM only when it is actually demanded is called <strong>demand paging</strong>.</p>
<p>so by Now we have established the fact that every mapped region from the VM (or a frame ) has some source or rule for where its contents come from. Broadly, there are two important kinds: <strong>file-backed</strong> and <strong>anonymous</strong>.</p>
<h2 id="file-backed"><a class="heading-anchor" href="#file-backed" aria-hidden="true">#</a>File-backed</h2>
<p>A file-backed region has some file capable of supplying its contents.</p>
<p>The obvious example is your executable&#39;s code.</p>
<p>When the kernel loads an executable, it reads enough of the executable&#39;s metadata to learn things like , this part of the file contains executable code or this part contains initialized data or this file range should appear at this virtual address etc.</p>
<p>let&#39;s talk about how this happens , A file sitting on SSD does not have a process virtual address. It does, however, have <strong>file offsets</strong>. A file is ultimately a sequence of bytes.<br>So the kernel can remember something conceptually like ,</p>
<pre class="code-block"><code>virtual page 0x400000

comes from

./game
file offset 0x2000
</code></pre>
<p>Then later, if the CPU accesses that virtual page and it isn&#39;t in the Memory, the kernel knows where the original bytes live. It can read the corresponding part of the file into a physical frame, update the page table, and let execution continue. Code is not the only example. Initialized global data is also initially present inside the executable:</p>
<pre class="code-block"><code>int score = 42;
</code></pre>
<p>That <code>42</code> physically exists somewhere in the executable file. Shared libraries work the same way. Code from <code>libc.so</code>, some <code>.so</code>, or a <code>.dylib</code> is backed by those library files.<br>And then there are files that a program deliberately maps into memory using <code>mmap</code>.</p>
<hr>
<p>a tangent about the <code>mmap()</code></p>
<h3 id="aside-read-versus-mmap"><a class="heading-anchor" href="#aside-read-versus-mmap" aria-hidden="true">#</a>Aside: <code>read()</code> versus <code>mmap()</code></h3>
<p>A normal <code>read()</code> and <code>mmap()</code> connect a process to a file in fundamentally different ways. It is one of the ways a normal file can become the backing source of a virtual-memory region. Usually, if I want data from <code>numbers.bin</code>, I call <code>read()</code>. The kernel finds those bytes and copies them into some buffer that already belongs to my process. <code>mmap()</code> changes that relationship. Instead of copying the file into a buffer I chose, I ask the kernel to associate some range of the file with some range of my virtual address space , something like</p>
<pre class="code-block"><code>numbers.bin bytes 0–4095
           ↕
VA 0x700000–0x700fff
</code></pre>
<p>The file still stays where it is. What changes is that the kernel now knows that accesses to those virtual addresses are supposed to correspond to bytes from that file. If I later touch one of those addresses and its page is not in RAM, the resulting page fault gives the kernel enough information to fetch the appropriate page from <code>numberys.bin</code>.</p>
<p>And <code>mmap()</code> is not limited to files. It can also create an <strong>anonymous mapping</strong>: a virtual-memory region with no backing file at all. In that case, the pages start as fresh anonymous memory rather than bytes from disk.</p>
<hr>
<h2 id="anonymous"><a class="heading-anchor" href="#anonymous" aria-hidden="true">#</a>Anonymous</h2>
<p>Now the other kind. Anonymous memory is memory whose current contents are not backed by an ordinary file. The usual examples are the heap, the stack, and <code>.bss</code>.</p>
<p>I used to think it as “data the program generated,” and that works often enough to be misleading. The heap fits that description. The stack mostly fits too. But <code>.bss</code> breaks it. Take:</p>
<pre class="code-block"><code>static int hidden[1000000];
</code></pre>
<p>Because <code>hidden</code> is an uninitialized global, it lives in <code>.bss</code>, and C guarantees that it starts out filled with zeros. But those four million bytes of zeros are not sitting inside the executable on disk. The executable only records that this much zero-initialized memory needs to exist when the process runs. So when one of those pages is touched for the first time, the kernel does not go looking for its contents in a file. It simply provides a zero-filled page. That is called <strong>demand-zero paging</strong>: the virtual region already exists, but the actual page is only materialized when it is touched, and its initial contents are known to be zero.</p>
<p>a better simple def can be &quot; anonymous memory is memory for which there is no ordinary file that can reproduce the page’s current contents.&quot;</p>
<h3 id="aside-why-fresh-memory-has-to-be-zeroed"><a class="heading-anchor" href="#aside-why-fresh-memory-has-to-be-zeroed" aria-hidden="true">#</a>Aside: why fresh memory has to be zeroed</h3>
<p>Fresh anonymous memory is exposed to a process as zeroed memory. <code>.bss</code> is only one example; the same applies to fresh stack pages, heap pages obtained from the kernel, anonymous <code>mmap</code> regions ( not file mapping to VAs ) , and other anonymous mappings.</p>
<p>The reason is <code>process isolat</code>. A physical frame may have belonged to another process moments earlier, so the kernel cannot expose its leftover contents to the next one. File-backed pages are different: their initial contents come from the backing file, not from zero-fill.</p>
<p>This makes <code>malloc()</code> an interesting case, because in everyday C programming we are taught that memory returned by <code>malloc()</code> contains garbage. That sounds contradictory. If fresh anonymous memory from the kernel starts at zero, where does the garbage come from? <code>malloc()</code> is not asking the kernel for a brand-new page on every call. The allocator usually asks the kernel for larger regions of anonymous memory and then manages those regions itself. When you <code>free()</code> a chunk, <code>malloc()</code> may later hand that same chunk back to you without clearing it first. So the garbage you see in a <code>malloc()</code> allocation is generally stale memory from your own process or allocator bookkeeping, not secret leftovers from some unrelated process that previously owned the physical frame. And that is why <code>malloc()</code> does not promise zeros, while <code>calloc()</code> does.</p>
<h2 id="why-any-of-this-matters"><a class="heading-anchor" href="#why-any-of-this-matters" aria-hidden="true">#</a>Why any of this matters</h2>
<p>It gets imp when RAM gets tight and the kernel wants a frame back.</p>
<p>Suppose the victim is a clean file-backed page, say a page of <code>./game</code>&#39;s code. The copy in RAM is identical to the bytes already sitting in the executable, so there is nothing to save here. The kernel can discard the frame and, if the page is needed again, fault it back in from the original file. However Anonymous memory has no such escape hatch. Suppose a heap page now contains a value your program computed. Those exact bytes may exist nowhere except RAM. Throwing the page away would destroy part of the process&#39;s state. So before reclaiming that frame, the kernel needs somewhere to preserve the page. and that is <strong>swap file</strong>.</p>
<p>This is a useful way to think about swap: not extra RAM, and not as a stop between a program on disk and RAM ( this is what i used to think btw ;-) ) . So Pages reach swap as they are being pushed <strong>out of RAM</strong> so that we can use them later if needed.</p>
<h2 id="but-what-if-i-change-a-file-backed-page"><a class="heading-anchor" href="#but-what-if-i-change-a-file-backed-page" aria-hidden="true">#</a>But what if I change a file-backed page?</h2>
<p>So far the distinction has been neat. A file-backed page can be thrown away because the file can recreate it. An anonymous page cannot, so if we need to evict it, swap gives those bytes a parking space. But now suppose the CPU writes to a file-backed page. The file contains <code>X</code>, the page arrives in RAM containing <code>X</code>, and at this point the page is <strong>clean</strong>: RAM and its backing file agree. Then the program changes it to <code>Y</code>. Now RAM contains <code>Y</code>, while the file still contains <code>X</code>. The page is <strong>dirty</strong>. And kernel cannot just throw that page away anymore. If it did, <code>Y</code> would disappear and rereading the file would only bring back <code>X</code>.</p>
<p>So where should <code>Y</code> go? This is where another property of the mapping starts to matter: is it <strong>shared</strong> or <strong>private</strong>?</p>
<h3 id="shared-does-not-mean-shared-virtual-address"><a class="heading-anchor" href="#shared-does-not-mean-shared-virtual-address" aria-hidden="true">#</a>Shared does not mean shared virtual address</h3>
<p>This confused me for a while. Every process still has its own virtual address space. Two processes do not need to share the same VA for a mapping to be called shared. Process A might have a page at <code>0x700000</code>, while process B has it at <code>0x900000</code>, yet both virtual addresses can refer to the same underlying file-backed page. What is shared is not the virtual address. What is shared is the backing state.</p>
<p>Suppose both processes map the same part of <code>save.dat</code> using a writable <code>MAP_SHARED</code> mapping. The kernel records, when those mappings are created, that these virtual ranges correspond to this file and these file offsets, that writes are allowed, and that those writes belong to the shared file-backed state. Now suppose the file contains a score of <code>10</code>. The corresponding page is faulted into RAM. A process changes that score to <code>11</code>. The CPU has no concern about <code>save.dat</code>, SSDs, filesystems, or persistence. It simply stores a new value into memory. But that write makes the page dirty. The kernel already knows from the mapping metadata that this dirty page belongs to a shared mapping of <code>save.dat</code>. So unlike anonymous memory, this page already has somewhere appropriate for the new bytes to go: back to <code>save.dat</code>.</p>
<p>The kernel does not need to write it back immediately. It can keep the dirty page in RAM for a while, batch writes, and eventually flush it through the filesystem and storage stack. Once the file contains the same new bytes again, the page is clean. So a shared file-backed page can move through a little cycle: clean file-backed page → CPU writes → dirty file-backed page → writeback → clean again. And once it is clean again, the kernel can discard it whenever it needs the frame, because the file once again contains everything needed to recreate it.</p>
<h3 id="what-if-two-processes-write-the-shared-mapping"><a class="heading-anchor" href="#what-if-two-processes-write-the-shared-mapping" aria-hidden="true">#</a>What if two processes write the shared mapping?</h3>
<p>Then we have a concurrency problem. If process A writes one value and process B later writes another value to the same bytes, the later write is what remains in the shared memory. If both race, the result depends on timing, overlap, atomicity, and whatever synchronization the program uses. <code>MAP_SHARED</code> means the state is shared. It does not mean the kernel understands the intention behind each writer and somehow merges them. The filesystem&#39;s job comes later: take the dirty file-backed state and eventually get those bytes onto persistent storage. This also exposes another useful boundary. The CPU deals in virtual addresses, page-table permissions, physical memory, faults, and memory accesses. It has no concept of “this is <code>save.dat</code> at offset 8192.” That relationship lives in kernel VM and filesystem metadata. The CPU writes RAM. The kernel knows what that RAM represents.</p>
<h3 id="sharedprivate-and-readwrite-are-different-questions"><a class="heading-anchor" href="#sharedprivate-and-readwrite-are-different-questions" aria-hidden="true">#</a>Shared/private and read/write are different questions</h3>
<p>Another thing I kept mixing together was <strong>private</strong> and <strong>read-only</strong>. They are not the same thing. There are really two independent questions.</p>
<p>Can this mapping be written to?<br>And if it is written to, are those changes supposed to modify the backing file?</p>
<p>So a mapping can be shared and read-only, shared and writable, private and read-only, or private and writable. The read/write permissions answer whether the CPU is allowed to perform the access. Shared/private answers what a successful write is supposed to mean.</p>
<h3 id="private-mappings"><a class="heading-anchor" href="#private-mappings" aria-hidden="true">#</a>Private mappings</h3>
<p>Suppose the file again contains <code>X</code>, and I map it privately. The file still supplies the initial bytes. I can read <code>X</code> exactly as before. But if the mapping is writable and I change <code>X</code> to <code>Y</code>, that <code>Y</code> belongs only to my process. The original file must remain <code>X</code>. This is where copy-on-write enters. As long as I only read, there is no reason to create another copy. I can keep using the original file-backed page. The moment I write, the kernel gives my process private modified state instead. The file remains untouched.</p>
<p>Now we have an interesting situation.</p>
<p>The page originally came from the file, but the file no longer contains the version my process needs. My process has <code>Y</code>. The file still has <code>X</code>. If memory pressure arrives, the kernel cannot discard my <code>Y</code> and reread the file later, because that would resurrect <code>X</code>. It also cannot write <code>Y</code> back to the file, because the mapping was private. So that modified page has effectively crossed into the anonymous side of the story: its current contents are now private process state with no ordinary file capable of recreating them. If it has to leave RAM, swap can preserve it. And this is why saying “dirty page = swap” is wrong. A dirty <strong>shared</strong> file-backed page can eventually go back to its file. A dirty <strong>private</strong> file-backed page cannot, so its modified contents may need swap if evicted. Dirty tells us that RAM and the backing file have diverged. Shared/private tells us what the kernel is allowed to do about that divergence.</p>
<h3 id="data-is-the-perfect-example"><a class="heading-anchor" href="#data-is-the-perfect-example" aria-hidden="true">#</a><code>.data</code> is the perfect example</h3>
<p>Take: <code>int global_count = 42;</code> Unlike <code>.bss</code>, that <code>42</code> actually exists inside the executable, in <code>.data</code>. So initially the page is file-backed. The executable can provide the original bytes. Then the process runs: <code>global_count++;</code> Now the running process needs <code>43</code>. But obviously the kernel should not open the executable on disk and replace the original <code>42</code> with <code>43</code>. Otherwise simply running a program would slowly rewrite its binary. So writable <code>.data</code> is mapped privately. The executable supplies the starting state, but modifications belong to the process. That means the page begins life file-backed, but after the private write, the executable can no longer reconstruct the process&#39;s current version. The original file still knows <code>42</code>. The process now knows <code>43</code>. If that modified page is later evicted, <code>43</code> may have to survive in swap. This is the weird middle ground that makes the original file-backed/anonymous split less rigid than it first looked. A page can begin with a file as its source and later acquire private state that the file no longer represents.</p>
<h3 id="and-that-is-copy-on-write-again"><a class="heading-anchor" href="#and-that-is-copy-on-write-again" aria-hidden="true">#</a>And that is copy-on-write again</h3>
<p>This is the same idea we saw with <code>fork()</code>. Two processes can initially share one physical page because both see the same bytes. As long as nobody writes, there is no reason to duplicate anything. Then one process writes. That write faults under copy-on-write rules, and the writer gets its own private version while the other process keeps the original.</p>
<p>Same principle:</p>
<p>share the original while everybody agrees on the bytes; create private state only when somebody tries to diverge. The file-backed private case is doing essentially the same thing. The file provides the original state, and the first private write creates a process-specific version.</p>
<h3 id="shared-library-is-not-map_shared"><a class="heading-anchor" href="#shared-library-is-not-map_shared" aria-hidden="true">#</a>“shared library” is not <code>MAP_SHARED</code></h3>
<p>A <code>.so</code> or <code>.dylib</code> is called a shared library because many processes can use the same library code. That does not mean one process can casually edit the library for everyone else. The executable code pages of a shared library are normally mapped read-only and executable. Many processes can therefore reuse the same physical pages safely because nobody is allowed to modify them. Writable library data is generally private to each process. So “shared library” means its code can be shared across processes. It does not mean every mapping of that library is a writable <code>MAP_SHARED</code> mapping back to the <code>.so</code> or <code>.dylib</code>.</p>
<h2 id="back-to-the-100-gb-game"><a class="heading-anchor" href="#back-to-the-100-gb-game" aria-hidden="true">#</a>Back to the 100 GB game</h2>
<p>So now the original <code>./game</code> story has a fuller shape.</p>
<p>The game begins as files on storage. The kernel reads the executable metadata, creates a process and its virtual address space, and establishes which ranges correspond to which files or to anonymous memory. Pages are brought into RAM as demanded. Some pages remain clean and file-backed. If RAM gets tight, those are easy: discard them and fetch them again later. Some pages are anonymous from the beginning: stack, heap, <code>.bss</code>, anonymous mappings. Once they contain state the program needs, there is no ordinary file to recreate them, so swap can preserve them when their frames are reclaimed. And some pages start file-backed but become privately modified. The file supplied their original contents, but no longer represents their current ones. Those pages end up needing the same kind of preservation as anonymous memory. Which leaves me with a much better question than “is this code, heap, stack, or data?” If this page disappeared from RAM right now, where could the kernel get these exact bytes again? If the answer is “the executable at this offset,” discard it. If the answer is “this mapped file, once the dirty changes are written back,” flush it there. If the answer is “nowhere, these bytes belong only to this running process,” then the kernel has to preserve them somewhere else. And that somewhere is often swap.</p>
]]></content:encoded>
    </item>
    <item>
      <title>The Fault That Isn't ?</title>
      <link>https://srinathshrestha.xyz/blogs/page-fault</link>
      <guid>https://srinathshrestha.xyz/blogs/page-fault</guid>
      <pubDate>Wed, 26 Aug 2026 20:11:23 GMT</pubDate>
      <description>Last time: the MMU reads a PTE, and the valid bit is 0. The hardware cannot proceed, so it stops and hands the whole mess to the kernel. That's a page fault. (The TLB) The name ? A page fault…</description>
      <content:encoded><![CDATA[<p>Last time: the MMU reads a PTE, and the valid bit is 0. The hardware cannot proceed, so it stops and hands the whole mess to the kernel. That&#39;s a page fault. (<a href="https://srinathshrestha.xyz/blogs/tlb">The TLB</a>)</p>
<h2 id="the-name-"><a class="heading-anchor" href="#the-name-" aria-hidden="true">#</a>The name ?</h2>
<p>A page fault is not an error. It is the normal, routine, designed mechanism by which memory gets loaded, and your machine is servicing thousands of them a second right now, this exact second, while you read this. &quot;Fault&quot; here means &quot;the hardware hit a wall it can&#39;t get past alone and needs software to take over&quot; - not &quot;something broke.&quot; Same word English uses for &quot;it&#39;s not your fault,&quot;.</p>
<p>(Small tangent, because I fell for this exact thing for a month or two of writing C: I used to think a page fault and a segfault were basically the same event with two names. They&#39;re not, and the difference is the entire point of this post. Anyway.)</p>
<h2 id="three-questions-in-order"><a class="heading-anchor" href="#three-questions-in-order" aria-hidden="true">#</a>Three questions, in order</h2>
<p>When the fault lands, the kernel runs through a fixed sequence of instruction or rather you can say interrupt, and where you fall out of that sequence is the difference between a routine lazy load nobody ever notices and your program exiting with <code>SIGSEGV</code>.</p>
<p><strong>1. Does this address even belong to you?</strong></p>
<p>The kernel keeps a list of the legitimate regions of your address space, on Linux, <code>vm_area_struct</code> records, one per mapped region: code, heap, stack, each shared library, each <code>mmap</code>ed file. The faulting address gets checked against that list. if it&#39;s Outside all of them? You referenced memory you were never given in the first place. Dereferencing <code>NULL</code> dies here, and so does a wild pointer that wandered off into nothing.</p>
<p>→ <strong>SIGSEGV.</strong></p>
<p>btw this is a kernel SIG.</p>
<p><strong>2. Fine, it&#39;s yours, but is <em>the kind</em> of access allowed?</strong></p>
<p>Legal address but wrong permission. Writing to your own read-only code section (something like .rodata). User code reaching for a kernel-only page. Trying to execute a page that&#39;s marked no-execute. Here The address checks out but the <em>verb</em> do not.</p>
<p>again → <strong>SIGSEGV.</strong></p>
<p><strong>3. It&#39;s a legal address, a permitted access but the page just isn&#39;t in RAM yet.</strong></p>
<p>This is overwhelming majority of the cases, and it&#39;s the one that&#39;s actually interesting: the kernel picks a victim frame, writes it back if it was dirty, fetches the page you actually wanted from wherever it lives, updates the PTE, and restarts the exact instruction that faulted.</p>
<p>Restarts it. Not resumes , restarts, from the top of that one instruction. The instruction can&#39;t know any of this happened. It fires, gets yanked out from under itself mid-flight, and fires again, and from the program&#39;s point of view, sure the whole thing just took a while, but No error code. No signal. Nothing to catch. It simply worked, eventually.</p>
<p>So: &quot;segfault&quot; isn&#39;t a curse the universe put on your code. It&#39;s the part of the plan. Your address failed check 1 or check 2, and you can usually tell which just by looking at what you touched.</p>
<h2 id="the-checking"><a class="heading-anchor" href="#the-checking" aria-hidden="true">#</a>The checking</h2>
<p>None of this is free-floating logic somewhere in the kernel&#39;s head. It&#39;s bits, sitting right there in the PTE the hardware was already reading. On x86-64:</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Bit</th>
<th>What it means</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>P</strong> (present)</td>
<td>is this page actually in RAM right now</td>
</tr>
<tr>
<td><strong>R/W</strong></td>
<td>read-only vs read-write</td>
</tr>
<tr>
<td><strong>U/S</strong></td>
<td>user-accessible vs kernel-only</td>
</tr>
<tr>
<td><strong>A</strong> (accessed)</td>
<td>hardware sets this on any reference — feeds the eviction policy</td>
</tr>
<tr>
<td><strong>D</strong> (dirty)</td>
<td>hardware sets this on any write — tells the kernel this page needs writing back</td>
</tr>
<tr>
<td><strong>XD</strong> (execute-disable)</td>
<td>instruction fetch from this page is forbidden</td>
</tr>
</tbody>
</table></div>
<p>That last one has a real history. Before it existed, an attacker who could smuggle bytes into a writable buffer could often just jump execution straight into it and run those bytes as code. XD lets the kernel draw a hard line , that , this region holds data, and data is never code, Period. And it killed an entire family of exploit outright. Same story as everything else in this series: the check costs nothing, because the hardware was reading that PTE anyway.</p>
<p>Right. Go home.</p>
<p>Except we&#39;ve been saying &quot;fetches the page from wherever it lives&quot; for two posts now, and I&#39;ve never told you where &quot;wherever&quot; actually is. Two very different answers, and which one applies to a given page decides almost everything else about how it behaves , whether it can be thrown away for free or has to be written somewhere first, what swap is actually for, why an initialized global is weirder than it looks. see you in next one.</p>
]]></content:encoded>
    </item>
    <item>
      <title>The TLB</title>
      <link>https://srinathshrestha.xyz/blogs/tlb</link>
      <guid>https://srinathshrestha.xyz/blogs/tlb</guid>
      <pubDate>Wed, 26 Aug 2026 20:01:13 GMT</pubDate>
      <description>Last time we translated 0x03d4 with a table lookup and a concatenate. That has to run on every load and store, so it has to be nearly free. Except the table lives in memory. To read one byte you first…</description>
      <content:encoded><![CDATA[<p>Last time we translated <code>0x03d4</code> with a table lookup and a concatenate. That has to run on every load and store, so it has to be nearly free. Except the table lives in memory. To read one byte you first go to memory for the PTE, <em>then</em> go to memory for the data. Every access became two. (<a href="https://srinathshrestha.xyz/blogs/pages">Pages</a>)</p>
<h2 id="the-extra-trip"><a class="heading-anchor" href="#the-extra-trip" aria-hidden="true">#</a>The extra trip</h2>
<p>You&#39;ve doubled the cost of memory, which is a spectacular way to destroy performance.</p>
<p>The fix is the <strong>TLB</strong>, translation lookaside buffer. It&#39;s a small, highly associative cache of recently used PTEs, and critically it sits <em>inside the MMU itself</em>, on the SoC , not in RAM, and not in L1 either. Separate structure. Tiny. Fast.</p>
<p>Before walking the page table, check the TLB:</p>
<ul>
<li><strong>TLB hit:</strong> the translation is already on-chip. No page-table access at all.</li>
<li><strong>TLB miss:</strong> walk the page table, then cache the result for next time.</li>
</ul>
<p>If the TLB is set-associative, the VPN splits the same way any cache key does: <strong>TLBI</strong> (index: which set) and <strong>TLBT</strong> (tag: did we get the right entry). Many L1 TLBs are so small they are highly associative, or fully associative, and just match the VPN (plus an address-space id) which is Same idea, cache translations, not bytes.</p>
<p>And it works very well, for the same reason all caching works: <strong>locality</strong>.</p>
<ul>
<li><strong>Temporal locality</strong> — if you used something recently, you&#39;ll probably use it again soon.</li>
<li><strong>Spatial locality</strong> — if you used something, you&#39;ll probably use what&#39;s next to it.</li>
</ul>
<p>A loop over an array hits the same page hundreds of times in a row. One TLB entry covers an entire page (4 KiB or 16 KiB). A well written programs hit in the TLB the overwhelming majority of the time.</p>
<p>Two more pieces.</p>
<p><strong>Where do the CPU caches sit?</strong> Translation happens, then you have a physical address, then you look in the data caches. L2 and L3 are physically addressed. L1 is often <strong>virtually indexed, physically tagged</strong> (VIPT): it can start the set lookup from the virtual address in parallel with the TLB, and it confirms the line with the physical tag once the TLB answers. Either way, you do not wait for DRAM to know &quot;which page&quot; before the cache even begins.</p>
<pre class="code-block"><code>   virtual address
        ↓
   TLB ──hit──→ physical address
        │              ↓
      miss           L1 → L2 → L3
        ↓              ↓
   walk page table   DRAM
</code></pre>
<p><strong>And what makes a TLB miss not that costly?</strong> The page table is data in memory like any other data, so PTEs get cached in L1 and L2 like anything else. A TLB miss usually doesn&#39;t mean a trip to DRAM. It means a trip to L1.</p>
<p>One thing the last post left hanging: when the kernel writes CR3 / TTBR, those TLB entries were for the <em>old</em> table. Historically that write flushed the TLB. Modern chips tag entries with an <strong>ASID</strong> (ARM) / <strong>PCID</strong> (x86), so you can keep the other process&#39;s translations around instead of throwing them away on every switch.</p>
<h2 id="the-flat-table-"><a class="heading-anchor" href="#the-flat-table-" aria-hidden="true">#</a>The flat table ?</h2>
<p>let take a case , Start modest: a 32-bit address space, 4 KiB pages, 4-byte PTEs. That&#39;s 2^20^ pages which is about a million , times 4 bytes, so <strong>4 MiB of page table</strong>. Per process. Fully resident, all the time, even for a program that touches three pages and exits.</p>
<p>Now 64-bit. Even restricting to the <strong>48 bits</strong> typical x86-64 actually implements, a flat table with 8-byte PTEs is <code>2^(48-12) × 8</code> bytes = <strong>512 GiB</strong>. Per process. To describe a program using eight kilobytes. (The full 64-bit space is worse. Five-level / 57-bit x86 is the &quot;hundreds of terabytes&quot; version.)</p>
<p>The absurdity has an obvious cause when you name it: address spaces are overwhelmingly <strong>empty</strong>. Your program has some code down low, a heap growing up, a stack growing down, some libraries mapped in the middle, and between those regions, nothing mapped. Astronomically much nothing. A flat table dutifully allocates an entry for every page of that nothing.</p>
<p>The fix is a <strong>hierarchy</strong>. Instead of one enormous table, a small top-level table whose entries either point to a second-level table <em>or are null</em>.</p>
<p>And there&#39;s the win: <strong>if an entire region of the address space is unused, its top-level entry is null and the lower-level table for that region is never created at all.</strong> The empty parts cost one null entry each, not millions of PTEs. Only the top level must always be resident; the levels below get created on demand, and can themselves be paged out like ordinary data.</p>
<p>x86-64 uses <strong>four</strong> levels, each indexed by a 9-bit slice of the VPN, with the physical address of the top table in CR3. (2^9^ = 512 entries per table, times 8 bytes, is exactly 4 KiB — one page. The page table is made of pages. Everything is pages.) Apple Silicon with 16 KiB pages uses a different split: <strong>three</strong> levels of 11 bits over a 14-bit offset, because the page size changes the arithmetic. 2^11^ × 8 bytes = 16 KiB. Same trick. The principle is identical.</p>
<p>The obvious objection: doesn&#39;t a four-level table mean four memory accesses per translation instead of one? Yes. That&#39;s <em>exactly</em> what the TLB is for. On a hit, you walk <strong>zero</strong> levels.</p>
<p>Right. Go home.</p>
<p>Except the MMU reads a PTE and the valid bit is <strong>0</strong>. The hardware cannot proceed. That is a <strong>page fault</strong>, and the name is a lie. That&#39;s next.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Pages</title>
      <link>https://srinathshrestha.xyz/blogs/pages</link>
      <guid>https://srinathshrestha.xyz/blogs/pages</guid>
      <pubDate>Wed, 26 Aug 2026 00:06:19 GMT</pubDate>
      <description>Last time: the kernel gives you a table, and that table cannot have a row for every byte. A 64bit keyspace, one entry per byte, and the table is larger than the memory it describes. So we don't translate bytes.…</description>
      <content:encoded><![CDATA[<p>Last time: the kernel gives you a table, and that table cannot have a row for every byte. A 64-bit keyspace, one entry per byte, and the table is larger than the memory it describes. So we don&#39;t translate bytes. We translate <strong>chunks</strong>. That&#39;s the grid ASLR was snapping to. (<a href="https://srinathshrestha.xyz/blogs/one-table-three-jobs">A Table</a>)</p>
<h2 id="pages"><a class="heading-anchor" href="#pages" aria-hidden="true">#</a>Pages</h2>
<p>Let&#39;s talk about the size of the thing we&#39;re translating, because it&#39;s the first design decision and it constrains everything downward. You cannot translate individual bytes. Do the arithmetic: a 64-bit address space, one table entry per byte, and the table is unfathomably larger than the memory it describes. It&#39;s absurd. So we chunk them up.</p>
<p>In the virtual world, those chunks are called <strong>pages</strong>. In physical memory, the equally-sized slots they land in are called <strong>frames</strong>, sometimes &quot;page frames,&quot; or &quot;physical pages,&quot; which is the term CS:APP prefers. Not buffers. A buffer is a different thing entirely. Page in, frame out. Same size on both sides, which is what makes the mapping work: a page slots into any frame, Fully associative.</p>
<p>How big is the page ? Typically 4 KiB, which is the historical default and the number every textbook quotes. Apple Silicon uses 16 KiB, which is exactly the grid ASLR was snapping to, <code>0x104720000</code> and <code>0x104c54000</code> were both multiples of <code>0x4000</code>. Modern systems also support &quot;huge pages&quot; of 2 MiB or 1 GiB for workloads that touch enormous contiguous regions and would otherwise drown in translation overhead.</p>
<p>But <em>why</em> that size range? Two competing forces, pushing in from opposite directions. Pages want to be <strong>big</strong>, because bookkeeping cost is per-page. Halve the page size and you double the number of table entries you have to store and walk. Big pages also amortize disk transfers: reading from disk has a huge fixed cost per operation, so once you&#39;ve paid to go there at all, you want to come back with a lot.</p>
<p>Pages want to be <strong>small</strong>, because you waste the leftovers. Allocate a page for a 40-byte object and the remaining 16,344 bytes are gone. And when memory is tight, you&#39;d rather evict at fine granularity than throw out 16 KiB to reclaim space for 40 bytes.</p>
<p>Four to sixteen kilobytes is where those pressures balance out for typical workloads. That band is not a folklore number someone copied from a textbook. People actually measured it, and the honest result is that <strong>there is no one globally optimal page size</strong>. <a href="https://doi.org/10.1016/0166-5316(83)90030-5">Alanko and Verkamo (1983)</a> ran production programs through a working-set simulator and got two kinds of jobs: some want small pages and a large window, some want the reverse. What Intel shipped on the 386 was still <strong>4 KiB</strong>, because that sat in the 512 B–4 KiB range machines of that era already used. IBM&#39;s <a href="https://en.wikipedia.org/wiki/IBM_System/360_Model_67">System/360 Model 67</a> — one of the first production DAT / virtual-memory machines — already used 4096-byte pages in the mid-1960s. Later work keeps arguing the <em>base</em> should move with RAM: <a href="https://doi.org/10.1109/IRI.2009.5211562">Weisberg and Wiseman (2009)</a> simulated SPEC2000 and recommended <strong>16 KiB</strong>, which is exactly what Apple Silicon did. A <a href="https://www.sigarch.org/larger-pages/">2022 SIGARCH note</a> makes the same case for raising the minimum, not just bolting on huge pages.</p>
<p>Now, splitting an address. This part is genuinely elegant.</p>
<p>If a page is 16 KiB, that&#39;s <span class="math math-inline" data-math="2^{14}">$2^{14}$</span> bytes, so <strong>the low 14 bits of any address are the position within its page.</strong> Not by convention — arithmetically. Those 14 bits count 0 through 16,383, which is exactly one page&#39;s worth of bytes. Everything above them identifies <em>which</em> page.</p>
<p>So every virtual address has two fields:</p>
<pre class="code-block"><code>   virtual address
   ┌──────────────────────────┬────────────────────┐
   │          VPN             │        VPO         │
   │   virtual page number    │   offset in page   │
   └──────────────────────────┴────────────────────┘
</code></pre>
<p><strong>VPN</strong>: virtual page number. <strong>VPO</strong>: virtual page offset. The CPU doesn&#39;t compute these, and the instruction doesn&#39;t encode them. They&#39;re just <em>which bits you look at</em>. The address <code>0x104720000</code> is a VPN and a VPO the same way the number 1,432 is &quot;fourteen hundreds and thirty-two.&quot;</p>
<p>And on the physical side, the identical split: <strong>PPN</strong> (physical page number) and <strong>PPO</strong> (physical page offset). <strong>PPO always equals VPO.</strong> Always. Translation only ever changes <em>which page</em>, never <em>where in the page</em>, because pages are aligned and the same size on both sides. Byte 900 of a page is byte 900 of that page no matter which frame it&#39;s sitting in.</p>
<p>Which means the entire operation is: look up the VPN to get a PPN, then glue the untouched VPO onto the end.</p>
<h2 id="page-table--kernel"><a class="heading-anchor" href="#page-table--kernel" aria-hidden="true">#</a>Page table &amp; kernel</h2>
<p>That lookup needs somewhere to look. It&#39;s the <strong>page table</strong>: an array of <strong>page table entries</strong>, PTEs, one entry per virtual page in the address space. Each PTE is a small fixed-size record (8 bytes on x86-64). It always contains a <strong>valid bit</strong> (also called the Present bit). The rest of the entry is interpreted according to that bit:</p>
<ul>
<li>if the valid bit is set, the entry holds the <strong>physical page number</strong> PPN of the frame that currently contains this page.</li>
<li>if the valid bit is clear, the entry either holds enough information for the kernel to locate the page later, or it holds nothing at all.</li>
</ul>
<p>that gives every virtual page one of three possible states at any moment:</p>
<ul>
<li><strong>Unallocated</strong> — the page was never requested. And it costs nothing.</li>
<li><strong>Cached</strong> — the page is currently sitting in a physical frame.</li>
<li><strong>Uncached</strong> — the page exists, but its contents live on disk (or in swap) rather than in RAM.</li>
</ul>
<p>The single most important fact about page tables is this:</p>
<p><strong>Every process has its own private page table.</strong></p>
<p>That is what makes the opening demo work. (<a href="https://srinathshrestha.xyz/blogs/same-address-two-values">Same address but two values</a>) Parent and child each have a separate table. Both tables contain an entry for the virtual page that holds <code>value</code>. After the first write triggers copy-on-write, those two entries point at two different physical frames. Same VPN but different PPN. Same printed address and completely different memory.</p>
<p>The kernel owns the tables. It builds them when a process is created, updates a PTE when a page is brought in (or written for the first time under copy-on-write), and destroys the whole table when the process exits. The MMU does not construct mappings. It <strong>reads</strong> PTEs on every translation. (It does write two status bits later — Accessed and Dirty — so the kernel can tell what was used and what needs writeback. That&#39;s bookkeeping, not &quot;the MMU decided your layout.&quot;)</p>
<p>So how does the MMU even <em>find</em> the table? The table itself lives in ordinary physical memory. A dedicated register holds the physical address of the root of the current process&#39;s page table. On x86-64 that register is <strong>CR3</strong>. The textbook name is <strong>PTBR</strong> (page-table base register). Apple Silicon&#39;s equivalent is <strong>TTBR</strong>.</p>
<p>Once the register is loaded, finding any PTE in this one-level picture is index arithmetic:</p>
<pre class="code-block"><code>PTE address = PTBR + (VPN × size of a PTE)
</code></pre>
<p>Real 64-bit machines do not store one giant array like this. The table is a tree. That&#39;s the next problem. For now this is the whole mechanism: one array, VPN is the index.</p>
<p>And now the part that makes multitasking possible: <strong>the kernel rewrites that register when it switches to a different address space.</strong> Switching from your browser to your editor doesn&#39;t move any memory around. It changes one register, and instantly every virtual address in the machine means something different. Two threads of the same process share a table, so that switch does not touch CR3.</p>
<h2 id="eg"><a class="heading-anchor" href="#eg" aria-hidden="true">#</a>e.g..</h2>
<p>Let&#39;s walk a real address through, with small numbers so the bit-fiddling is visible. This is the worked example from CS:APP.</p>
<p>Setup: 14-bit virtual addresses, 12-bit physical addresses, 64-byte pages.</p>
<p>64 bytes is <span class="math math-inline" data-math="2^6">$2^6$</span>, so <strong>the low 6 bits are the offset.</strong> Everything above is the page number.</p>
<p>The address: <code>0x03d4</code>.</p>
<p>In binary, across 14 bits:</p>
<pre class="code-block"><code>   0 0 0 0 1 1 1 1 | 0 1 0 1 0 0
   └── VPN ───────┘ └─ VPO ────┘
</code></pre>
<p>The top 8 bits are <code>0b00001111</code> = <code>0x0F</code>. That&#39;s the VPN. The low 6 bits are <code>0b010100</code> = <code>0x14</code>. That&#39;s the VPO.</p>
<p>So: <strong>VPN = 0x0F, VPO = 0x14.</strong></p>
<p>The MMU indexes the page table at entry <code>0x0F</code>. Say that entry is valid and holds PPN <code>0x0D</code>.</p>
<p>Now glue:</p>
<pre class="code-block"><code>   PPN 0x0D        VPO 0x14
   0 0 1 1 0 1 | 0 1 0 1 0 0
   └──────────── 0x354 ─────────┘
</code></pre>
<p>Physical address: <strong><code>0x354</code></strong>.</p>
<p>Notice that PPN is <em>concatenated</em> with VPO, shifted up into the high bits and the offset dropped in below. This trips me up constantly. <code>0x0D + 0x14</code> is <code>0x21</code>, which is not the answer.</p>
<p>And that&#39;s it. A table lookup, followed by a bit-concatenation. This runs on <strong>every single memory access your machine performs</strong>, billions of times a second, so it has to be nearly free of any perf cost.</p>
<p>Right. Go home.</p>
<p>Except the page table lives in memory. To read one byte you first go to memory for the PTE, <em>then</em> go to memory for the data. Every access became two. That&#39;s Can be costly. That&#39;s next.</p>
]]></content:encoded>
    </item>
    <item>
      <title>A Table</title>
      <link>https://srinathshrestha.xyz/blogs/one-table-three-jobs</link>
      <guid>https://srinathshrestha.xyz/blogs/one-table-three-jobs</guid>
      <pubDate>Tue, 25 Aug 2026 23:38:01 GMT</pubDate>
      <description>In the last piece we saw our prog printed 0x104720000 while holding a 3 and a 300. The curveball was that the number isn't a location. It's a lookup key, and each process resolves it differently. (Same address but two…</description>
      <content:encoded><![CDATA[<p>In the last piece we saw our prog printed <code>0x104720000</code> while holding a <code>3</code> and a <code>300</code>. The curveball was that the number isn&#39;t a location. It&#39;s a lookup key, and each process resolves it differently. (<a href="https://srinathshrestha.xyz/blogs/same-address-two-values">Same address but two values</a>). So if addresses aren&#39;t locations, how has any of your code been working?</p>
<h2 id="addr-in-instructions-"><a class="heading-anchor" href="#addr-in-instructions-" aria-hidden="true">#</a>Addr in instructions ?</h2>
<p>Your code is <em>full</em> of addresses. Pointers, arrays, function calls, the stack. If addresses aren&#39;t real, how has any of it been working? The answer is that your program never depended on a real one. AKA <strong>virtual addresses</strong>.</p>
<p>Here&#39;s the precise cliam, <strong>You have never written a physical address.</strong> A non-PIE linker can bake numbers into jump tables and immediates that look like addresses — those are still <em>virtual</em>, patched at load time, not physical locations in RAM. On a PIE binary (what you actually ran), the baked number is usually a distance anyway. Either way: never a physical address.</p>
<p>More than that, an enormous fraction of what your program does is expressed as <strong>offsets</strong> or simply put distances, rather than absolute positions. Cuz Distances works well with relocation. Positions don&#39;t.</p>
<p>Take an array for example</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">int arr[10];
</code></pre></div>
<p><code>arr</code> and <code>&amp;arr[0]</code> are the same address. The array <em>is</em> its first element&#39;s location, so it&#39;s not wrong to say that we address an array by its first element&#39;s address. And <code>arr[5]</code> isn&#39;t some table lookup. The compiler emits arithmetic, which put simply can look like , take the base, add 5 × 4 bytes, load from there. Every array access you have ever written is base-plus-offset. Strings are the same thing, a <code>char</code> array, terminated by a <code>&#39;\0&#39;</code>, indexed by adding a distance to a base. (For anyone reading this from beyond the grave, I know it&#39;s called null-terminated char array.)</p>
<p>The stack works the same way. A local variable isn&#39;t at some absolute address the compiler knew about. It&#39;s at <em>the frame pointer minus twenty</em>, or <em>the stack pointer plus eight</em>. Push a frame, and every local in it shifts along with the frame; the offsets inside the frame don&#39;t change at all. That&#39;s why recursion works. And function calls, too, but there is where I want to stress on a wrong understanding i used to have all the time, because it&#39;s really important. A <code>call</code> instruction on x86-64 usually encodes its target as a <strong>relative displacement</strong>, not &quot;jump to address X&quot; rather &quot;jump 2 or 142 bytes past the <em>next</em> instruction&quot; — relative to the address of the instruction <em>after</em> the <code>call</code>, not the <code>call</code> itself. Relocatable. But <code>ret</code> is <em>not</em> relative. <code>call</code> pushes the absolute <strong>virtual</strong> return address onto the stack (the VA of that next instruction), and <code>ret</code> pops that VA and jumps to it. The MMU still translates it. Relative call, absolute-VA return, commit to memory.</p>
<p><em>(While we&#39;re being precise: x86-64 instructions are variable-length, anywhere from 1 to 15 bytes, with 15 being the hard architectural ceiling rather than anything typical; most are two to five. Base RISC-V instructions are 4 bytes; the compressed extension, which a lot of chips actually ship, is 2. Still a lot more regular than x86.)</em></p>
<p>And then there&#39;s the move that ties it all together: <strong>RIP-relative addressing</strong>. When your compiled code wants a global variable, it doesn&#39;t emit &quot;load from <code>0x104720000</code>.&quot; It emits something closer to:</p>
<div class="code-container"><span class="code-language">asm</span><pre class="code-block language-asm"><code class="language-asm">mov rax, [rip + 0x2f31]
</code></pre></div>
<p>Meaning: take RIP as it will be <em>after</em> this instruction (the address of the next one), add 12,081, load from there. Not the address of the <code>mov</code> itself , x86-64 RIP-relative is always relative to the following instruction. The <code>mov</code> has no idea where it sits. It only knows how far away its data is, and that distance is fixed forever at link time regardless of where the whole program ends up sitting.</p>
<p>this is where i plug my <a href="https://srinathshrestha.xyz/blogs/linking">linking</a> blog ;)</p>
<blockquote><p>which is why the following is possible,<br><strong>run the first program again. The address changed.</strong> Mine went from <code>0x104720000</code> on one run to <code>0x104c54000</code> on the next, while the binary has not recompiled. The loader dropped the entire program at a different base address, and the program was completely unbothered; every pointer inside it still worked perfectly. That&#39;s <strong>ASLR</strong>, address space layout randomization, and the reason for it is security. A whole family of exploits works by corrupting memory and then redirecting execution to a known address, a function you didn&#39;t mean to call, a buffer the attacker filled. All of it depends on the attacker knowing where things are. So the kernel stops telling them. Every launch, the code, the stack, the heap, and the shared libraries all land somewhere new. This only works because the binary is a <strong>PIE</strong>, position-independent executable, built entirely out of offsets, exactly as described above. On Linux, you can opt out with <code>-no-pie</code> and watch the address freeze. On Apple Silicon, you can&#39;t; it&#39;s mandatory.</p>
<p>My two addresses were <code>0x104720000</code> and <code>0x104c54000</code>. Both end in three zeros. Both are exact multiples of <code>0x4000</code> — 16,384, or 16 KiB. The randomizer isn&#39;t choosing arbitrary byte offsets. It&#39;s choosing from a grid. Hold onto that; we&#39;re about to find out what the grid is.</p>
</blockquote>
<p>So the TL;DR here is , your program is built out of distances. Distances don&#39;t care where you put them. The operating system is therefore free to drop your program absolutely anywhere in the <strong>virtual</strong> address space (on a page grid, we&#39;ll get there). That&#39;s ASLR. Physical RAM is a different knob , the MMU picks those frames later.</p>
<p>Every Process either you spwan it through your program or a program forks it , they get their own Virtual address space, private , isolated. On paper a 64-bit CPU can name <span class="math math-inline" data-math="2^{64}">$2^{64}$</span> addresses. Real silicon is smaller: <strong>48 bits</strong> of virtual address on typical x86-64 (four-level page tables), <strong>47 bits</strong> on Apple Silicon with 16 KiB pages (three 11-bit levels plus a 14-bit offset). Still <mark>enormous</mark>. Each process gets that whole logical space.</p>
<p>The addresses your program produces , <code>0x104720000</code> and friends, live in that virtual range <em>before</em> the MMU touches them. After the MMU, you have a physical address, and that one has to land in actual DRAM, 16 GB or whatever you have. That is really the crux of VM.</p>
<h2 id="pa-feasible-"><a class="heading-anchor" href="#pa-feasible-" aria-hidden="true">#</a>PA Feasible ?</h2>
<p>Physical addressing: the CPU emits an address, the address goes straight to the memory bus, the memory responds. Works <em>perfectly</em>. It&#39;s what early machines did. It&#39;s what the microcontroller in your washing machine does. It&#39;s simple, it&#39;s fast, and there is nothing wrong with it , right up until you want to run two programs at once. Then it fails in three distinct ways.</p>
<p><strong>It collides.</strong> Your compiler needs to decide where <code>value</code> lives. Say it picks <code>0x104720000</code>. Fine. Now run two copies of the program. Both want that exact byte. (cuz it can , nothing is there to prevent it) . One of them has to lose, which means the compiler can&#39;t ever hardcode anything, which means every program has to be relocated at load time against every other program currently running. It&#39;s a scheduling nightmare that changes every time a user launches something.</p>
<p><strong>It can&#39;t be protected.</strong> If any program can name any physical byte, then any program can <em>write</em> any physical byte. A bug in your text editor can scribble over the kernel. A malicious PDF reader can read your password manager&#39;s memory. There&#39;s no wall to put up, because there&#39;s no place to put the wall; the CPU is handing raw addresses to raw memory and nothing is in between to enforce protection.</p>
<p><strong>And, yes, it doesn&#39;t fit.</strong> Your machine has, what, 16 GB? Your game folder is 90. Something has to give up.</p>
<p>Now here&#39;s the thing about virtual memory which is beautiful. <strong>One mechanism fixes all three.</strong></p>
<p>Put a translation step between the CPU and the memory bus. The CPU generates a virtual address; a piece of dedicated hardware called the <strong>MMU</strong> ( memory management unit ) translates it into a physical address using a table the kernel maintains; only <em>then</em> does anything reach memory. And once that translation is happening on every single access anyway,</p>
<ul>
<li>Give each process its own table, and two processes can use identical addresses that resolve to different memory. <strong>Collision solved.</strong>.</li>
<li>Since the table is being consulted anyway, staple a few permission bits onto each entry. Readable? Writable? Executable? Kernel-only? The check costs nothing because the lookup was already happening. <strong>Protection solved.</strong>.</li>
<li>And let entries say &quot;not currently in memory,&quot; so that memory can act as a <em>cache</em> for a much larger space that actually lives on disk or network. <strong>Capacity solved.</strong></li>
</ul>
<p>If you take away one idea from this piece, take that.</p>
<p>That&#39;s why the demo worked. The kernel did not hand parent and child a byte at <code>0x104720000</code>. It handed each of them a <strong>table</strong>. The MMU looks up the same key in whichever table is currently installed. After the first write, those two entries point at two different pieces of RAM. Same printed number. Completely different memory.</p>
<p>The kernel never gives you memory. It gives you a table.</p>
<p>Right. Go home.</p>
<p>Except the table cannot have a row for every byte. A 64-bit keyspace, one entry per byte, and the table is larger than the memory it describes. So we don&#39;t translate bytes. We translate <strong>chunks</strong>. That&#39;s the grid ASLR was snapping to. That&#39;s next.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Same Address but two diff val</title>
      <link>https://srinathshrestha.xyz/blogs/same-address-two-values</link>
      <guid>https://srinathshrestha.xyz/blogs/same-address-two-values</guid>
      <pubDate>Tue, 25 Aug 2026 22:38:36 GMT</pubDate>
      <description>Try to compile this and run it. Don't worry that it's C; it's C, thus it's easy to understand things in it. Here's what I got: Did you see it? No? No worries. value is a single global variable, declared…</description>
      <content:encoded><![CDATA[<p>Try to compile this and run it. Don&#39;t worry that it&#39;s C; it&#39;s C, thus it&#39;s easy to understand things in it.</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">#include &lt;stdio.h&gt;
#include &lt;unistd.h&gt;
#include &lt;sys/wait.h&gt;

int value = 0;

int main(void) {
    printf(&quot;before fork- &amp;value = %p\n&quot;, (void *)&amp;value);
    fflush(stdout);
    pid_t pid = fork();
    int step = (pid == 0) ? 1 : 100;
    for (int i = 0; i &lt; 5; i++) {
        value += step;
        printf(&quot;pid %d: &amp;value = %p, value = %d\n&quot;,
               getpid(), (void *)&amp;value, value);
        sleep(1);
    }
    if (pid &gt; 0) wait(NULL);
    return 0;
}
</code></pre></div>
<p>Here&#39;s what I got:</p>
<pre class="code-block"><code>before fork: &amp;value = 0x104720000
pid 99257: &amp;value = 0x104720000, value = 100
pid 99314: &amp;value = 0x104720000, value = 1
pid 99314: &amp;value = 0x104720000, value = 2
pid 99257: &amp;value = 0x104720000, value = 200
pid 99314: &amp;value = 0x104720000, value = 3
pid 99257: &amp;value = 0x104720000, value = 300
pid 99314: &amp;value = 0x104720000, value = 4
pid 99257: &amp;value = 0x104720000, value = 400
pid 99314: &amp;value = 0x104720000, value = 5
pid 99257: &amp;value = 0x104720000, value = 500
</code></pre>
<p>Did you see it? No? No worries. <code>value</code> is a single global variable, declared at file scope. <code>fork()</code> makes a second process, and both processes proceed to update it , parent adding 100, child adding 1. And they&#39;re both reporting the <strong>same address</strong>: <code>0x104720000</code>.</p>
<p>So if there is one address, being incremented by two processes, the output should look something like this:</p>
<pre class="code-block"><code>pid 99257: value = 100
pid 99314: value = 101
pid 99257: value = 201
pid 99314: value = 202
pid 99257: value = 302
...
</code></pre>
<p>One counter, Incrementing, with the two processes taking turns depending on which one the scheduler runs. But what happened is that <code>0x104720000</code> contained a <code>3</code> and a <code>300</code> at the same moment.</p>
<blockquote><h2 id="fork-"><a class="heading-anchor" href="#fork-" aria-hidden="true">#</a>fork() ?</h2>
</blockquote>
<blockquote><p>When control hits <code>fork()</code>, the kernel makes a duplicate of the process that called it, the Original one. And it is called <strong>parent</strong>, the duplicate is the <strong>child</strong>. On Linux, the <code>fork()</code> you call from libc is a thin wrapper over the <code>clone()</code> syscall; on macOS and the BSDs, it&#39;s its own syscall.</p>
</blockquote>
<blockquote><p>The child gets a fresh <strong>PID</strong> (process ID), and its <strong>PPID</strong> (parent process ID) is set to whoever forked it. Its CPU-time and resource counters reset to zero. File record locks held by the parent are <em>not</em> inherited. If either process later changes its working directory, the other doesn&#39;t notice.</p>
</blockquote>
<blockquote><p>What <em>is</em> carried over? the register state, the program counter, the file descriptor table, the environment, the umask, the user and group IDs, the working directory as it stood at that instant, and, most importantly for us, the entire <strong>address space</strong>. Every byte of memory the parent had, the child has too, laid out identically.</p>
</blockquote>
<blockquote><p><em>(Tiny piece of trivia while we&#39;re here: every process on your machine except one is somebody&#39;s child. On Linux, the root of the tree is PID 1, <code>systemd</code> on most distros. On macOS, it&#39;s <code>launchd</code>. That process is spawned by the kernel at boot and everything else descends from it. Your shell is a child of your terminal, which is a child of the window server, and so on up.)</em></p>
</blockquote>
<blockquote><p>The file descriptor <strong>table</strong> is copied, but the open file <strong>descriptions</strong> it points into are shared. Which means parent and child share a file <em>offset</em>. If both inherit an open file and both write to it, they don&#39;t bash each other at byte zero; they advance one shared cursor, taking turns. Two processes but one position in a file. Now this is <strong>sharing</strong>. But the address space isn&#39;t. The address space is logically <em>duplicated</em>, the instant <code>fork()</code> returns. Two separate copies of <code>value</code> explains 3 and 300 coexisting just fine. It does not explain them sharing an address.</p>
</blockquote>
<h2 id="fork-copies-"><a class="heading-anchor" href="#fork-copies-" aria-hidden="true">#</a>Fork() copies ?</h2>
<p>So what actually happened? Depends what you mean by &quot;copied.&quot; Not a single byte of your program&#39;s actual data. The kernel did just duplicate a task struct and grow a whole new page table for the child, but that&#39;s the map, not the territory , new entries, not new pages. Parent and child are both looking at the same physical memory, the same actual page holding <code>value</code>, and the kernel has marked that memory <strong>read-only</strong> in both of them. The instant either process runs <code>value += step</code>, the processor tries to write to read-only memory and faults. The kernel catches the fault, and says, &quot;well, that&#39;s expected,&quot; and it grabs a fresh piece of physical memory, copies the old contents across, points <strong>that one process</strong> at the copy, restores write permission, and restarts the instruction that just failed. The instruction runs a second time. This time it succeeds. To the process this does not register.</p>
<p>That is <strong>Copy-On-Write</strong>, universally abbreviated COW, and no, not the animal.</p>
<p>And notice who did the most of the work. <code>fork()</code>? Not really. The <strong>page fault handler</strong>. <code>fork()</code> itself did almost nothing, flipped some permission bits and returned. Which is why forking is really efficient, fork a four-gigabyte process and it copies nothing up front, defers everything until somebody actually writes, and then copies exactly one chunk at a time, and only the chunks your program actually touched. Fork and then immediately <code>exec</code> a different program, which is what your shell does every single time you run a command, and it often copies <strong>zero</strong> bytes.</p>
<p>Right. Mystery solved. Go home.</p>
<p>Except, read that back, because I slipped something past you.</p>
<p>I said the kernel &quot;points that one process at the copy.&quot; Points <strong>what</strong> at the copy? And if the two processes walk away holding two physically different pieces of memory, then how on earth are they both still printing <code>0x104720000</code>? Two different locations in physical RAM but one address? This can only mean one thing, and this is what this series is about. <strong>That number a lookup key, not a actual address in your RAM, and each process resolves it differently.</strong></p>
]]></content:encoded>
    </item>
    <item>
      <title>Linking</title>
      <link>https://srinathshrestha.xyz/blogs/linking</link>
      <guid>https://srinathshrestha.xyz/blogs/linking</guid>
      <pubDate>Mon, 17 Aug 2026 23:12:31 GMT</pubDate>
      <description>How a Name Becomes a Distance Every function call you write is a name where as every function call the processor executes is a number. Something in between performs the conversion, and it does so in stages, deferring each decision…</description>
      <content:encoded><![CDATA[<h1 id="how-a-name-becomes-a-distance"><a class="heading-anchor" href="#how-a-name-becomes-a-distance" aria-hidden="true">#</a>How a Name Becomes a Distance</h1>
<p>Every function call you write is a name where as every function call the processor executes is a number. Something in between performs the conversion, and it does so in stages, deferring each decision until the last moment at which it can still be made correctly.</p>
<p>This is a piece about that conversion, traced with <code>objdump</code>, <code>readelf</code> and <code>nm</code> on a program small enough to read in full.</p>
<hr>
<h2 id="i-the-hole"><a class="heading-anchor" href="#i-the-hole" aria-hidden="true">#</a>I. The hole</h2>
<p>Here is the first of two files.</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">/* main.c */
int add(int a, int b);

int main(void)
{
    return add(2, 3);
}
</code></pre></div>
<p><code>add</code> is declared and never defined. There is no body for it anywhere in this file, and the compiler does not complain. Compile it, stopping deliberately short of a program. The <code>-c</code> flag ends the process after assembly:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ gcc -c main.c -o main.o
</code></pre></div>
<p>The result is an <strong>ELF relocatable object file</strong>. It is not an executable, but a component from which one may later be assembled.</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ objdump -d -M intel main.o

0000000000000000 &lt;main&gt;:
   0:	f3 0f 1e fa          	endbr64
   4:	55                   	push   rbp
   5:	48 89 e5             	mov    rbp,rsp
   8:	be 03 00 00 00       	mov    esi,0x3
   d:	bf 02 00 00 00       	mov    edi,0x2
  12:	e8 00 00 00 00       	call   17 &lt;main+0x17&gt;
  17:	5d                   	pop    rbp
  18:	c3                   	ret
</code></pre></div>
<p>The arguments are staged as expected: <code>3</code> into <code>esi</code>, <code>2</code> into <code>edi</code>, the registers reserved for the first two integer parameters under the x86-64 System V calling convention.</p>
<p>The call is another matter. Its destination, <code>0x17</code>, is the instruction immediately beneath it.</p>
<h2 id="00-00-00-00-"><a class="heading-anchor" href="#00-00-00-00-" aria-hidden="true">#</a><code>00 00 00 00</code> ?</h2>
<p><code>e8</code> is the opcode for <code>call</code>. So what are we to make of <code>00 00 00 00</code>? is it trying to jmp to zero, No, cuz first , address zero , in normal processes has nothing mapped there at all. the bottom of the address space is left deliberately empty so that deferencing null pointer fault immediatly instead of quietly scribbling over whatever happened to be lying around. and second, <strong>Those four bytes aren&#39;t an address.</strong> For this form of <code>call</code>, they hold a <em>signed offset</em>, measured from the end of the call instruction. The four bytes that follow are not an address. For this encoding they hold a <strong>signed offset measured from the end of the instruction</strong>. So the arithmetic runs like this. The call begins at <code>0x12</code> and occupies five bytes, which puts its end at <code>0x17</code>, By the time the CPU is ready to act on the instruction, it has already finished fetching it, so PC now reads <code>0x17</code>. Add the offset currently zero :</p>
<p><code>0x17 + 0 = 0x17</code></p>
<p><code>objdump</code> also performs the same arithmetic and reports the result. Zero denotes no displacement whatever, which lands on the following instruction incidentally. It was never the intended target.</p>
<p>The compiler required a <code>call</code>; the encoding demands four bytes of displacement; the correct displacement was unknown. So it reserved the field and left it empty. <strong>That is what i call a hole.</strong></p>
<h2 id="the-addresses-are-not-addresses"><a class="heading-anchor" href="#the-addresses-are-not-addresses" aria-hidden="true">#</a>The addresses are not addresses</h2>
<p>Note the first line of the dump:</p>
<div class="code-container"><span class="code-language">text</span><pre class="code-block language-text"><code class="language-text">0000000000000000 &lt;main&gt;:
</code></pre></div>
<p><code>main</code> is at zero, which does not mean it will ever reside at virtual address zero. These are offsets within this object file&#39;s <code>.text</code> section: distances from the start of this file&#39;s own code. Nothing has been placed. The compiler is just measuring, not assigning.</p>
<p>The reason for the hole follows from the same isolation. The compiler was handed exactly one file. <code>add</code>&#39;s body resides in another object file it was never shown and cannot go looking for. It could not compute the distance because it could not see the destination.</p>
<p>So it reserved the space and recorded a note.</p>
<h2 id="the-note"><a class="heading-anchor" href="#the-note" aria-hidden="true">#</a>The note</h2>
<p>The note is inside <code>main.o</code>, but not inside the machine code. It lives in <code>.rela.text</code>, a section of its own:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ readelf -S main.o

  [Nr] Name              Type             Address           Offset
  [ 1] .text             PROGBITS         0000000000000000  00000040
  [ 2] .rela.text        RELA             0000000000000000  00000170
</code></pre></div>
<p>Nearly three hundred bytes separate the two on disk. <code>objdump -dr</code> interleaves them for legibility, which is convenient until it persuades you that relocations live inside the instruction stream. They do not.</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ readelf -r main.o

Relocation section &#39;.rela.text&#39; at offset 0x170 contains 1 entry:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000000013  000400000004 R_X86_64_PLT32    0000000000000000 add - 4
</code></pre></div>
<p>take a look at the hole ( which is R_X86_64_PLT32 ). keeping aside the <code>Info</code> column, which merely packs the other fields into a single number, this is the shape of every relocation entry there is.</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Field</th>
<th>Value</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Offset</strong></td>
<td><code>0x13</code></td>
<td><em>where</em> the hole is</td>
</tr>
<tr>
<td><strong>Type</strong></td>
<td><code>R_X86_64_PLT32</code></td>
<td><em>how</em> to compute the value</td>
</tr>
<tr>
<td><strong>Symbol</strong></td>
<td><code>add</code></td>
<td><em>what</em> it should point at</td>
</tr>
<tr>
<td><strong>Addend</strong></td>
<td><code>-4</code></td>
<td>a constant correction</td>
</tr>
</tbody>
</table></div>
<p>Two of these warrant scrutiny.</p>
<p><strong>The offset is <code>0x13</code>, though the instruction begins at <code>0x12</code>.</strong> This is not an off-by-one. The byte at <code>0x12</code> is the <code>e8</code> opcode, which means the four-byte relocation starts at <code>0x13</code>. The relocation identifies the gap, not the instruction enclosing it.</p>
<p><strong>The addend is <code>-4</code> because two reference points are in play.</strong> The relocation marks the start of the hole at <code>0x13</code>, whereas the processor measures its jump from the end of the instruction at <code>0x17</code>. The two are four bytes apart, exactly the width of the field. The addend instructs the linker to shift its result from one reference point to the other, so that the number written is a displacement the processor will measure correctly.</p>
<p><em>(The <code>PLT</code> in <code>R_X86_64_PLT32</code> pertains to machinery that matters only for calls into shared libraries. We will arrive at it in due course.)</em></p>
<p>The symbol table states the same circumstance from the opposite direction:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ nm main.o

                 U add
0000000000000000 T main
</code></pre></div>
<p><code>main</code> carries an offset because it is defined here. <code>add</code> carries none. In its place stands <code>U</code>, for undefined: referenced by this file, contained in it nowhere.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/08/257d5d91-856d-4299-b751-50c04efd3c5a-01-hole.svg" alt="257d5d91-856d-4299-b751-50c04efd3c5a-01-hole" class="post-img" loading="lazy" /><figcaption>257d5d91-856d-4299-b751-50c04efd3c5a-01-hole</figcaption></figure></p>
<p>The division shown there is worth stating plainly. The processor will only ever execute <code>.text</code>. It has no notion of a relocation and will never read one. That metadata exists for the linker, and is discarded before the program runs.</p>
<h3 id="resolution"><a class="heading-anchor" href="#resolution" aria-hidden="true">#</a>Resolution</h3>
<p>Give <code>add</code> a body in a file of its own, compile it separately, and present both objects at once:</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">/* add.c */
int add(int a, int b)
{
    return a + b;
}
</code></pre></div>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ gcc -c add.c -o add.o
$ gcc -o prog main.o add.o
</code></pre></div>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ objdump -d -M intel prog

0000000000001129 &lt;main&gt;:
    1129:	f3 0f 1e fa          	endbr64
    112d:	55                   	push   rbp
    112e:	48 89 e5             	mov    rbp,rsp
    1131:	be 03 00 00 00       	mov    esi,0x3
    1136:	bf 02 00 00 00       	mov    edi,0x2
    113b:	e8 02 00 00 00       	call   1142 &lt;add&gt;
    1140:	5d                   	pop    rbp
    1141:	c3                   	ret

0000000000001142 &lt;add&gt;:
    1142:	f3 0f 1e fa          	endbr64
    ...
</code></pre></div>
<p><code>e8 00 00 00 00</code> has become <code>e8 02 00 00 00</code>. The call sits at <code>0x113b</code> and runs five bytes, so it ends at <code>0x1140</code>, and <code>0x1140 + 2 = 0x1142</code>, the first byte of <code>add</code>.</p>
<p>The <code>2</code> is not abstract. Between the call and <code>add</code> stand exactly two instructions, <code>pop rbp</code> and <code>ret</code>, one byte apiece. The displacement is the length of the code in the way.</p>
<p>Something larger has also happened. <code>main</code> is no longer at <code>0</code> but at <code>0x1129</code>. In the object file it was only ever <code>.text + 0</code>; once the linker decided where <code>.text</code> goes, that relative offset hardened into an address. Every number in the file moved, though not a single instruction changed. They acquired a location.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/08/81c6037e-0a6c-462a-912f-82e65355c74a-02-fill.svg" alt="02-fill" class="post-img" loading="lazy" /><figcaption>02-fill</figcaption></figure></p>
<p>The linker did not merely patch a hole. It took fragments that each measured from a private zero, gathered them into one shared address space, matched every outstanding name to a definition, and converted provisional references into concrete numbers.</p>
<p>That is the complete account. For <code>add</code>.</p>
<hr>
<h2 id="ii-when-add-is-not-ours"><a class="heading-anchor" href="#ii-when-add-is-not-ours" aria-hidden="true">#</a>II. When <code>add()</code> is not ours</h2>
<p><code>add</code> was tractable because its body existed, on disk, in a file handed to the linker. The distance was therefore knowable at link time, and once known, permanent.</p>
<p>Consider a name for which none of that holds.</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">/* hello.c */
#include &lt;stdio.h&gt;

int main(void)
{
    printf(&quot;answer %d\n&quot;, 42);
    return 0;
}
</code></pre></div>
<p><code>#include &lt;stdio.h&gt;</code> supplies no implementation. The preprocessor pastes the header&#39;s text into the file, and what the header contains is a declaration: one line describing <code>printf</code>&#39;s shape and nothing about its whereabouts. The compiler is in precisely the position it occupied with <code>add</code>, and behaves identically:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ objdump -dr -M intel hello.o

  1c:	e8 00 00 00 00       	call   21 &lt;main+0x21&gt;
            1d: R_X86_64_PLT32	printf-0x4
  21:	b8 00 00 00 00       	mov    eax,0x0
</code></pre></div>
<p>The same empty field, the same relocation type, the same addend. Only the symbol differs. Nothing at this stage distinguishes a call into a library from a call into the file next door.</p>
<p>Now let&#39;s link it.</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ gcc -o hello hello.o
$ objdump -d -M intel hello

0000000000001149 &lt;main&gt;:
    1165:	e8 e6 fe ff ff       	call   1050 &lt;printf@plt&gt;
</code></pre></div>
<p>The hole is filled. <code>e8 e6 fe ff ff</code> is a displacement of −282, which taken from <code>0x116a</code> yields <code>0x1050</code>. The mechanism is unchanged. But notice it says <code>printf@plt</code> , not <code>printf</code>. which is U and another layer or deffering.</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ nm hello | grep printf
                 U printf@GLIBC_2.2.5
</code></pre></div>
<p>The executable is finished, the linker has exited without error, and <code>printf</code> remains a name this program requires and does not possess.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/08/abd2f2a8-ef8e-4c94-8a66-21d7039a44e5-03-two-fates.svg" alt="03-two-fates" class="post-img" loading="lazy" /><figcaption>03-two-fates</figcaption></figure></p>
<h2 id="what-sits-at-0x1050"><a class="heading-anchor" href="#what-sits-at-0x1050" aria-hidden="true">#</a>What sits at 0x1050</h2>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ objdump -d -M intel hello

0000000000001050 &lt;printf@plt&gt;:
    1050:	f3 0f 1e fa          	endbr64
    1054:	ff 25 76 2f 00 00    	jmp    QWORD PTR [rip+0x2f76]        # 3fd0
    105a:	66 0f 1f 44 00 00    	nop
</code></pre></div>
<p><code>	jmp    QWORD PTR [rip+0x2f76] </code> this is a lil piece of code called PLT stub. Think of it as a forwarding booth, you program says &quot;call printf&quot; the linker says &quot;i can&#39;t give you the actual printf address yet, But i can give you a fixed address for this little sub, which you can call&quot;.<br>and now as i said , we have another layer of indirection , what is at that jmp address.</p>
<p><em>( QWORD PTR [rip+0x2f76] means Calculate an address using RIP + 0x2f76, go to that memory location, read an 8-byte value from there, and use that value as the jump target. )</em></p>
<p>That variable lives in the <strong>global offset table</strong>:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ readelf -S hello

  [24] .got              PROGBITS         0000000000003fb8  00002fb8
</code></pre></div>
<blockquote><p>In English : There is a section in this executable called .got, and it begins around address 0x3fb8.</p>
</blockquote>
<p><code>0x3fd0</code> falls inside <code>.got</code>, a data section, writable and distinct from the read-only code. And the executable ships a second relocation describing it, this one addressed not to the linker but to whatever runs next:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ readelf -r hello

Relocation section &#39;.rela.plt&#39; at offset 0x610 contains 1 entry:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000003fd0  000300000007 R_X86_64_JUMP_SLO 0000000000000000 printf@GLIBC_2.2.5 + 0
</code></pre></div>
<p>The same four fields as before. A hole at <code>0x3fd0</code>, to be filled with the address of <code>printf</code>. The linker did not resolve the reference. It moved the problem out of the instruction stream, where it could not be revised, and into a data slot where it can be. eg,GOT[printf] = actual_printf_address .</p>
<h2 id="why-it-had-no-choice"><a class="heading-anchor" href="#why-it-had-no-choice" aria-hidden="true">#</a>Why it had no choice</h2>
<p>The reason is visible from the shell.</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">$ ldd hello
    libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f042a200000)
</code></pre></div>
<p><code>printf</code> resides in a separate file, mapped into the process at run time. Ask three times:</p>
<div class="code-container"><span class="code-language">text</span><pre class="code-block language-text"><code class="language-text">0x00007f1429e00000
0x00007f0a5da00000
0x00007f9762600000
</code></pre></div>
<p>Three launches of the same unmodified binary, three different base addresses. Address-space layout randomisation (done for security reasons) relocates the library on every execution, and the executable itself is position-independent by default, so even <code>main</code> at <code>0x1129</code> is an offset from a load base chosen at run time rather than a fixed address.</p>
<p>No constant written into <code>hello</code> at link time could have been correct. The question the linker was asked (<em>how far is <code>printf</code>?</em>) has no answer that survives until the program runs.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/08/77bedf3e-f8a7-4580-91be-9cb04f73eb73-04-indirection.svg" alt="04-indirection" class="post-img" loading="lazy" /><figcaption>04-indirection</figcaption></figure></p>
<h2 id="the-shape-of-the-compromise"><a class="heading-anchor" href="#the-shape-of-the-compromise" aria-hidden="true">#</a>The shape of the compromise</h2>
<p>Note what the arrangement preserves. The call in <code>main</code> is an ordinary fixed displacement. The stub is an ordinary fixed jump. Both live in read-only, executable memory, and neither is modified after the linker writes it. That is what permits a single physical copy of that code to be mapped into every process on the machine simultaneously.</p>
<p>All the variability is confined to eight bytes of writable data. One indirection buys the entire property: instructions that never change, reaching a target that changes on every run.</p>
<p>Which leaves one question outstanding. Something must write an address into <code>0x3fd0</code>, and it must do so after the library has been placed and before the call is executed. The ELF is a descriptor of a program image. but if it&#39;s is dynamiclly linked it will need to resolve runtime symboles by a dynamic linker.</p>
]]></content:encoded>
    </item>
    <item>
      <title>SSD &amp; File Systems</title>
      <link>https://srinathshrestha.xyz/blogs/ssd-file-sys</link>
      <guid>https://srinathshrestha.xyz/blogs/ssd-file-sys</guid>
      <pubDate>Fri, 03 Apr 2026 22:57:12 GMT</pubDate>
      <description>Imagine you bought a 500 GB NVMe from Samsung's website. You plug it in, format it, start dumping files and creating directories. Life is good. But do you actually know what's happening underneath? Not the handwavy &quot;it stores data&quot; version,…</description>
      <content:encoded><![CDATA[<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/ssd-500GB.webp" alt="500GB NVMe" style="max-width:600px; width:100%" class="post-img" loading="lazy" /><figcaption>500GB NVMe</figcaption></figure></p>
<p>Imagine you bought a 500 GB NVMe from Samsung&#39;s website. You plug it in, format it, start dumping files and creating directories. Life is good. But do you actually know what&#39;s happening underneath? Not the hand-wavy &quot;it stores data&quot; version, what is actually happening that enables persistent storage and convenient and fast read and write on the Drive to you. Worry not. This is a good and easy read. Grab something to drink.</p>
<hr>
<h2 id="a-sea-of-blocks"><a class="heading-anchor" href="#a-sea-of-blocks" aria-hidden="true">#</a>A Sea of Blocks</h2>
<p>At the hardware level, your SSD is just billions of transistors, holding charge or no charge , ones and zeros stretching out into the void. If you examine an SSD further more, you will see there is a microcontroller inside it. It runs firmware that does work like error correction, garbage collection, bad block management, and translating between the logical block addresses the OS uses and the physical locations on the NAND flash. This layer is called the <strong>Flash Translation Layer (FTL)</strong>, and it&#39;s sophisticated engineering. But here&#39;s the key thing: <strong>it has zero understanding of your filesystem.</strong> It doesn&#39;t know what a file is. It doesn&#39;t know what a directory is. It has no idea that block 50,000 holds the first chapter of your novel and block 50,001 holds a cat picture. To the FTL, every block is just ~4096 bytes of &quot;stuff the OS asked me to store.&quot;</p>
<p>So what are &quot;blocks&quot;? You can imagine blocks as virtual partitioning on the storage real estate. The estate being billions of transistors, which is a lot. To make this chaos usable, we carve it into <strong>blocks</strong>, chunks of 4096 bytes (about 4 KB each). Every block gets a number, because this is computer science and everything is indexed.</p>
<p>One honest caveat before we go further: that 4 KB is the <strong>logical</strong> block, the number the OS agrees to see. The NAND underneath doesn&#39;t know or care about 4 KB , it&#39;s got its own pages (often 16 KiB) and its own erase blocks (megabytes), and the FTL&#39;s entire job is lying to you about that convincingly enough that you never have to think about it. Which is exactly why we&#39;re not going to think about it. Back to the lie, since it&#39;s the one that actually matters for what a filesystem does.</p>
<pre class="code-block"><code>Block 0  │ Block 1  │ Block 2  │ Block 3  │ ... │ Block N
[4KB]    │ [4KB]    │ [4KB]    │ [4KB]    │     │ [4KB]
</code></pre>
<p>Why blocks? Because addressing individual bytes across 500 GB of raw space would be absolute madness. You&#39;d need half a billion addresses just for indexing. Blocks are the first act of sanity the system imposes on the hardware.</p>
<p>But right now, this is still just a flat, dumb array of numbered blocks. No structure, no meaning. That changes the moment you hit &quot;Format.&quot;</p>
<hr>
<h2 id="formatting-imposing-order-on-chaos"><a class="heading-anchor" href="#formatting-imposing-order-on-chaos" aria-hidden="true">#</a>Formatting: Imposing Order on Chaos</h2>
<p>When you format a drive, a program stamps that featureless array of blocks with a structure , <code>mkfs</code> and friends, plain userspace, not some kernel module lurking in ring 0. It writes through the block layer exactly like any other program on your machine would. Think of it like laying down city infrastructure on empty land , roads, zones, a city hall, before ppl move in.</p>
<p>The structure it imposes looks something like this:</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/Filesystem_layout_strip.png" alt="Filesystem_layout_strip" style="max-width:600px; width:100%" class="post-img" loading="lazy" /><figcaption>Filesystem layout strip</figcaption></figure></p>
<p>A quick disclaimer: this is the simplified layout for a basic filesystem. If you try to understand something like <a href="https://developer.apple.com/documentation/foundation/file_system/about_apple_file_system">APFS</a>, you&#39;ll find the same core concepts, just over-engineered into oblivion. For explaining we will keep things simple :-)</p>
<p>Before the formatter writes a single byte, it has to do some counting. It reads the drive&#39;s reported capacity and block size, then works out how to divide the space:</p>
<pre class="code-block"><code>Total capacity:           500 GB
Block size:               4096 bytes
Total blocks:             500,000,000,000 / 4096 ≈ 122 million blocks
Inodes to allocate:       based on an assumption (we&#39;ll get to this)
Blocks for inode table:   (inode count × 256 bytes) / 4096
Remaining:                data blocks
</code></pre>
<p>Let&#39;s walk through each section of this layout.</p>
<hr>
<h2 id="the-superblock"><a class="heading-anchor" href="#the-superblock" aria-hidden="true">#</a>The Superblock</h2>
<p>The superblock is the very first thing the formatter writes, and it always fits inside a single block, by design it never spans two. It lives at a known, fixed location (byte offset 1024 on ext4, block 0 on APFS), and it holds the vital stats of the entire filesystem:</p>
<pre class="code-block"><code>Magic number            → identifies the filesystem type (ext4? APFS? the 
                          kernel knows just by reading the first few bytes)
Block size              → 4096 bytes
Total block count       → ~122 million
Total inode count       → however many we calculated
Free block count        → almost all of them on a fresh drive
Free inode count        → all of them
Inode table start       → &quot;inode table begins at block 2&quot;
Data blocks start       → &quot;data begins at block 50000&quot;
Mount count             → 0
Last mount time         → 0
Filesystem state        → clean
</code></pre>
<p>There are other fields, but these are the essentials every filesystem needs.</p>
<p>Here&#39;s the thing about the superblock, it&#39;s the <strong>root of trust</strong> for the entire filesystem. If it&#39;s corrupted, the kernel won&#39;t even try. No valid superblock, no filesystem. Full stop.</p>
<h3 id="when-the-superblock-gets-read"><a class="heading-anchor" href="#when-the-superblock-gets-read" aria-hidden="true">#</a>When the superblock gets read</h3>
<p>When you mount a drive (not for the first time , just a normal Tuesday), the kernel reads the superblock from its known location, validates the magic number, and copies the whole thing into memory. From that point on, all file operations work against the in-memory copy. The kernel almost never touches the on-disk superblock again during normal use.</p>
<h3 id="when-the-superblock-gets-written"><a class="heading-anchor" href="#when-the-superblock-gets-written" aria-hidden="true">#</a>When the superblock gets written</h3>
<p>Not all fields update at the same time, and the logic breaks into three categories:</p>
<p><strong>Static fields</strong> , the magic number, total block count, block size, etc, are written once during formatting. Unless you&#39;re resizing the partition later, these never change.</p>
<p><strong>Dynamic counters</strong> , free blocks, free inodes , change every time you create, delete, or modify a file. But the kernel isn&#39;t hammering the SSD after every single operation. It syncs these back to disk periodically, or when you run <code>sync</code>, or when you safely unmount.</p>
<p><strong>Mount-related fields</strong> track whether the filesystem was shut down properly, think of it like a sign on a door. When you mount the drive, the kernel increments the mount count, updates the timestamp, and marks the state as <strong>dirty</strong>. The sign now reads &quot;OPEN , someone&#39;s in here.&quot; When you safely eject, the kernel finishes all pending writes, makes sure everything is consistent, and flips the state back to <strong>clean</strong>. Sign reads &quot;CLOSED.&quot;</p>
<p>Now imagine the power cuts while the sign still says &quot;OPEN.&quot; Nobody got to flip it back. The kernel was in the middle of something , maybe it was halfway through writing a file, maybe it updated the bitmap but hadn&#39;t touched the inode yet, maybe dirty pages in the page cache never got flushed to disk. The filesystem could be in a half-finished, inconsistent state, and nobody ran the cleanup.</p>
<p>So the next time you plug the drive in, the kernel reads the superblock, sees the dirty flag, and knows the last session didn&#39;t end gracefully. Before it lets you use the drive, it runs a <strong>recovery step</strong> , either a full disk check (<code>fsck</code>) that walks the entire filesystem hunting for inconsistencies, or a <strong>journal replay</strong> if the filesystem keeps a journal (most modern ones do). A journal is a small log where the kernel writes &quot;I&#39;m about to do X&quot; <em>before</em> actually doing X. If the system crashed mid-X, the journal tells recovery exactly what was in progress and how to undo or finish it. It&#39;s a transaction log, same idea databases use.</p>
<p>The mount count itself is simpler , it just goes up by 1 every time you mount. Some filesystems use it as a safety net: after 30 or so mounts, run a full check regardless, just to be safe.</p>
<hr>
<h2 id="inodes-every-files-id-card"><a class="heading-anchor" href="#inodes-every-files-id-card" aria-hidden="true">#</a>Inodes: Every File&#39;s ID Card</h2>
<p>Now we get to arguably the most important struct in the whole filesystem. Every single file , and every single directory, but we&#39;ll get to that twist later , gets an <strong>inode</strong>. <mark>One file, one inode</mark>. No exceptions. A 1-byte text file? Gets an inode. Your 47 GB 4K video? Also exactly one inode. This rule is important to internalize.</p>
<p>An inode is just a small struct, 256 bytes, that holds metadata about a file:</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">struct inode {
    mode_t    permissions;   // rwxr-xr-x
    uid_t     owner;         // UID 501
    gid_t     group;         // GID 20
    size_t    file_size;     // 9344 bytes
    time_t    modified;      // timestamp
    block_ptr data_blocks[]; // which blocks hold the actual data
};
</code></pre></div>
<p>And this isn&#39;t just theory you read and mug up as trivia. If you have a lot of time you can dig into the code for the filesystem in your kernel. Here&#39;s the struct from my Mac, straight from the SDK headers , small correction on what this actually is, though: it&#39;s what <code>stat()</code> hands back to userspace, not the inode itself. <code>st_ino</code> is the inode <em>number</em>, a receipt, not the thing it refers to. The real on-disk inode, the one APFS or ext4 actually keep, lives somewhere these headers don&#39;t show you:</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">// /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/stat.h

struct ostat {
    __uint16_t      st_dev;         /* inode&#39;s device */
    ino_t           st_ino;         /* inode&#39;s number */
    mode_t          st_mode;        /* inode protection mode */
    nlink_t         st_nlink;       /* number of hard links */
    __uint16_t      st_uid;         /* user ID of the file&#39;s owner */
    __uint16_t      st_gid;         /* group ID of the file&#39;s group */
    __uint16_t      st_rdev;        /* device type */
    __int32_t       st_size;        /* file size, in bytes */
    struct  timespec st_atimespec;  /* time of last access */
    struct  timespec st_mtimespec;  /* time of last data modification */
    struct  timespec st_ctimespec;  /* time of last file status change */
    __int32_t       st_blksize;     /* optimal blocksize for I/O */
    __int32_t       st_blocks;      /* blocks allocated for file */
    __uint32_t      st_flags;       /* user defined flags for file */
    __uint32_t      st_gen;         /* file generation number */
};
</code></pre></div>
<p>All the things match with what I read in <a href="https://pages.cs.wisc.edu/~remzi/OSTEP/">OSTEP</a> (btw most of this article is built on concepts from that book, it&#39;s free and brilliant, go read it).</p>
<h3 id="how-many-inodes-do-we-make"><a class="heading-anchor" href="#how-many-inodes-do-we-make" aria-hidden="true">#</a>How many inodes do we make?</h3>
<p>Here&#39;s a problem: at format time, the kernel has no idea what you&#39;re going to do with this drive. Maybe you&#39;ll store a million tiny config files. Maybe you&#39;ll dump four 100 GB movies. It can&#39;t know.</p>
<p>So it guesses. The standard heuristic is: <strong>one inode per 16 KB of space</strong>. It assumes the average file will be roughly 16 KB, does the division, and provisions that many inodes.</p>
<pre class="code-block"><code>500,000,000,000 bytes / 16,384 bytes per file = 30,517,578 inodes  (≈31 million)
</code></pre>
<p>Each inode is 256 bytes, so the inode table eats up:</p>
<pre class="code-block"><code>30,517,578 × 256 / 4096 = 1,907,348 blocks  (≈1.9 million blocks, ~7.8 GB)
</code></pre>
<h3 id="wait--the-math-is-not-mathing"><a class="heading-anchor" href="#wait--the-math-is-not-mathing" aria-hidden="true">#</a>Wait , the math is not mathing?</h3>
<p>If you&#39;ve been paying close attention to the math, something should be bugging you. We calculated the inode count based on the full 500 GB. But the superblock, the inode table itself, and the bitmap all <em>also</em> live on that 500 GB. We&#39;re provisioning inodes for space that will never hold files. Isn&#39;t that a lil chicken-and-egg situation? At the end of the day we have to have inodes for only files that live in the data blocks, but while formatting we can&#39;t really know what the size is unless we have taken out the space for superblock, inode table, bitmap section, out of the total capacity, which again we can&#39;t know with the future files we will have! I hope i&#39;m being able to communicate the doubt here that i had, so i&#39;m mentioning it here.</p>
<p>So yes. It absolutely is. And the kernel&#39;s answer is: <strong>it doesn&#39;t care.</strong></p>
<p>Here&#39;s why. The 16 KB ratio is already a wild guess. The kernel has no idea if you&#39;ll create ten files or ten million. Being mathematically precise about overhead doesn&#39;t actually produce a better estimate , it just makes the formatter more complex and more prone to bugs.</p>
<p>And the waste is laughably small. Those &quot;extra&quot; inodes for the 7.8 GB of overhead? That&#39;s about 488,000 unnecessary inodes, which take up roughly 125 MB. On a 500 GB drive. The system engineers will take that trade every single time.</p>
<p>Now coming back to the size estimation for the inode section of the layout and therefore total inodes. There&#39;s also a scarier reason: <strong>running out of inodes is a nightmare.</strong> There&#39;s a famous error , <code>No space left on device</code> , (also called inode busting) that sometimes hits users who have 50 GB of free space left. How? They created so many tiny files that they exhausted every inode, even though the data blocks were mostly empty. Inode table is full means the data section is full, as far as the filesystem is concerned. Formatters would rather over-provision than let that happen.</p>
<p>And that <code>No space left on device</code> error isn&#39;t just a theoretical footnote , it&#39;s a real operational headache in specific environments. <strong>CDN edge servers</strong> that cache millions of tiny assets , thumbnails, CSS files, JavaScript bundles, 1x1 tracking pixels , can burn through inodes fast. The files are small (often under 4 KB each), but there are <em>millions</em> of them. The data blocks are barely touched, but the inode table is completely full. Same story with <strong>mail servers</strong> and <strong>container and CI/CD environments</strong>, basically any use case where lots of tiny files are involved.</p>
<p>The fix is usually to reformat with a lower bytes-per-inode ratio (say, 4096 instead of 16384), which allocates more inodes at the cost of a larger inode table. Or you switch to a filesystem like <a href="https://xfs.wiki.kernel.org/">XFS</a> or <a href="https://btrfs.readthedocs.io/">Btrfs</a> that allocates inodes dynamically instead of fixing the count at format time.</p>
<p><em>(If you&#39;re curious: modern filesystems like ext4 actually dodge this problem more elegantly by dividing the disk into ~128 MB &quot;block groups&quot; and stamping a repeating pattern of superblock-copy + bitmap + inodes + data onto each group. They never have to calculate the overhead for the whole drive at once. But for understanding the concept, the flat model works perfectly.)</em></p>
<hr>
<h2 id="indirection-how-256-bytes-points-to-half-a-terabyte"><a class="heading-anchor" href="#indirection-how-256-bytes-points-to-half-a-terabyte" aria-hidden="true">#</a>Indirection: How 256 Bytes Points to Half a Terabyte</h2>
<p>This is a brilliant piece of engineering. A single inode is 256 bytes. Some files are hundreds of gigabytes. How does a 256-byte metadata struct track all that data?</p>
<p>The answer is a beautiful trick called <strong>indirection</strong> , the same idea as a pointer to a pointer in C, except on disk.</p>
<p><em>(Quick disclaimer before the pointer math: this is the classic Unix textbook inode, not what&#39;s actually sitting on your ext4 or APFS drive. Real ext4 uses <strong>extents</strong> instead of walking indirect blocks, and the old-school pointers were 4 bytes, not 8 , 1024 per block, not 512. None of that changes the idea. Indirection is still indirection. Just don&#39;t go hunting for this exact struct on your Samsung NVMe.)</em></p>
<p>Every inode has 15 block pointers. The first <strong>12</strong> are <strong>direct pointers</strong>. Each one points straight to a data block. That gives you 12 × 4 KB = <strong>48 KB</strong> of addressable space. Plenty for tiny files, and most files on your system are tiny.</p>
<p>The <strong>13th</strong> is a <strong>single indirect pointer</strong>. It doesn&#39;t point to data , it points to a block <em>full of pointers</em>. One block holds 4096 / 8 = 512 pointers (8-byte pointers, in this model). So this one slot gives you 512 × 4 KB = <strong>~2 MB</strong> more.</p>
<p>The <strong>14th</strong> is a <strong>double indirect pointer</strong>. It points to a block of pointers that each point to blocks of pointers. 512 × 512 = 262,144 pointers. That&#39;s <strong>~1 GB</strong>.</p>
<p>The <strong>15th</strong> is a <strong>triple indirect pointer</strong>. Pointers to pointers to pointers to data. 512 × 512 × 512 = ~134 million pointers. That&#39;s over <strong>500 GB</strong> from a single entry in a 256-byte struct.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/Indirection.png" alt="Indirection" style="max-width:600px; width:100%" class="post-img" loading="lazy" /><figcaption>Indirection</figcaption></figure></p>
<p>It&#39;s pointers all the way down. If you&#39;ve ever written <code>**ptr</code> in C and felt confused, congratulations, your filesystem has been doing the same thing on disk this whole time and handling it better than you.</p>
<hr>
<h2 id="the-block-bitmap-15-megabytes-of-bookkeeping"><a class="heading-anchor" href="#the-block-bitmap-15-megabytes-of-bookkeeping" aria-hidden="true">#</a>The Block Bitmap: 15 Megabytes of Bookkeeping</h2>
<p>The block bitmap is the simplest structure in the entire filesystem. It uses exactly <strong>one bit</strong> per data block. A <code>1</code> means occupied, a <code>0</code> means free. For 122 million blocks, that&#39;s 122 million bits, roughly around <strong>15 MB</strong>. That&#39;s it. The entire free-space map for a 500 GB drive fits in 15 megabytes.</p>
<p>When the kernel needs to write new data, it scans this bitmap to find blocks marked <code>0</code>, claims them, flips the bits to <code>1</code>, and writes the data. I hear you asking &quot;how does the mapping work?&quot; well good question! The kernel knows from the superblock that the data section starts at, say, block 10,000. The mapping between bitmap bits and data blocks is pure arithmetic:</p>
<pre class="code-block"><code>Bit 0  →  Block 10,000
Bit 1  →  Block 10,001
Bit 2  →  Block 10,002
...
</code></pre>
<p>So if the kernel wants to check whether block 15,000 is free, it subtracts: <code>15,000 - 10,000 = 5,000</code>. It needs the 5,000th bit.</p>
<p>But here&#39;s the catch, we all know CPUs are <strong>byte-addressable</strong>, not bit-addressable. You can&#39;t ask a computer system to &quot;read bit 5,000.&quot; You have to fetch the byte that contains it.</p>
<p>Two small operations. <strong>Divide by 8</strong> to find the byte: <code>5000 / 8 = 625</code>, fetch the 625th byte of the bitmap. Then <strong>modulo 8</strong> to find the bit within that byte: <code>5000 % 8 = 0</code>, check bit 0 of that byte.</p>
<p>The kernel loads the byte into a register, applies a bitwise AND mask, and instantly knows: free or occupied. When it needs to allocate, it scans bytes sequentially looking for anything that isn&#39;t <code>0xFF</code> (all eight blocks taken), locates the <code>0</code> bit, flips it, and reverse-calculates the block number. Very mechanical and rapid.</p>
<hr>
<h2 id="directories"><a class="heading-anchor" href="#directories" aria-hidden="true">#</a>Directories</h2>
<p>We&#39;ve saved the best part for last, and it starts with a misconception. You might think inodes only belong to files, the &quot;leaf nodes&quot; in your directory tree, and that directories are some special container type that the OS handles differently.</p>
<p>They&#39;re not. A directory is just a file.</p>
<p>The only difference is a tiny flag inside the inode&#39;s <code>mode</code> field that tells the kernel: &quot;the data blocks for this inode don&#39;t contain document text or video frames , they contain a <strong>name-to-number lookup table</strong>.&quot;</p>
<p>Let&#39;s look at what lives inside a directory&#39;s data blocks. Say you have a directory called <code>projects/</code> that contains two files:</p>
<pre class="code-block"><code>projects/
├── fruits.txt
└── sample.txt
</code></pre>
<p>The directory <code>projects/</code> has an inode , let&#39;s say inode 64345000. When the kernel reads the data blocks that this inode points to, it doesn&#39;t find file contents. It finds a table like this:</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th align="left">Name</th>
<th align="left">Inode Number</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>.</code></td>
<td align="left">64345000</td>
</tr>
<tr>
<td align="left"><code>..</code></td>
<td align="left">64340000</td>
</tr>
<tr>
<td align="left"><code>fruits.txt</code></td>
<td align="left">64346628</td>
</tr>
<tr>
<td align="left"><code>sample.txt</code></td>
<td align="left">64346700</td>
</tr>
</tbody>
</table></div>
<p>That first entry, <code>.</code>, points to 64345000, that&#39;s the directory pointing to <em>itself</em>. That&#39;s why <code>cd .</code> does nothing , you&#39;re telling the kernel &quot;resolve this inode&quot; and it resolves to where you already are. The second entry, <code>..</code>, points to 64340000, the <em>parent</em> directory, which is how <code>cd ..</code> works. These two entries exist in every single directory on the system.</p>
<p>The other two entries are the actual files. But notice: the names <code>fruits.txt</code> and <code>sample.txt</code> don&#39;t live inside those files. They live here, inside the directory&#39;s lookup table. <strong>The files themselves have no names.</strong> A file is just an inode number. The &quot;name&quot; is just a label that a particular directory has assigned to that number.</p>
<p>This means renaming a file doesn&#39;t touch the file at all , it just edits the directory&#39;s table. Moving a file between directories on the same filesystem doesn&#39;t copy any data , it deletes the entry from one directory&#39;s table and adds it to another&#39;s. The inode, the data blocks, everything stays exactly where it is. <code>mv</code> is lying to you about how much work it&#39;s doing.</p>
<h3 id="the-filesystem-is-a-tree"><a class="heading-anchor" href="#the-filesystem-is-a-tree" aria-hidden="true">#</a>The Filesystem Is a Tree</h3>
<p>Step back and look at the shape of what we&#39;ve built. The root directory <code>/</code> is a directory file whose table points to other directories. Those directories point to more directories or to files. Directories never form cycles (ignoring <a href="https://man7.org/linux/man-pages/man2/link.2.html">hard links</a> for now). This is a <strong>tree</strong>, the same tree data structure you&#39;ve seen in algorithms, with directories as internal nodes and regular files as leaves.</p>
<pre class="code-block"><code>            / (inode 2)
           / \
        home   etc
        /       \
     ubuntu    passwd (file)
      /
   fruits.txt (file)
</code></pre>
<p>Every edge in this tree is a name-to-inode mapping stored inside a directory&#39;s data blocks. The tree isn&#39;t stored as a tree anywhere , there&#39;s no &quot;tree structure&quot; on disk. It <em>emerges</em> from directories pointing to other directories. The shape exists only because of the lookup tables.</p>
<h3 id="path-resolution"><a class="heading-anchor" href="#path-resolution" aria-hidden="true">#</a>Path Resolution</h3>
<p>When you type <code>cat /home/ubuntu/fruits.txt</code>, the kernel doesn&#39;t know where that file lives. It walks the path, one hop at a time, starting from a hardcoded rule: the root directory <code>/</code> is always inode 2. Well , on ext it is. APFS doesn&#39;t play by that rule, but we&#39;re staying in ext-land for this walk, so inode 2 it is. Everything else is discovered by walking.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/Path_resolution.png" alt="Path_resolution" class="post-img" loading="lazy" /><figcaption>Path resolution</figcaption></figure></p>
<p>Here&#39;s the full walk:</p>
<p><strong>Hop 1:</strong> The kernel reads <strong>inode 2</strong> from the inode table. It checks the mode flag, yes, this is a directory. It follows the data block pointers to read the directory&#39;s lookup table. It scans for the name <code>home</code>. Found it , mapped to <strong>inode 15</strong>.</p>
<p><strong>Hop 2:</strong> The kernel reads <strong>inode 15</strong>. Directory flag set. Reads its data blocks. Scans for <code>ubuntu</code>. Found , <strong>inode 42</strong>.</p>
<p><strong>Hop 3:</strong> The kernel reads <strong>inode 42</strong>. Directory flag set. Reads its data blocks. Scans for <code>fruits.txt</code>. Found , <strong>inode 88</strong>.</p>
<p><strong>Hop 4:</strong> The kernel reads <strong>inode 88</strong>. No directory flag, this is a regular file. The resolution is complete. The kernel now has the inode, which contains the file size, permissions, timestamps, and , critically , the block pointers that lead to the actual file data.</p>
<p>Four hops. Every <code>cd</code>, every <code>ls</code>, every <code>open()</code> call triggers this walk. The path you type is just a treasure map , the real addresses are inode numbers, and the directories are the clues.</p>
<h3 id="what-happens-when-it-fails"><a class="heading-anchor" href="#what-happens-when-it-fails" aria-hidden="true">#</a>What happens when it fails</h3>
<p>If at any hop the kernel scans the directory table and doesn&#39;t find the next name in the path, the walk stops immediately and the kernel returns <code>ENOENT</code> , the error code behind every &quot;No such file or directory&quot; message you&#39;ve ever seen. It doesn&#39;t guess, it doesn&#39;t search elsewhere. The path is a precise set of instructions, and if any step fails, the whole thing fails.</p>
<p>There&#39;s another failure mode: <strong>permission denied</strong>. At every single hop, the kernel checks whether the current user has execute permission on the directory. Yes, <em>execute</em> on a directory , that&#39;s what the <code>x</code> bit means for directories. It&#39;s the permission to traverse, to look up names inside that directory. If you have read permission but not execute, you can <code>ls</code> the directory and see the names, but you can&#39;t <code>cd</code> into it or resolve any path through it. The walk stops and the kernel returns <code>EACCES</code>. If you want to read more about Unix permissions, the <a href="https://man7.org/linux/man-pages/man1/chmod.1.html">chmod man page</a> is the canonical source.</p>
<h3 id="what-happens-when-it-succeeds"><a class="heading-anchor" href="#what-happens-when-it-succeeds" aria-hidden="true">#</a>What happens when it succeeds</h3>
<p>Once the kernel holds the final inode, it still has work to do. The <code>open()</code> system call doesn&#39;t actually read the file data , it just sets up a <strong>file descriptor</strong>, an entry in the process&#39;s open file table that says &quot;this process has inode 88 open for reading.&quot; The file descriptor is just a small integer , 0, 1, 2, 3 , that the process uses as a handle.</p>
<p>The actual data only gets loaded when the process calls <code>read()</code>. At that point, the kernel looks at the inode&#39;s block pointers, figures out which data blocks it needs, and reads them off the SSD. But even here, it doesn&#39;t just dump raw blocks into the process , it goes through the <strong>page cache</strong> first, which brings us to the next section.</p>
<hr>
<h2 id="io-speed"><a class="heading-anchor" href="#io-speed" aria-hidden="true">#</a>I/O Speed</h2>
<p>We&#39;ve been talking about blocks on an SSD as if the kernel reads them directly every time you access a file. In reality, there are multiple layers of caching between your program and the physical NAND flash, and they exist for one reason: <strong>disk I/O is brutally slow compared to RAM.</strong></p>
<p>To put numbers on it:</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th align="left">Storage Type</th>
<th align="left">Read Latency</th>
<th align="left">Sequential Read Speed</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">CPU L1 Cache</td>
<td align="left">~1 ns</td>
<td align="left">—</td>
</tr>
<tr>
<td align="left">RAM (DDR4/5)</td>
<td align="left">~50–100 ns</td>
<td align="left">~50 GB/s</td>
</tr>
<tr>
<td align="left">NVMe SSD</td>
<td align="left">~10,000–20,000 ns</td>
<td align="left">~3–7 GB/s</td>
</tr>
<tr>
<td align="left">SATA SSD</td>
<td align="left">~50,000–100,000 ns</td>
<td align="left">~500 MB/s</td>
</tr>
<tr>
<td align="left">HDD (spinning disk)</td>
<td align="left">~5,000,000–10,000,000 ns</td>
<td align="left">~100–200 MB/s</td>
</tr>
</tbody>
</table></div>
<p>RAM is roughly <strong>100x–1000x faster</strong> than an SSD depending on the access pattern. A spinning hard drive is another order of magnitude slower. This gap is why every layer of the system is trying desperately to avoid touching the disk.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/caching_layers.png" alt="caching_layers" class="post-img" loading="lazy" /><figcaption>caching layers</figcaption></figure></p>
<h3 id="layer-1-the-page-cache-os-level"><a class="heading-anchor" href="#layer-1-the-page-cache-os-level" aria-hidden="true">#</a>Layer 1: The Page Cache (OS-level)</h3>
<p>The kernel maintains a massive <strong>page cache</strong> in RAM , a pool of recently-read (and recently-written) disk blocks kept in memory. When a process calls <code>read()</code>, the kernel checks the page cache first. If the block is already there (a &quot;cache hit&quot;), the data is served from RAM without touching the SSD at all.</p>
<p>This is why opening a file for the second time feels instant , the first read loaded the blocks into the page cache, and the second read just grabs them from memory. It&#39;s also why your system&#39;s &quot;free&quot; RAM always looks low: the kernel aggressively fills unused RAM with cached disk data, because empty RAM is wasted RAM. If you&#39;ve ever panicked looking at <code>htop</code> and seeing 14 out of 16 GB &quot;used,&quot; relax. Most of that is cache, and the kernel will happily evict it the moment a real program needs the memory.</p>
<p>Writes go through the page cache too. When a process calls <code>write()</code>, the kernel updates the page in memory and marks it as <strong>dirty</strong>. It doesn&#39;t immediately write to disk. The dirty pages get flushed to disk later , by a background kernel thread, or when the process calls <code>fsync()</code>, or when memory pressure forces an eviction. This is called <strong>write-back caching</strong>, and it&#39;s why pulling the plug on a computer can lose recent changes.</p>
<h3 id="layer-2-the-disks-own-cache"><a class="heading-anchor" href="#layer-2-the-disks-own-cache" aria-hidden="true">#</a>Layer 2: The Disk&#39;s Own Cache</h3>
<p>Your SSD also has its own DRAM cache , usually 256 MB to a few GB, depending on the model. The SSD&#39;s firmware uses this to buffer incoming writes, cache its internal mapping tables (the FTL we talked about earlier), and pre-fetch data it predicts you&#39;ll need next. The firmware on that microcontroller is running its own little caching strategy independently of the OS. It&#39;s caches all the way down, just like it was pointers all the way down.</p>
<p>So when you read a file, the data might travel through three caches before reaching your program: the SSD&#39;s DRAM cache, then the OS page cache, then potentially the CPU caches. When you write, the data passes through the same chain in reverse.</p>
<h3 id="layer-3-application-level-buffering"><a class="heading-anchor" href="#layer-3-application-level-buffering" aria-hidden="true">#</a>Layer 3: Application-Level Buffering</h3>
<p>Applications often add yet another layer. Databases like <a href="https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-SHARED-BUFFERS">PostgreSQL</a> maintain a <strong>shared buffer pool</strong> , a managed cache in userspace, separate from the OS page cache. When PostgreSQL needs a table row, it checks its own buffer pool first, only hitting the OS (and therefore the disk) if the page isn&#39;t cached locally. Databases do this because they understand their own access patterns better than the generic kernel LRU algorithm can.</p>
<p>This is also why databases use <code>O_DIRECT</code> or <code>fsync()</code> strategically , they need precise control over when data actually hits persistent storage, because &quot;the write went to a cache somewhere&quot; isn&#39;t good enough when you&#39;re guaranteeing transactional durability. The database needs to know: <strong>is this on the physical disk, or is it still floating in some volatile cache that would vanish in a power failure?</strong></p>
<h3 id="ramdisk-cutting-out-the-middleman"><a class="heading-anchor" href="#ramdisk-cutting-out-the-middleman" aria-hidden="true">#</a>RAMDisk: Cutting Out the Middleman</h3>
<p>If caching disk data in RAM is so fast, why not skip the disk entirely? That&#39;s exactly what a <strong>RAMDisk</strong> does , it carves out a chunk of RAM and presents it to the OS as a block device, with a full filesystem on top. The kernel formats it, creates a superblock, builds an inode table , the whole ceremony we&#39;ve been discussing , except the underlying &quot;blocks&quot; are just RAM addresses.</p>
<p>Read and write speeds on a RAMDisk are essentially the speed of your RAM: tens of GB/s, with nanosecond-level latency. The catch is obvious: when power goes out, everything vanishes. RAMDisks are useful for temporary build artifacts, scratch space, and workloads where speed matters more than persistence.</p>
<hr>
<h2 id="the-full-picture"><a class="heading-anchor" href="#the-full-picture" aria-hidden="true">#</a>The Full Picture</h2>
<p>Zoom out and look at what we&#39;ve built from that featureless array of transistors.</p>
<p>The <strong>superblock</strong> is the root of trust, holding every vital stat the kernel needs to bring the filesystem online. The <strong>inode table</strong> stores one 256-byte card per file, tracking ownership, permissions, size, and block pointers that lead to the actual data. The <strong>block bitmap</strong> uses one bit per block, 15 MB of bookkeeping for a 500 GB drive, checked with nothing more than integer division and a bitmask. The <strong>directories</strong> are files posing as folders, mapping human-readable names to inode numbers. And the <strong>page cache</strong> sits between all of this and your program, making sure the kernel touches the disk as rarely as it can get away with.</p>
<p>All of it , every layer, every structure , is managed entirely by the kernel. No user, no application, no firmware ever touches the filesystem directly. You just type <code>ls</code> and see your files. The kernel does the rest.</p>
<p>That&#39;s what happens when you plug in your SSD.</p>
<hr>
<h2 id="party-trivia"><a class="heading-anchor" href="#party-trivia" aria-hidden="true">#</a>Party Trivia</h2>
<p>If you want to act cool or chad in parties, if that&#39;s something you are familiar with, then these trivias can come really handy:</p>
<p><strong>SSDs forget.</strong> NAND flash stores data as electrical charge trapped in transistor cells. Over time, that charge leaks. If you leave an SSD unpowered in a drawer for years, the data degrades. At high temperatures, this can happen in as little as a year. Enterprise SSDs are rated for data retention of about a year at 40°C without power. Consumer drives are more tolerant but not immortal. HDDs, by contrast, store data as magnetic orientation on a spinning platter , their long-term enemy is mechanical corrosion and bearing failure, not charge leak. For archival storage measured in decades, spinning disks are still more reliable than flash. Your SSD is fast but it&#39;s also kinda needy , it needs you to plug it in every once in a while or it starts forgetting things. Like a Tamagotchi, but for your data.</p>
<p><strong>The <code>stat</code> command is a filesystem tourist.</strong> When you run <code>stat filename</code> on a Unix system, you&#39;re reading the inode directly. Every field we discussed , permissions, size, timestamps, block count , gets printed to your terminal. Try it right now. It makes the whole theory concrete.</p>
<p><strong>Hard links break the tree.</strong> We said the filesystem is a tree, but <a href="https://man7.org/linux/man-pages/man2/link.2.html">hard links</a> let two different directory entries point to the same inode. Now one file has two names in two different directories. The inode tracks this with a <strong>link count</strong> (<code>st_nlink</code> in the struct above). The file&#39;s data blocks only get freed when the link count hits zero. This is why <code>rm</code> in Unix is technically &quot;unlink&quot; , it removes a directory entry and decrements the count, not necessarily deletes the data.</p>
<p><strong>Everything is a file.</strong> Directories are files. <code>/dev/null</code> is a file. Your keyboard is <code>/dev/input/event0</code> , a file. When you run a program, the input it reads and the output it creates, or errors if written by me, they all pipe into stdin, stdout and stderr, these are OS-level files and the terminal shell output is where stdout and stderr go live. Same with network sockets, pipes, device drivers , all exposed as files. This isn&#39;t a cute metaphor. It&#39;s a literal design decision: the Unix kernel exposes nearly everything through the same <code>open/read/write/close</code> interface, backed by inodes, handled through file descriptors. The filesystem isn&#39;t just where your data lives , it&#39;s the OS&#39;s universal API.</p>
<hr>
<h2 id="further-reading"><a class="heading-anchor" href="#further-reading" aria-hidden="true">#</a>Further Reading</h2>
<p>If this article got you curious and you want to go deeper, here are some resources that are genuinely worth your time:</p>
<p><a href="https://pages.cs.wisc.edu/~remzi/OSTEP/"><strong>OSTEP (Operating Systems: Three Easy Pieces)</strong></a> , Free online textbook. The chapters on file systems (36-42) are what most of this article is built on. Brilliantly written, doesn&#39;t assume you know everything already.</p>
<p><a href="https://www.kernel.org/doc/html/latest/filesystems/"><strong>The Linux Kernel Documentation on Filesystems</strong></a> , If you want to see how ext4, XFS, and Btrfs actually implement these concepts. Dense but authoritative.</p>
<p><a href="https://csapp.cs.cmu.edu/"><strong>CS:APP (Computer Systems: A Programmer&#39;s Perspective)</strong></a> , Covers the full stack from bits to processes. The I/O chapters connect directly to the caching and page cache concepts we discussed.</p>
<p><a href="https://ext4.wiki.kernel.org/index.php/Main_Page"><strong>ext4 Wiki</strong></a> , Practical details on block groups, journaling, and all the real-world engineering that ext4 does on top of the simple model we covered.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Hash Tables</title>
      <link>https://srinathshrestha.xyz/blogs/how-hash-table-works</link>
      <guid>https://srinathshrestha.xyz/blogs/how-hash-table-works</guid>
      <pubDate>Tue, 10 Mar 2026 09:52:48 GMT</pubDate>
      <description>Hash tables are, at their core, straightforward. The idea is this: in an ordinary unsorted array, finding an element requires examining each one in sequence. A hash table eliminates that search by computing, from the value itself, exactly where in…</description>
      <content:encoded><![CDATA[<p>Hash tables are, at their core, straightforward. The idea is this: in an ordinary unsorted array, finding an element requires examining each one in sequence. A hash table eliminates that search by computing, from the value itself, exactly where in the array that value ought to live. You do not search for the element. You calculate its address and go directly there.</p>
<p>The mechanism that does this is called the <strong>hash function</strong>.</p>
<hr>
<h2 id="the-hash-function"><a class="heading-anchor" href="#the-hash-function" aria-hidden="true">#</a>The Hash Function</h2>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">int hash(int key) {
    int index = key % TABLE_SIZE;
    if (index &lt; 0) {
        index += TABLE_SIZE;
    }
    return index;
}
</code></pre></div>
<p><code>TABLE_SIZE</code> is the length of your array. The function divides the key by that size and returns the remainder. The remainder becomes the index.</p>
<p><strong>An illustration.</strong> Suppose you have 101 slots, numbered 0 to 100. A key of <code>105</code> divides as follows: <code>105 ÷ 101</code> leaves a remainder of <code>4</code>. The value <code>105</code> lives at index <code>4</code>.</p>
<p>Negative keys require a small correction. In C, <code>-5 % 101</code> evaluates to <code>-5</code> rather than <code>96</code>. Adding <code>TABLE_SIZE</code> wraps the result into the valid range: <code>(-5 % 101) + 101 = 96</code>.</p>
<h3 id="why-101-slots-and-not-100"><a class="heading-anchor" href="#why-101-slots-and-not-100" aria-hidden="true">#</a>Why 101 Slots and Not 100?</h3>
<p>This is where the design becomes interesting. Consider keys that are multiples of 100 — <code>100, 200, 300, 400</code> — with a table of exactly 100 slots:</p>
<pre class="code-block"><code>100 % 100 = 0
200 % 100 = 0
300 % 100 = 0
</code></pre>
<p>Every key maps to index <code>0</code>. The remaining 99 slots are never used. The hash table has effectively become a linked list — with the overhead of an array attached to it for no benefit.</p>
<p>With 101 slots — a prime number:</p>
<pre class="code-block"><code>100 % 101 = 100
200 % 101 = 99
300 % 101 = 98
</code></pre>
<p>The keys distribute across the table. This is why <code>TABLE_SIZE</code> should be prime , for this hash. Small but real distinction: prime resists clustering specifically when your mixing is as lazy as <code>key % n</code>. It&#39;s a fix for a weak hash, not a law of hash tables in general. Python&#39;s dict and Java&#39;s HashMap use power-of-two sizes and don&#39;t bother with primes at all , they just mix harder before the modulo. Different fix, same problem.</p>
<hr>
<h2 id="collisions"><a class="heading-anchor" href="#collisions" aria-hidden="true">#</a>Collisions</h2>
<p>Here a natural question arises. If prime numbers distribute keys so evenly, why do collisions occur at all?</p>
<p>Because the number of possible keys is not bounded by your table size. A table of 7 slots has indices <code>0</code> through <code>6</code>. Feed it a hundred keys and some indices will necessarily accommodate more than one:</p>
<pre class="code-block"><code>keys → [10, 20, 30, 35, 36, 37, 40, 50, 70, 80, 90, 99]

Index 0  →  35, 70
Index 1  →  36, 50, 99
Index 2  →  30, 37
Index 3  →  10, 80
Index 4  →  (empty)
Index 5  →  40
Index 6  →  20, 90
</code></pre>
<p>Collisions are not a failure of the hash function. They are an arithmetic inevitability when your input set is larger than your table. The prime number minimises them. The linked list at each index handles the remainder.</p>
<h3 id="structure-of-the-table"><a class="heading-anchor" href="#structure-of-the-table" aria-hidden="true">#</a>Structure of the Table</h3>
<p>Each index holds a pointer to the head of a linked list. When a collision occurs, the new element is prepended to that list:</p>
<pre class="code-block"><code>index 0  →  Node → Node → NULL
index 1  →  Node → Node → Node → NULL
index 2  →  Node → NULL
index 3  →  NULL
</code></pre>
<p>The prime number does its job. The linked list does its job. Both are necessary; neither is redundant.</p>
<hr>
<h2 id="the-code"><a class="heading-anchor" href="#the-code" aria-hidden="true">#</a>The Code</h2>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">typedef struct Node {
    int key;
    char value[20];
    struct Node *next;
} Node;

typedef enum {
    INSERT_SUCCESS   =  0,
    INSERT_DUPLICATE =  1,
    INSERT_MEM_ERROR = -1
} InRes;

int hash(int key) {
    int index = key % TABLE_SIZE;
    if (index &lt; 0) {   // handle negative keys
        index += TABLE_SIZE;
    }
    return index;
}

InRes insert(int key, const char *val, Node *arr[]) {
    int index = hash(key);
    Node *curr = arr[index];

    // 1. Check for duplicates
    // We don&#39;t want: index -&gt; 7 -&gt; 7 -&gt; 7 -&gt; 7 -&gt; NULL
    while (curr != NULL) {
        if (curr-&gt;key == key) {
            return INSERT_DUPLICATE;
        }
        curr = curr-&gt;next;
    }

    // 2. Create new node
    Node *new_node = (Node *)malloc(sizeof(Node));
    if (new_node == NULL)
        return INSERT_MEM_ERROR;

    new_node-&gt;key = key;
    strncpy(new_node-&gt;value, val, 19);  // max 19 chars + null terminator
    new_node-&gt;value[19] = &#39;\0&#39;;

    // 3. Link it at the front
    new_node-&gt;next = arr[index];
    arr[index] = new_node;

    return INSERT_SUCCESS;
}

void printTable(Node *arr[]) {
    for (int i = 0; i &lt; TABLE_SIZE; i++) {
        if (arr[i] == NULL)
            continue;  // skip empty buckets, nothing to see here
        printf(&quot;bucket[%d]: &quot;, i);
        Node *curr = arr[i];
        while (curr != NULL) {
            printf(&quot;[%d: %s] -&gt; &quot;, curr-&gt;key, curr-&gt;value);
            curr = curr-&gt;next;
        }
        printf(&quot;NULL\n&quot;);
    }
}

void freeTable(Node *arr[]) {
    for (int i = 0; i &lt; TABLE_SIZE; i++) {
        Node *curr = arr[i];
        while (curr != NULL) {
            Node *temp = curr;
            curr = curr-&gt;next;
            free(temp);
        }
    }
}

/*
 * How freeTable traversal works:
 *
 * [ Person A ] -&gt; [ Person B ] -&gt; [ Person C ]
 *      ^    ^
 *     curr temp
 *
 * [ Person A ] -&gt; [ Person B ] -&gt; [ Person C ]
 *      ^                ^
 *     temp            curr   (leader moves ahead, temp gets freed)
 */

void printRes(int res) {
    if (res == INSERT_SUCCESS) {
        printf(&quot;Insertion successful\n&quot;);
    } else if (res == INSERT_DUPLICATE) {
        printf(&quot;Duplicate key\n&quot;);
    } else {
        printf(&quot;Memory error\n&quot;);
    }
}

int main() {
    Node *hashTable[TABLE_SIZE] = {NULL};

    insert(234, &quot;Srinath&quot;, hashTable);
    insert(65,  &quot;Alice&quot;,   hashTable);
    insert(987, &quot;Bob&quot;,     hashTable);

    printTable(hashTable);

    // Searching also gives you access to the value
    int searchKey = 65;
    Node *curr = hashTable[hash(searchKey)];
    while (curr) {
        if (curr-&gt;key == searchKey) {
            printf(&quot;Found: %s\n&quot;, curr-&gt;value);
            break;
        }
        curr = curr-&gt;next;
    }

    freeTable(hashTable);
    return 0;
}
</code></pre></div>
<p>That is a hash table. An array that knows where things live before you ask.</p>
<hr>
<h2 id="one-limitation-worth-noting"><a class="heading-anchor" href="#one-limitation-worth-noting" aria-hidden="true">#</a>One Limitation Worth Noting</h2>
<p>Everything above assumes integer keys. The modulo operation requires a number, and <code>key % TABLE_SIZE</code> works precisely for that. String keys — a <code>char</code> array — cannot be fed to <code>%</code> directly. They require a function that converts the string to an integer first, then applies the modulo. Simply summing ASCII values works in principle but distributes poorly. One popular fix for string keys is the <strong>djb2</strong> algorithm , a well-known string hash, not the standard one, there isn&#39;t one. FNV, MurmurHash, SipHash all do the same job differently , which we shall examine separately.</p>
]]></content:encoded>
    </item>
    <item>
      <title>The Skyscraper Inside Your Program</title>
      <link>https://srinathshrestha.xyz/blogs/how-stack-work</link>
      <guid>https://srinathshrestha.xyz/blogs/how-stack-work</guid>
      <pubDate>Sun, 15 Feb 2026 14:31:29 GMT</pubDate>
      <description>For any program that is running, the operating system gives it a slice of memory to work with. What the program sees is not the raw physical RAM, but a virtual address space — a private, continuous range of addresses…</description>
      <content:encoded><![CDATA[<p>For any program that is running, the operating system gives it a slice of memory to work with. What the program sees is not the raw physical RAM, but a <strong>virtual address space</strong> — a private, continuous range of addresses that makes memory look clean and isolated.</p>
<p>Now, on a typical 64-bit system this address space is enormous (terabytes in theory), far larger than the physical RAM in the machine. In practice, current x86-64 CPU implement <strong>48 bits virtual addressing</strong>, giving each process up to 256 TB of addressable space which is still large for any computer you can afford. OS and CPU’s memory-management unit, sort of work in tandem to map virtual addresses to real memory pages as needed, the catch is that only the portions actually used are backed by physical RAM, the rest may be mapped lazily, shared with other processes, or moved to disk through paging when memory pressure rises.</p>
<p>A virtual address itself is split into two logical parts. The upper bits form the <strong>virtual page number</strong>, which the hardware translates into a <strong>physical frame number</strong>. The lower bits are the <strong>page offset</strong>, which stays the same during translation and identifies the exact byte within that page. This paging mechanism lets programs see a smooth, continuous memory space while the OS quietly manages where data actually lives.</p>
<p>Inside that virtual address space, memory is divided into regions that serve different roles. You’ll commonly see:</p>
<ul>
<li>a <strong>text (code) segment</strong> containing executable instructions</li>
<li>a <strong>read-only data section</strong> for constants and string literals</li>
<li>a <strong>data segment</strong> for global and static variables</li>
<li>a <strong>heap</strong>, used for dynamic allocation and able to grow during runtime </li>
<li>a <strong>stack</strong>, used for function calls and local variables</li>
</ul>
<p><em>This is a simplified view; the actual layout you see in <code>/proc/&lt;pid&gt;/maps</code> is more granular</em></p>
<p>if you are wondering why, then these regions exist so the OS and hardware can enforce protection, manage growth, and optimize memory use.</p>
<p>Now the stack and heap grow toward each other in the address space, the stack typically starts near the high addresses and grows downward, while the heap starts lower and grows upward. The stack size is limited (often around 8 MB per thread on Linux and Windows by default), whereas the heap can expand as needed within process limits.</p>
<p>If you’re wondering why memory is organized into sections and how the OS manages this virtual space, that’s a separate rabbit hole you can explore it by reading about ELF file format, comparing Clang and GCC outputs, and learning how linker and loaders work. I too am exploring those topics and soon I’ll write a fun, easy-to-understand article without compromising the details, if you are wandering , Hey! why don&#39;t you know these already, then listen, Topics and concepts in CS are like fractals — the more you dig in, the more there is to be dug. </p>
<p>Apart from that , If you want the hardware side of address translation, paging, and memory hierarchy, that falls under Computer Organization and Architecture (COA); a clear overview is available : <a href="https://www.geeksforgeeks.org/computer-organization-and-architecture-tutorials/">here</a></p>
<p>when talking about stacks , we can&#39;t let alone function call right , so when a function is called, a new <strong>stack frame</strong> is created in memory to store the function&#39;s parameters and local variables and other <a href="#doubts-or-queries">bookkeeping</a> info. When the function returns, its entire stack frame is deallocated. </p>
<p>Now here’s something subtle but important: when a function returns, its stack memory doesn’t disappear — it simply becomes available for reuse. If you keep a pointer to that memory, you’re pointing to something that no longer belongs to you.</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">#include &lt;stdio.h&gt;

typedef struct {
  int x;
  int y;
} coord_t;

coord_t *new_coord(int x, int y) {
  coord_t c;      // lives on the stack
  c.x = x;
  c.y = y;
  return &amp;c;      // returning address of a local variable [X]
}

int main() {
  coord_t *c1 = new_coord(10, 20);
  coord_t *c2 = new_coord(30, 40);
  coord_t *c3 = new_coord(50, 60);

  printf(&quot;%d %d\n&quot;, c1-&gt;x, c1-&gt;y);
  printf(&quot;%d %d\n&quot;, c2-&gt;x, c2-&gt;y);
  printf(&quot;%d %d\n&quot;, c3-&gt;x, c3-&gt;y);
}
</code></pre></div>
<p>What’s happening here is subtle: <code>c</code> lives inside the stack frame of <code>new_coord()</code>. When the function returns, that frame is popped and the memory becomes free for reuse. Each new call reuses the same stack slot, so all three pointers end up referring to the same location, which finally contains <code>50, 60</code>. Small print: <code>return &amp;c</code> is <strong>undefined behaviour</strong>, not a promise. The compiler is well within its rights to reuse that slot, which is what happened here and is the boring, common outcome, but it&#39;s just as within its rights to delete the whole dangling mess at compile time, or do literally anything else. What you&#39;re looking at is <em>a</em> thing that happens, on this compiler, today, not <em>the</em> thing that happens. This is called a <strong>dangling pointer</strong> — a pointer that still holds an address, but the object it pointed to no longer exists. basically Stack objects die when the function returns. Pointers to them become ghosts.</p>
<p>Back to our Low level discussion, we have ~8MB of stack space in our virtual address space and local buffers live on the stack too, writing past their boundaries can corrupt adjacent stack data, which essentially is Buffer OverFlow.</p>
<p>speaking about overflow , we have a very common or i should say we <strong>had</strong> a (<code>gets()</code> was removed from the C standard &amp; recommended to Use <code>fgets()</code> instead) very common bug in one of the method called gets() from the string lib from c std lib, which essentially allows the users or programmer to sort of write more bytes to the a variable exceeding it&#39;s predefined limit , through this a hacker can take full control. </p>
<p>One honest caveat before the demo: whether <code>name[8]</code> actually sits right next to <code>is_admin</code> in memory, and which direction, depends on layout, the ABI, whether canaries are on, and compiler flags like <code>-fno-stack-protector</code>. Declaration order in your source is not stack order in memory. This works, on my machine, canaries off. Your mileage varies, which is sort of the whole point of buffer overflows being an exploit you have to earn, not a guarantee you get for free.</p>
<div class="code-container"><span class="code-language">c</span><pre class="code-block language-c"><code class="language-c">#include &lt;stdio.h&gt;
#include &lt;string.h&gt; 
int main() { 
    volatile int is_admin = 0; // address 100; 
    char name[8]; // 92 
    printf(&quot;Enter your name: &quot;); 
    gets(name); 
    printf(&quot;\nDEBUG: name is at %p, is_admin is at %p\n&quot;, name, &amp;is_admin);
    printf(&quot;DEBUG: is_admin value is currently: %d\n&quot;, is_admin); 
    if (is_admin != 0) { 
        printf(&quot;--------------------------------------\n&quot;); 
        printf(&quot;ACCESS GRANTED. Welcome, Administrator.\n&quot;); 
        printf(&quot;--------------------------------------\n&quot;); 
    } else { 
        printf(&quot;Access Denied. You are a mere mortal.\n&quot;);
    } 
    return 0; 
}
</code></pre></div>
<p>in this code , the input we are taking can potentially overwrite the values in the <code>is_admin</code>, through buffer overflow , it the same as how <code>sprintf</code> writes blindly into memory thus we are suggested to use <code>snprintf</code> which takes limit(<code>n</code>) to know it&#39;s boundary, similarly we have <code>scanf(&quot;%s&quot;, name)</code> ,<code>strcpy()</code> and even <code>read()</code> which are mention in the context of buffer overflow, if you are wandering, what bad can happen if our <code>name</code> buffer DO overwrites <code>is_Admin</code>? then i&#39;ll ask you to think twice about it , we have a if condition that is guarding the code inside it through a simple check, that our <code>is_admin</code> has to be a non zero value, so with this user can flip the value of <code>is_admin</code> essentially causing a privilege bypass. That&#39;s not all , hacker can overwrite the stack address and put a pointer to some new machine code, exactly this is crazy right ! well i always say this , hacking begins when we stop thing normally and push the limits, </p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/stackSkyScrapperpng.png" alt="stack_skyscraper_analogy" style="max-width:400px; width:100%" class="post-img" loading="lazy" /><figcaption>stack skyscraper analogy</figcaption></figure> </p>
<p>lets better understand this , imagine the dynamic section of the virtual memory space for a process as a <strong>skyscraper</strong> , where , the High Address are at the ceiling , the low address are the floor, and the stack is sort of starts from the ceiling -&gt; floor and the Heap Grows up (from floor -&gt; ceiling) BTW heap is just a memory space that is not fixed (not limited , theoretically) unlike stack which is around 8 Mb in the Linux and windows, we will discuss on the Heap memory later, for now let&#39;s try  to see the stack through and through alright! </p>
<p>try to imagine this </p>
<div class="code-container"><span class="code-language">scss</span><pre class="code-block language-scss"><code class="language-scss">main()
  └── greet()
</code></pre></div>
<p>by the time we reach <code>greet()</code> the stack looks like this , </p>
<div class="code-container"><span class="code-language">css</span><pre class="code-block language-css"><code class="language-css">%%---higher_address---%%

[greet return address → back to main]
[greet bookkeeping]
[greet locals]

[ main return address → runtime ] ← where program goes after main
[ main bookkeeping ]
[ is_admin ]
[ name[8] ]                       ← your buffer
%% ---lower_address--- %%
</code></pre></div>
<p>you can see that the buffer lives at the bottom of the Block , i&#39;ve added one more function to sort of drive home the point that function call are stacked in memory, </p>
<p>now , when you type input bytes go into name , and when you type more then 8 bytes they don&#39;t stop , they just keep going, into the next slots, guess what&#39;s there in next slot , </p>
<div class="code-container"><span class="code-language">css</span><pre class="code-block language-css"><code class="language-css">name → is_admin → bookkeeping → return address
</code></pre></div>
<p>so this is how we overwrite , and if you really overthink about this like i do , you will reach upon the conclusion that ,</p>
<blockquote><p>A buffer overflow is not “extra input” but it is just writing into memory that belongs to something else.</p>
</blockquote>
<p>When a function finishes, the program needs to know, where do I continue? So it looks at the return address stored on the stack and jumps there. If that address is correct , program continues normally. If that address was overwritten, program jumps to the wrong place, Imagine this as some one is just swapping the rug under your feet when you jump after you finish drinking water till a certain level in a tank that is above you,  wow that was just a wired example, LOL :)) </p>
<p>now hacker can sort of measure , the offset till the return address, </p>
<div class="code-container"><span class="code-language">css</span><pre class="code-block language-css"><code class="language-css">buffer size = 8
+ saved frame pointer = 8
------------------------
return address at byte 16


/*
In simple builds without protections, the return address often appears just above the saved frame pointer, though the exact offset varies depending on compiler, architecture, and security features.
*/
</code></pre></div>
<p>so the input they will enter will sort of look like this </p>
<div class="code-container"><span class="code-language">css</span><pre class="code-block language-css"><code class="language-css">[ padding bytes ]
[ new return address ]
[ attacker-controlled data ]
</code></pre></div>
<p>now some caveat, the string that a hacker will enter have to be, such a string,  that when sort of read as bytes it act as machine instruction, now the catch is , that, for the CPU to successfully being executing, it has to check these 2 following condition </p>
<ol>
<li>execution is redirected to that memory address (e.g return address overwritten to point there)</li>
<li>the memory region is executable,</li>
</ol>
<p>if the program just take the input and prints it, then technically it can&#39;t do any harm , except that&#39;s backwards. The damage, if there is any, already happened the moment <code>gets()</code> wrote past the buffer. Printing afterward doesn&#39;t undo a smashed return address, it&#39;s just the next line of code that happens to run.<br>Now another catch , this can never happen even if you push methods like get() to prod, cuz modern systems often marks stack memory as non-executable (NX), so even if the control jumps there, CPU will block the execution. heights of technology right ! Now if hacker is reading this they might argue that , yeah NX prevents shell-code injection , but we can use return-to-libc or ROP chains, then i will say , yeah that True! , but those topic are beyond our naive lil scope of this article.    <em>being a lil meta here , aren&#39;t we ?</em></p>
<hr>
<h2 id="doubts-or-queries"><a class="heading-anchor" href="#doubts-or-queries" aria-hidden="true">#</a>Doubts or Queries</h2>
<p>this section is for doubts and misunderstanding or confusions i has when i was learning about these topics , which i figured to mention here to clear your model further more, </p>
<p><strong>About Volatile :</strong> </p>
<p>okay so when compiler optimization are on , volatile will tell our compiler , to not sort look at the local block and pre assume that &quot;wait I don&#39;t see any thing updating this var so I&#39;m gonna assume that this is will never change and replace it with some thing concrete in compile time only&quot; , it tell compiler , &quot;dude , there Might be some bigger play here, that you don&#39;t understand so clam down&quot; !!<br>And about the Buffer over flow , code snippet , we were not like updating the <code>is_admin</code> , legally, so compiler though this var will just be 0 all the time. </p>
<p><strong>some volatile pattern</strong></p>
<p>This is often called the <strong>&quot;Const/Volatile Right-Left Rule&quot;</strong>: Read it backward (from right to left) to understand what is happening.</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Code</th>
<th>Read Backwards</th>
<th>What it means</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong><code>volatile int *ptr;</code></strong></td>
<td>&quot;Pointer to an <code>int</code> that is <code>volatile</code>&quot;</td>
<td><strong>The Data is Volatile.</strong><br><br>  <br><br>The <em>pointer</em> stays fixed, but the <em>value</em> it points to (like a hardware timer) changes.</td>
</tr>
<tr>
<td><strong><code>int * volatile ptr;</code></strong></td>
<td>&quot;Volatile Pointer to an <code>int</code>&quot;</td>
<td><strong>The Address is Volatile.</strong><br><br>  <br><br>The <em>value</em> is stable, but the <em>pointer itself</em> might change (e.g., an interrupt swaps which buffer you are reading).</td>
</tr>
<tr>
<td><strong><code>volatile int * volatile ptr;</code></strong></td>
<td>&quot;Volatile Pointer to a Volatile <code>int</code>&quot;</td>
<td><strong>Everything is Chaos.</strong><br><br>  <br><br>Both the <em>address</em> AND the <em>data</em> can change at any millisecond. Rare, but real.</td>
</tr>
</tbody>
</table></div>
<p><strong>Pro Tip:</strong> This works exactly the same way as <code>const</code>. If you master this logic, you master <code>const</code> too.</p>
<hr>
<p><strong>what is bookkeeping :</strong></p>
<p>“<strong>Bookkeeping</strong>” is just the extra data a function stores on the stack so it can run and return correctly.</p>
<p>Besides your variables, a stack frame usually needs to remember things like:</p>
<ul>
<li>the previous stack frame location  </li>
<li>alignment / space reservations  </li>
<li>saved register values (if the function needs them)  </li>
<li>temporary storage the compiler uses</li>
</ul>
<p>The most common piece is the <strong>saved frame pointer</strong> (a reference that helps the program find its way back to the previous frame).</p>
<hr>
]]></content:encoded>
    </item>
    <item>
      <title>Will software Suck ?</title>
      <link>https://srinathshrestha.xyz/blogs/will-software-in-future-suck</link>
      <guid>https://srinathshrestha.xyz/blogs/will-software-in-future-suck</guid>
      <pubDate>Thu, 06 Nov 2025 01:17:24 GMT</pubDate>
      <description>Lately my feed has been overflowing with layoffs and news about companies have stopped hiring juniors. The mid &amp; senior folks they kept get handed the juniors' work on top of their own. Why? Cuz AI makes everything fast. My…</description>
      <content:encoded><![CDATA[<p><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2026/11/578ac211-d079-4b96-adcc-a005f7c0eb02-software-suck.png" alt="" style="max-width:640px; width:100%" class="post-img plain" loading="lazy" /></p>
<p>Lately my feed has been overflowing with layoffs and news about companies have stopped hiring juniors. The mid &amp; senior folks they kept get handed the juniors&#39; work on top of their own. Why? Cuz AI makes everything fast.</p>
<p>My take is that we need the same rate of hiring growth we had before AI, if not more. Good software gets built by handing small pieces of work to people who&#39;ll craft them carefully, an optimisation here, a small feature there, lil research about a slightly faster or efficient algorithm or data struct, and the quality of the whole is the sum of that care. It&#39;s the classic quality vs quantity trope, and software tech is doubling on the everything opposite of it. ( this is not a generalization , rather what the trend is )</p>
<p>Look at this tomfoolery called <strong>tokenmaxxing</strong>.</p>
<p>Back in April 2026 it came out that Meta had an internal leaderboard, <em>Claudeonomics</em>, ranking 85,000+ employees by how many AI tokens they burned. The top burners got titles like <em>Token Legend</em> and <em>Session Immortal</em>. Can&#39;t make this stuff up. Meta, OpenAI &amp; Microsoft all had some version of it, and some engineers reportedly set bots running in loops to climb the board while producing nothing. Of course they did. Measure people by how much they consume and they&#39;ll consume.</p>
<p>Meta took the board down eventually, but the pressure to show the AI bill is paying off is still very much there, and the software being churned out under it is a ticking bomb of CVEs. Folks at Georgia Tech tracking vulnerabilities traced back to AI coding tools counted <strong>35 in March 2026 alone</strong>, up from a couple a few months before, and they reckon the real number is 5–10x that.</p>
<p>The bigger problem is the pipeline.</p>
<blockquote><p><strong>If the industry produces no juniors today, it&#39;ll have no seniors tomorrow.</strong></p>
</blockquote>
<p>You can&#39;t skip a whole tier of the pipeline and expect competence to show up out of thin air. A senior engineer is years of learning, breaking prod (hopefully not too often), getting corrected and soaking up context. Last I checked, there&#39;s no <code>npm install senior-engineer</code>. Take away the years and you take away the engineers.</p>
<p>Meanwhile the seniors, on top of the juniors&#39; work, are reviewing code, designing systems and cleaning up after AI suggestions that sound <em>extremely</em> sure of themselves and fall apart the moment you look at the structure. And the industry&#39;s response? Move faster. Oh, and the models writing that stuff are increasingly trained on older AI output, so it&#39;s AI learning from AI, and that loop is already running.</p>
<p>A model&#39;s context window has practical limits. An engineer who&#39;s spent months inside a large codebase carries its history in their head, how it breaks, why it&#39;s built the way it is, which decisions were deliberate &amp; which were 2am hacks that stuck around. You can&#39;t rebuild that from a context window, at least not with the LLMs we have today. When that engineer leaves, all of it leaves with them.</p>
<p>So if the industry keeps overloading the experienced folks it has left and refuses to grow new ones, it&#39;s not hard to see where this goes. Slower systems, compounding tech debt, and a generation of devs stuck maintaining &amp; debugging codebases nobody around them fully understands, cuz the people who did are gone and never handed any of it over.</p>
<p>The money saved today comes with an invoice tomorrow. <em>And it&#39;ll arrive with interest.</em></p>
]]></content:encoded>
    </item>
    <item>
      <title>Build || !Build</title>
      <link>https://srinathshrestha.xyz/blogs/to-build-or-not-to-build</link>
      <guid>https://srinathshrestha.xyz/blogs/to-build-or-not-to-build</guid>
      <pubDate>Sun, 05 Oct 2025 18:14:37 GMT</pubDate>
      <description>There was a time when nobuild meant exactly what it said. You dropped in an .html file, added some .js and shipped it. Nobody wrote a config file or waited on a build, and none of the rituals and firedancing…</description>
      <content:encoded><![CDATA[<p>There was a time when <em>no-build</em> meant exactly what it said. You dropped in an <code>.html</code> file, added some <code>.js</code> and shipped it. Nobody wrote a config file or waited on a build, and none of the rituals and fire-dancing that shipping a page involves today existed yet. Can you believe it? I know I&#39;m starting to sound like some Dennis Ritchie, which I&#39;m not, but the option is still open to me. It&#39;s buried under a pile of obscure frameworks, but it&#39;s still there.</p>
<p><strong>worked, works &amp; will work</strong></p>
<p>For starters, the feedback is instant. You change something, refresh, and it&#39;s there. It&#39;s light too, cuz it&#39;s raw files served from a CDN cache close to the user, with nothing between the file and the browser that could go wrong. This next one&#39;s a bit of an unpopular opinion, but I think limitations breed ingenuity and push you towards creative ways of communicating information and state. When you only have a handful of features, you&#39;re forced to decide which of them truly matter. All in all, that keeps the entropy of what you put online low.</p>
<p>I also came across a fair critique in a Primeagen video. DHH pointed out that with a build step, every small change means cutting a new build and pushing it out to all your CDNs across the world. Somewhere along the way, frameworks started stamping <em>no-build</em> on projects that pulled fifty dependencies onto the client before rendering a single element. Changing a semicolon could set off cache invalidation, rebuild pipelines and CI jobs that had no business knowing about semicolons. The <em>instant</em> deployment turned into a two-minute affair cuz the CDN needed to rehydrate a configuration file written by someone who&#39;d forgotten that configuration files are not the product.</p>
<p>Complexity is debt. Either you took it on deliberately, or it piled up while you were busy staring at configuration files.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Running Puppeteer on Vercel</title>
      <link>https://srinathshrestha.xyz/blogs/running-puppeteer-on-vercel</link>
      <guid>https://srinathshrestha.xyz/blogs/running-puppeteer-on-vercel</guid>
      <pubDate>Sun, 05 Oct 2025 15:55:49 GMT</pubDate>
      <description>Picture the scene. You have built a Next.js application that uses Puppeteer to generate PDFs. It works. Locally, it works beautifully. The PDFs render, the logic holds, you are satisfied. You deploy to Vercel. then A deeply unwelcoming message. After…</description>
      <content:encoded><![CDATA[<p>Picture the scene. You have built a Next.js application that uses Puppeteer to generate PDFs. It works. Locally, it works beautifully. The PDFs render, the logic holds, you are satisfied. You deploy to Vercel. then</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">Error: Could not find Chrome (ver. 138.0.7204.94).**

This can occur if either:
1. you did not perform an installation before running the script
2. your cache path is incorrectly configured
</code></pre></div>
<p>A deeply unwelcoming message.<br>After some investigation, the situation became clear: Puppeteer bundles a Chromium binary that Vercel&#39;s serverless environment cannot accommodate. The fix suggested by various LLM Tools, rewrite everything using React PDF or pay handsomely for an external browser service, was unsatisfying. A better path existed. Here it is.</p>
<hr>
<h2 id="the-original-setup"><a class="heading-anchor" href="#the-original-setup" aria-hidden="true">#</a>The Original Setup</h2>
<p>The local configuration was straightforward:</p>
<div class="code-container"><span class="code-language">ts</span><pre class="code-block language-ts"><code class="language-ts">// Original working local setup
import puppeteer from &quot;puppeteer&quot;;

export async function generateCertificatePDF(
  data: CertificateData,
): Promise&lt;Buffer&gt; {
  const browser = await puppeteer.launch({
    headless: true,
    args: [
      &quot;--no-sandbox&quot;,
      &quot;--disable-setuid-sandbox&quot;,
      &quot;--disable-web-security&quot;,
    ],
  });
  const page = await browser.newPage();
  await page.setContent(htmlContent);
  const pdfBuffer = await page.pdf({ format: &quot;A4&quot; });
  await browser.close();

  return pdfBuffer;
}
</code></pre></div>
<p><strong>Why it worked locally</strong> is cuz Puppeteer downloads and bundles Chromium at roughly 300MB. A local machine accommodates this without complaint.</p>
<p><strong>Why it failed on Vercel</strong> is cuz Vercel enforces a 50MB function bundle size limit. Puppeteer&#39;s bundled Chromium is six times that figure. Serverless environments do not include Chrome by default and will not search for it on your behalf.</p>
<hr>
<h2 id="a-second-problem--the-database-corruption"><a class="heading-anchor" href="#a-second-problem--the-database-corruption" aria-hidden="true">#</a>A Second Problem — The Database Corruption</h2>
<p>But the worst part wasn’t just the Chrome error. My app had a critical bug:</p>
<div class="code-container"><span class="code-language">ts</span><pre class="code-block language-ts"><code class="language-ts">// DANGEROUS: This was updating the database even when PDF generation failed!
await updateInternCertificateKey(intern.email, s3Key); // s3Key was NULL!
</code></pre></div>
<p>When PDF generation failed, the database was still being updated, with a NULL S3 key. The consequence: users could not regenerate their PDFs because the application believed generation had already succeeded. The application then attempted to retrieve NULL links. Production data was silently corrupted.<br>Both problems required fixing.</p>
<hr>
<h2 id="three-approaches-considered"><a class="heading-anchor" href="#three-approaches-considered" aria-hidden="true">#</a>Three Approaches Considered</h2>
<h3 id="approach-1-react-pdf"><a class="heading-anchor" href="#approach-1-react-pdf" aria-hidden="true">#</a>Approach 1: React PDF</h3>
<p>Rewrite all PDF generation using <code>@react-pdf/renderer</code>. Serverless-friendly at roughly 4MB, no browser dependency, reliable. The cost: a complete rewrite of existing logic, and meaningfully less rendering flexibility.</p>
<div class="code-container"><span class="code-language">ts</span><pre class="code-block language-ts"><code class="language-ts">// React PDF approach - clean but requires rewrite
import { pdf, Document, Page, Text } from &#39;@react-pdf/renderer&#39;;

const MyDocument = () =&gt; (
  &lt;Document&gt;
    &lt;Page&gt;
      &lt;Text&gt;Certificate content...&lt;/Text&gt;
    &lt;/Page&gt;
  &lt;/Document&gt;
);

const buffer = await pdf(&lt;MyDocument /&gt;).toBuffer();
</code></pre></div>
<hr>
<h3 id="approach-2"><a class="heading-anchor" href="#approach-2" aria-hidden="true">#</a>Approach 2</h3>
<p><strong>External Browser Services</strong>. Services such as Browserless.io provide remote Chrome instances via WebSocket. Powerful, complete, and approximately $200 per month. Not appropriate for projects without that budget.</p>
<div class="code-container"><span class="code-language">ts</span><pre class="code-block language-ts"><code class="language-ts">// Browserless approach - works but costs money
const browser = await puppeteer.connect({
  browserWSEndpoint: `wss://chrome.browserless.io?token=${process.env.BLESS_TOKEN}`,
});
</code></pre></div>
<hr>
<h3 id="approach-3-serverless-chromium"><a class="heading-anchor" href="#approach-3-serverless-chromium" aria-hidden="true">#</a>Approach 3: Serverless Chromium</h3>
<p><strong>Serverless Chromium</strong>. The community-maintained <code>@sparticuz/chromium</code> package — built specifically for serverless environments, sized to fit within bundle limits, actively maintained, and free. It keeps your existing Puppeteer code substantially intact.</p>
<hr>
<h2 id="the-implementation"><a class="heading-anchor" href="#the-implementation" aria-hidden="true">#</a>The Implementation</h2>
<p><strong>Step 1 — Package changes:</strong></p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">npm uninstall puppeteer
npm install @sparticuz/chromium puppeteer-core
npm install --save-dev puppeteer
</code></pre></div>
<p><strong>Step 2 — Environment-aware browser launch:</strong><br>The key insight is that development and production require different strategies. One function handles both:</p>
<div class="code-container"><span class="code-language">ts</span><pre class="code-block language-ts"><code class="language-ts">async function getBrowser() {
  if (process.env.NODE_ENV === &quot;production&quot;) {
    const [chromiumModule, puppeteerModule] = await Promise.all([
      import(&quot;@sparticuz/chromium&quot;),
      import(&quot;puppeteer-core&quot;),
    ]);

    const chromium = chromiumModule.default;
    const puppeteer = puppeteerModule.default;

    return puppeteer.launch({
      args: [...chromium.args, &quot;--no-sandbox&quot;, &quot;--disable-setuid-sandbox&quot;],
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath(),
      headless: chromium.headless,
      ignoreHTTPSErrors: true,
    });
  } else {
    const puppeteerModule = await import(&quot;puppeteer&quot;);
    const puppeteer = puppeteerModule.default;

    return puppeteer.launch({
      headless: true,
      args: [&quot;--no-sandbox&quot;, &quot;--disable-setuid-sandbox&quot;],
    });
  }
}
</code></pre></div>
<p><strong>Step 3 — Next.js configuration:</strong></p>
<div class="code-container"><span class="code-language">ts</span><pre class="code-block language-ts"><code class="language-ts">// next.config.ts
const nextConfig: NextConfig = {
  serverExternalPackages: [&quot;puppeteer-core&quot;, &quot;@sparticuz/chromium&quot;],
  webpack: (config, { isServer }) =&gt; {
    if (isServer) {
      config.externals.push(&quot;@sparticuz/chromium&quot;);
    }
    return config;
  },
};
</code></pre></div>
<hr>
<p>The broader lesson, stated plainly: the environment in which your code runs is as much a part of your design constraints as the code itself. What works locally is not a guarantee. Know your deployment target before you commit to your dependencies.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Git Config Flag -&gt; messing around --landed-&gt; Apple’s APFS</title>
      <link>https://srinathshrestha.xyz/blogs/test</link>
      <guid>https://srinathshrestha.xyz/blogs/test</guid>
      <pubDate>Sun, 05 Oct 2025 15:15:35 GMT</pubDate>
      <description>I was learning Git. Minding my own business. Running commands quietly, like a person with no weekend Plans. Then I ran this: Output: well , Why does Git even need to care about case? Case Sensitivity 101 It turns out…</description>
      <content:encoded><![CDATA[<p>I was learning Git. Minding my own business. Running commands quietly, like a person with no weekend Plans. Then I ran this:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">git config --list --local
</code></pre></div>
<p>Output:</p>
<div class="code-container"><span class="code-language">bash</span><pre class="code-block language-bash"><code class="language-bash">core.ignorecase=true
</code></pre></div>
<p>well , <strong>Why does Git even need to care about case?</strong></p>
<hr>
<h2 id="case-sensitivity-101"><a class="heading-anchor" href="#case-sensitivity-101" aria-hidden="true">#</a>Case Sensitivity 101</h2>
<p>It turns out the answer sits at the level of the filesystem itself. <strong>MacOS (HFS+, APFS)</strong> is case-insensitive, but case-preserving. Meaning you create File.txt, attempt <code>file.txt</code> afterwards, and macOS treats them as the same entity, while remembering which capitalisation you preferred. Linux is case-sensitive. <code>File.txt</code> and <code>file.txt</code> are two entirely distinct files, with no opinion about each other whatsoever. Git&#39;s <code>core.ignorecase=true</code> flag exists to prevent repositories from blowing out when developers switch between the two. A small flag carrying considerable weight.</p>
<hr>
<h2 id="apple-filesystems"><a class="heading-anchor" href="#apple-filesystems" aria-hidden="true">#</a>Apple Filesystems</h2>
<p>One question, as tends to happen, led to another. I found myself reading about <strong>HFS+</strong>, Apple&#39;s old filesystem, a relic of the late 1990s, kept alive well past its natural lifespan through what can only be described as determined engineering stubbornness. Then, in 2017, Apple released APFS <mark>Apple File System</mark> designed specifically for SSDs. Built for this century.<br>The difference was considerable.</p>
<p><figure class="post-figure"><img src="https://myblogs-media-975050135234.s3.us-east-1.amazonaws.com/2025/10/02e55beb-5098-4236-be08-b4058619ade9-Gemini_Generated_Image_35gsb935gsb935gs.png" alt="HFS+ vs APFS" class="post-img" loading="lazy" /><figcaption>HFS+ vs APFS</figcaption></figure></p>
<hr>
<h2 id="apfs-"><a class="heading-anchor" href="#apfs-" aria-hidden="true">#</a>APFS ?</h2>
<ul>
<li><strong>Space Sharing</strong> → One container, multiple volumes, sharing a single pool of storage rather than each claiming a fixed partition.</li>
<li><strong>Copy-on-Write (CoW)</strong> → Modified data is written to a new location before the old is discarded. The filesystem never overwrites live data. Corruption from incomplete writes becomes structurally improbable..</li>
<li><strong>Snapshots</strong> → The system can capture its own state at a point in time and return to it precisely. This is what Time Machine is, at its core — not magic, but snapshot management made approachable..</li>
<li><strong>Clones</strong> → Duplicate a file instantaneously. The copy consumes no additional space until the two versions actually diverge.</li>
<li><strong>Atomic Safe Save</strong> → A file either saves completely or does not save at all. There is no intermediate state in which a half-written file can corrupt your data.</li>
<li><strong>Multi-Key Encryption</strong> → Different files can carry different encryption keys. The security model becomes considerably more granular than a single master key over everything.</li>
</ul>
<hr>
<h2 id="the-takeaway"><a class="heading-anchor" href="#the-takeaway" aria-hidden="true">#</a>The Takeaway</h2>
<p>I need to learn about File System More. ;((</p>
]]></content:encoded>
    </item>
  </channel>
</rss>