<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bhushitha Hashan on Medium]]></title>
        <description><![CDATA[Stories by Bhushitha Hashan on Medium]]></description>
        <link>https://medium.com/@bhushithahashan?source=rss-4cb2798e1fcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XNvfMkSKvKybzjQl</url>
            <title>Stories by Bhushitha Hashan on Medium</title>
            <link>https://medium.com/@bhushithahashan?source=rss-4cb2798e1fcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:58:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhushithahashan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Architect’s Manual to the Silicon Hallucination: x86–64 Virtual Memory]]></title>
            <link>https://medium.com/@bhushithahashan/the-architects-manual-to-the-silicon-hallucination-x86-64-virtual-memory-c0142f9db20f?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0142f9db20f</guid>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 07:29:50 GMT</pubDate>
            <atom:updated>2026-02-25T09:33:05.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jk1cb3myj-8E6ZKmmUdTQ.png" /></figure><h3>The Great Lie: Welcome to the Matrix</h3><p>Every single line of code you write is a lie. When your Assembly instruction says mov rax, [0x401000], you aren&#39;t actually looking at the 4 millionth byte of your RAM. You are looking at a <strong>Virtual Address</strong>.</p><p>The Linux Kernel and the CPU are running a massive, high-speed scam. They’ve convinced your process that it’s the only thing alive, sitting on top of a vast, uninterrupted exabyte empire of memory. In reality, your process is a digital orphan, living in a 4 KB playpen, while the <strong>MMU (Memory Management Unit)</strong> frantically swaps the “reality” behind your back.</p><p>Why? Because if processes could see the “Physical RAM,” a single buffer overflow in a JavaScript engine could overwrite the Kernel’s master password list. We created the Matrix to keep the chaos contained.</p><h3>1. The Hallucination Engine (MMU &amp; Page Faults)</h3><p>Think of Physical RAM as the actual concrete floor of a warehouse. <strong>Virtual Memory</strong> is the VR headset every process wears.</p><p>The <strong>MMU</strong> is the hardware component inside your CPU that acts as the VR engine. Every time your code tries to access memory, the MMU intercepts the request.</p><ul><li><strong>The Hit:</strong> If the address is mapped, the MMU silently translates it to physical RAM.</li><li><strong>The Miss:</strong> If you try to touch a “shelf” that doesn’t exist in your VR world, the MMU trips a silent alarm. The CPU pauses, screams <strong>“PAGE FAULT!”</strong>, and hands control to the Kernel to decide if it should give you more RAM or kill you (the infamous Segmentation Fault).</li></ul><h3>2. The Multi-Level Tree: Why Flat Tables are Suicide</h3><p>You might think, “Why not just have a big spreadsheet mapping virtual to physical?”</p><p><strong>The Math of Madness:</strong> A 64-bit address space is 2^64bytes. If we had a flat table with one 8-byte entry for every 4 KB page, the table itself would take up <strong>32 petabytes</strong>. You’d need a supercomputer just to store the map of your RAM.</p><p><strong>The Solution: The Page Table Tree.</strong></p><p>We use a 4-level hierarchy. It’s “Divide and Conquer.” If a process only uses 1 MB of RAM, we only build the “branches” of the tree for that 1 MB. The rest of the 16 exabyte void stays unallocated.</p><ol><li><strong>PML4 (Page Map Level 4):</strong> The Continent.</li><li><strong>PDPT (Page Directory Pointer Table):</strong> The Country.</li><li><strong>PD (Page Directory):</strong> The City.</li><li><strong>PT (Page Table):</strong> The Street.</li><li><strong>Offset:</strong> The specific House Number (byte).</li></ol><h3>3. The Anatomy of an Address: The 48-Bit Slicer</h3><p>Even though we call it 64-bit, the CPU is actually a bit of a lazy architect. It only uses <strong>48 bits</strong> for the actual address. The top 16 bits must be a copy of bit 47 (The <strong>Canonical Rule</strong>).</p><p>When you provide an address, the CPU slices it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*EoP6PX74PH9qXLoe_3vhYg.png" /></figure><h3>4. The CR3 Register: The Source of Truth</h3><p>If the Page Table is the map, the <strong>CR3 Register</strong> is the &quot;You Are Here&quot; marker.</p><p>Every process has its own unique Page Table tree. When the OS context-switches from your Browser to your Terminal, it performs a “Teleportation”:</p><ol><li>It saves your registers.</li><li>It loads the <strong>Physical Address</strong> of the new process’s <strong>PML4</strong> into the CR3 register.</li><li><strong>BOOM.</strong> The entire virtual universe changes. Suddenly, address 0x401000 points to an entirely different piece of physical silicon.</li></ol><p>Here’s how you can <strong>insert the new sections</strong> about physical vs virtual page tables and permission management into your article without touching the existing flow or style. I’ve kept the style consistent and positioned them where they naturally fit — mainly <strong>after section 4 “The CR3 Register”</strong> and before the user/kernel divide.</p><h3>5. The Dual Reality: Virtual vs. Physical Page Tables</h3><p>Think of your virtual address as the illusion the CPU serves you ,but underneath, there are actually <strong>two tables</strong> playing tag-team:</p><ul><li><strong>Virtual Page Table (PTEs)</strong>: The CPU consults this table every time your code accesses memory. This table contains not just the <strong>physical address</strong> but also <strong>permissions flags</strong>: read/write, user/supervisor, and execute.</li><li><strong>Physical Page Table / RAM Tracker</strong>: This is the OS’s bookkeeping. It keeps track of which physical pages are free, allocated, or being shared (like the .text of a shared library). Permissions aren’t stored here — the OS uses this table to decide how to update the virtual page tables when copy-on-write or allocation happens.</li></ul><p><strong>Analogy:</strong></p><ul><li>Virtual table = the “menu” CPU sees</li><li>Physical table = the pantry log the OS keeps to know which shelves are stocked</li></ul><p>When you access memory:</p><ol><li>CPU walks the virtual table (PML4 → PDPT → PD → PT)</li><li>Checks the flags (R/W/X/U/S) in the PTE</li><li>Translates your virtual address into a physical page</li><li>If the access violates a flag → <strong>page fault</strong> → kernel decides what to do (kill, COW, allocate)</li></ol><h3>6.Anatomy of a Page Table Entry (PTE)</h3><p>Each virtual mapping entry in x86–64 is <strong>64 bits</strong>, broken down like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*xSdOpoQsJj5uHNqYGS30GA.png" /></figure><blockquote><em>Every access the CPU makes is automatically checked against these bits. Violations instantly trigger a page fault.</em></blockquote><h3>7.CPU + OS Teamwork: Permission Enforcement</h3><p>The magic happens because <strong>CPU enforces, kernel sets</strong>:</p><ol><li><strong>Kernel sets up the PTEs</strong> for your process, pointing to physical pages and setting R/W/X/U/S flags.</li><li><strong>CPU consults PTEs for every load/store/execute</strong> automatically.</li><li>If the operation is invalid:</li></ol><ul><li>CPU → triggers <strong>page fault</strong></li><li>Kernel → decides: allocate new page (COW), terminate process, or handle exception</li></ul><p><strong>Key insight:</strong> permissions are <strong>per virtual mapping</strong>, not per physical page. The same physical page can have multiple virtual mappings with different R/W/X flags. This is how:</p><ul><li>Shared library code pages are RX for all processes</li><li>Data pages are private (COW)</li><li>NX / W^X protections are enforced</li></ul><h3>8. The Great Divide: User vs. Kernel</h3><p>Linux splits the virtual world right down the middle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*0EPhFPvN84J9PFCI466O2w.png" /></figure><p><strong>The Twist:</strong> The Kernel is mapped into <em>every</em> process’s address space at the same high addresses. Why? So that when you call sys_read, the CPU doesn&#39;t have to swap CR3 (which is slow). It just flips a privilege bit. However, the MMU prevents you from touching it while in &quot;User Mode.&quot; If you try, it’s a Page Fault, bitch.</p><h3>9. Per-Core Secrets: The GS Register &amp; swapgs</h3><p>Now, here is the badass part. Even though the Kernel space is shared, each CPU core needs its own private “Locker” for things like the <strong>TSS (Task State Segment)</strong> and <strong>GDT (Global Descriptor Table)</strong>.</p><p>We don’t want to remap Kernel Page Tables every time we change cores,that’s too much overhead. Instead, we use the <strong>GS Segment Register</strong>.</p><ol><li><strong>The Locker:</strong> Each core has a private page of RAM for its own data.</li><li><strong>The Shadow:</strong> The CPU has a hidden register called MSR_KERNEL_GS_BASE.</li><li><strong>The Switch:</strong> When you enter the Kernel via a syscall, the first thing the Kernel runs is swapgs. This instruction flips the User&#39;s GS value with the Kernel&#39;s GS pointer.</li></ol><p>Now, the Kernel can find its core-specific stack and tables instantly. When it’s time to go back to User-land, it calls swapgs again to give you back your data.</p><h3>10. Huge Pages &amp; The TLB Shortcut</h3><p>Walking a 4-level tree for every memory access would make your 5GHz CPU feel like a calculator.</p><ul><li><strong>The TLB (Translation Lookaside Buffer):</strong> A tiny cache inside the CPU that remembers the last few translations.</li><li><strong>Huge Pages:</strong> By skipping the “Street” (PT) level, we can map <strong>2 MB</strong> or even <strong>1 GB</strong> in one go. This makes the “Tree Walk” shorter and keeps the TLB from getting cluttered.</li></ul><h3>Final Insight</h3><p>The CPU is a world-class magician. It spends its entire life convincing your code that it owns the universe, while secretly juggling CR3, flipping GS registers, and walking 4-level trees just to keep you from accidentally nuking the system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0142f9db20f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Linux Kernel Hijacks Your CPU: The Hardcore Guide to Linux x86–64 Internals]]></title>
            <link>https://medium.com/@bhushithahashan/how-the-linux-kernel-hijacks-your-cpu-the-hardcore-guide-to-linux-x86-64-internals-1048356826ca?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1048356826ca</guid>
            <category><![CDATA[x86]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 15:28:40 GMT</pubDate>
            <atom:updated>2026-02-21T15:29:12.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9tdlxL6b-sFkc5a6D_Rkg.png" /></figure><p>On your journey on learning assembly and system programming, while at some point, you have to stop thinking of “Linux” as a program. Linux is an <strong>orchestrator</strong> that lives in the gaps between your code. Your program thinks it owns the CPU, but it’s actually living in a illusion.</p><h3>The Two Worlds: Rings, Privilege, and the “Secret Bit”</h3><p>Before we talk about anything, we have to talk about <strong>Authority</strong>. The x86–64 CPU doesn’t just “run code”; it runs code at a specific <strong>Current Privilege Level (CPL)</strong>. You’ve probably heard of Ring 3 (User) and Ring 0 (Kernel).</p><p>But here’s the expert detail: <strong>How does the CPU actually know which ring it’s in?</strong> It’s tucked away in the <strong>CS (Code Segment) Register</strong>. The bottom two bits of the CS register are the CPL. If they are 11, the CPU is in Ring 3 (User-land). If they are 00, the CPU is in Ring 0 (Kernel-land). This &quot;secret bit&quot; changes everything about what the CPU is allowed to do.like touching hardware or modifying the page tables.</p><p>When your program is running, it’s using the <strong>User Stack</strong>. This is that messy, high-memory area (0x7fff...) where your local variables and return addresses live. But the moment you need something from the OS like reading a file or handling a timer tick,the CPU has to switch to the <strong>Kernel Stack</strong>. The Kernel Stack is a clean, 8KB or 16KB &quot;secure office.&quot; You <strong>never</strong> want your kernel code running on a user stack, because a malicious user could manipulate that memory while the kernel is working.</p><h3>The Foundation: GDT, IDT, and the Architecture’s Map</h3><p>Before the CPU can even boot into an OS, it needs to know the “Rules of the House.” These are defined by two massive tables that aren’t just floating in space ,they are anchored by the CPU architecture itself.</p><ul><li><strong>The GDT (Global Descriptor Table):</strong> Think of this as the master blueprint for memory segments. It tells the CPU where “God Mode” (Kernel) memory starts and where “Citizen” (User) memory ends. The OS sets this up at a specific address in protected memory and then slams that address into the <strong>GDTR register</strong>. Once that’s set, the CPU knows the boundary between the rings.</li><li><strong>The IDT (Interrupt Descriptor Table):</strong> This is the emergency dispatch board. It has 256 “phone lines” (vectors). If a keyboard key is pressed, or a divide-by-zero error happens, the CPU looks at the <strong>IDTR register</strong> to find this table, then jumps to the specific handler function listed in the table.</li></ul><h3>The Identity Crisis: Silicon Wiring &amp; The SWAPGS Hack</h3><h4>The Problem: A Dumb Math Machine</h4><p>When a CPU core is redlining at 3GHz, it’s essentially just a hyper-fast, “dumb” math machine. It knows how to add, jump, and read memory, but it has zero self-awareness. It <strong>does not know</strong> which Linux process it is currently running. In a high-level language like C, you can just call getpid(), but down in the basement of Assembly, there is no such thing as a mov rax, current_pid instruction.</p><p>The Kernel needs to find the task_struct,that massive &quot;passport&quot; containing the process name, PID, and memory maps <strong>instantly</strong> the moment you enter a syscall. If the Kernel has to go searching through a linked list every time you call read(), the whole system would lag into oblivion.</p><h4>The Solution: Per-CPU Data &amp; The Shadow Registers</h4><p>The Kernel solves this by creating a dedicated block of memory for <strong>every single CPU core</strong> on your motherboard. This is the <strong>Per-CPU Data Area</strong>. Core 0 has its own block, Core 1 has its own, and so on. Inside Core 0’s block, at the very first byte (offset 0), the Kernel stores a pointer to the task_struct of the process currently assigned to that core.</p><p>To access this memory at light speed, the Kernel uses the <strong>GS Segment Register</strong>. But there’s a hardware catch: in 64-bit mode, the GS register itself is only 16 bits.way too small to hold a 64-bit memory address. To bypass this, the CPU designers added &quot;Shadow Registers&quot; called <strong>Model Specific Registers (MSRs)</strong>. Specifically, we care about MSR_GS_BASE (0xC0000101). This is a hidden 64-bit register that user-space programs can&#39;t touch. It holds the actual 64-bit base address of that Per-CPU Data Area.</p><h4>The SWAPGS Hand-off: Flipping the Script</h4><p>This is where the “Identity Crisis” gets resolved through a high stakes flip. See, when you’re in User land, the user program might be using GS for its own business (like Thread Local Storage). The &quot;Shadow&quot; MSR_GS_BASE is currently pointing to the user&#39;s data.</p><p>The moment you hit a syscall, you land in the Kernel&#39;s entry_SYSCALL_64, but the CPU is still &quot;wearing&quot; the user&#39;s identity. If the Kernel tried to read gs:[0] right then, it would be reading the user&#39;s garbage and would instantly Kernel Panic. To fix this, the very first instruction in the Kernel&#39;s entry code is <strong>SWAPGS</strong>.</p><p>The CPU has <em>another</em> hidden register called MSR_KERNEL_GS_BASE. When SWAPGS fires, it instantly swaps the values of the &quot;User GS Base&quot; and the &quot;Kernel GS Base&quot; in a single clock cycle. Suddenly, MSR_GS_BASE is pointing to the <strong>Kernel&#39;s Per-CPU area</strong>.</p><p>Now, the Kernel can safely run:</p><p>mov rax, gs:[0]</p><p><strong>Boom.</strong> RAX now holds the pointer to the task_struct. The Kernel has found its ID card. It knows exactly who is calling it.</p><h4>Why This Matters for Context Switching</h4><p>When the scheduler decides Process A has had enough time and it’s Process B’s turn on Core 0, it doesn’t just change the registers. It goes to that <strong>Per-CPU area</strong> for Core 0 and overwrites the pointer at gs:[0] with a pointer to <strong>Process B’s </strong><strong>task_struct</strong>.</p><p>The next time Core 0 executes a SWAPGS and looks at gs:[0], it finds B instead of A. The CPU doesn&#39;t even know it happened; it just follows the pointer in its &quot;glovebox.&quot;</p><h3>The Many Gates: Understanding entry_64</h3><p>This is where most people get confused. They think there’s just one “entry” into the kernel. In reality, the kernel has a whole hallway of different “Bouncers” called <strong>entry_64 handlers</strong>.</p><ul><li><strong>The Specialized Bouncers (Interrupts):</strong> In the IDT we mentioned earlier, every hardware interrupt (like a timer or a disk drive) has its own dedicated entry point. You have entry_64_timer, entry_64_keyboard, etc. These are tiny assembly stubs that handle the specific hardware &quot;glitch&quot; before jumping to the common kernel code.</li><li><strong>The Common Gate (Syscalls):</strong> Syscalls don’t use the IDT because the IDT is “slow.” Instead, modern x86–64 uses the syscall instruction. The CPU has a special register called LSTAR (Long System Target Address). The OS writes the address of the <strong>common </strong><strong>entry_SYSCALL_64 handler</strong> into this register at boot. Every time your code calls printf or open, the CPU teleports directly to this one specific gate.</li></ul><h3>The Forensic Snapshot: pt_regs</h3><p>The moment you hit any of those entry_64 gates, the kernel has to take a &quot;Forensic Snapshot.&quot; If it doesn&#39;t, it will overwrite your variables and your program will crash when it returns.</p><p>First, the <strong>hardware (CPU microcode)</strong> automatically pushes a “Hardware Frame” (RIP, CS, RFLAGS, RSP, SS) onto the kernel stack. Then, the <strong>software (the </strong><strong>entry_64 assembly)</strong> manually pushes every other register (RAX, RBX, RDI, etc.).</p><p>The result is a structure called <strong>pt_regs</strong> sitting on the stack. This is a bit-for-bit copy of the user&#39;s brain. If the kernel wants to return a value from a syscall, it doesn&#39;t just put it in a register; it <strong>overwrites the </strong><strong>RAX slot in the </strong><strong>pt_regs structure on the stack</strong>. When the kernel finally exits, it &quot;pops&quot; that modified RAX into the physical register, and the user-space program sees the return value.</p><h3>The Grand Shuffle: Context Switching</h3><p>This is the part of where the CPU suddenly realizes it’s not working for Process A anymore. This is <strong>The Grand Shuffle</strong>.</p><p>When the Linux scheduler decides that Process A has had enough time on the stage and it’s Process B’s turn, it doesn’t just “jump” to the new code. It has to perform a surgical, bit-for-bit heart transplant of the CPU’s entire state. If a single register is off by one bit, the whole system panics and dies.</p><p>Here is exactly how that high stakes transition happens, step by microscopic step.</p><h4>Step 1: Freezing Process A (The Preservation)</h4><p>Before the scheduler even thinks about Process B, it has to put Process A into a deep freeze. Remember, Process A was likely in the middle of a syscall or was just interrupted by a timer.</p><ol><li><strong>The Kernel Snapshot:</strong> We already have the pt_regs sitting on the top of Process A&#39;s kernel stack .that’s the snapshot of what A was doing in <strong>user-space</strong>.</li><li><strong>The Kernel-Mode State:</strong> But Process A was <em>also</em> doing work inside the kernel (running the scheduler code). The CPU has registers that the kernel was using for its own math. The kernel pushes <em>those</em> registers (like RBP, RBX, and others that are &quot;callee-saved&quot;) onto the stack as well.</li><li><strong>The Anchor Point:</strong> Now comes the critical move. The kernel takes the current value of the physical <strong>RSP register</strong> (the pointer to the top of A’s kernel stack) and tucks it away into a variable inside A’s task_struct, specifically at A-&gt;thread.sp.</li></ol><p>At this exact moment, Process A is totally “static.” It’s just a pile of data sitting on a private stack, and its “last known location” is safely recorded in its task_struct.</p><h4>Step 2: The TSS Update</h4><p>This is the hardware “trap” logic that people often miss. Even though we are switching to Process B, we are still technically running inside the kernel on the same physical CPU core.</p><p>The <strong>TSS (Task State Segment)</strong> is a piece of hardware memory that the CPU core looks at every time a user program hits a syscall. The CPU needs to know: <em>&quot;If this guy hits a syscall, where is his secure kernel stack?&quot;</em></p><p>If the kernel forgets to update the TSS, and Process B makes a syscall, the CPU will look at the TSS, see <strong>Process A’s old stack pointer</strong>, and try to land there. That’s a “Kernel Stack Overlap” a catastrophic bug where two different processes try to share the same memory.</p><p>To prevent this, the kernel performs the <strong>TSS Update</strong>:</p><p>It takes the pointer to the very top (the “ceiling”) of <strong>Process B’s kernel stack</strong> (stored in B-&gt;thread.rsp0) and writes it into the TSS.rsp0 field of the physical CPU core. Now, the hardware is &quot;re-wired&quot; to recognize B as the legitimate owner of the next kernel entry.</p><h4>Step 3: The Jump (Swapping the Stacks)</h4><p>Now for the actual “Shuffle.” This is the moment where the CPU’s “now” changes.</p><p>The kernel executes a mov instruction that changes the <strong>RSP register</strong> from A&#39;s kernel stack to <strong>B&#39;s kernel stack</strong>.</p><ul><li><strong>A is now “gone”:</strong> The CPU is no longer looking at A’s memory.</li><li><strong>B is now “present”:</strong> The CPU is now pointing at the stack where Process B was frozen the last time it was running.</li></ul><p>This is the “teleportation.” Because the stack pointer has changed, every pop instruction from here on out will pull data from <strong>B&#39;s history</strong>, not A&#39;s.</p><h4>Step 4: The Wakeup</h4><p>Process B is now “active,” but it’s still trapped inside the kernel. It needs to be kicked back out to user-space so it can keep running its actual code (like a browser or a game).</p><ol><li><strong>Restoring the Kernel State:</strong> The kernel starts pop-ing those &quot;callee-saved&quot; registers we mentioned earlier. This restores the kernel&#39;s own math to exactly where it was when B was last descheduled.</li><li><strong>The Final Threshold:</strong> The kernel then moves to the very top of the stack where the pt_regs snapshot is waiting. It pops all the general-purpose registers (RAX, RBX, RDI, etc.) back into the CPU.</li><li><strong>The Return to Reality:</strong> Finally, the kernel executes sysretq or iretq. This is the &quot;Wake Up&quot; call. The CPU:</li></ol><ul><li>Flips the Privilege Bits in the CS register back to <strong>Ring 3 (User Mode)</strong>.</li><li>Smashes the <strong>RIP (Instruction Pointer)</strong> with the saved address from B’s pt_regs.</li><li>Restores the <strong>User RSP</strong> so the program is back on its own messy user stack.</li></ul><p>then Process B “wakes up” and continues executing the very next assembly instruction after the one that was interrupted. It has no idea it was ever paused, no idea that Process A ever ran, and no idea that the kernel just performed a high-speed stack-swap behind its back.</p><h3>The Takeaway</h3><ul><li><strong>GDT/IDT</strong> are the maps (set at boot).</li><li><strong>TSS</strong> is the stack-switcher (updated on every context switch).</li><li><strong>entry_64</strong> are the bouncers (specialized for interrupts, common for syscalls).</li><li><strong>pt_regs</strong> is the snapshot (where the kernel does “surgery” on your return values).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1048356826ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Red Zone & Why Your Stack Matters More Than You Think In Assembly]]></title>
            <link>https://medium.com/@bhushithahashan/the-red-zone-why-your-stack-matters-9a487a7a4ee6?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a487a7a4ee6</guid>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[x86-assembly]]></category>
            <category><![CDATA[os]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 10:28:24 GMT</pubDate>
            <atom:updated>2026-02-20T10:30:30.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7y9AN00B06T-cm0vVDcSw.png" /></figure><p>Okay, first things first. We’ve all seen this word <strong>red zone</strong> floating around in assembly guides, and it sounds like some spicy secret NASA shit. But nah, it’s just a <strong>special 128-byte area below RSP in x86–64 Linux</strong> that you’re <strong>not supposed to touch in leaf functions</strong>.</p><p>Why? Because:</p><ul><li>It’s reserved by the ABI (Application Binary Interface).</li><li>Linux uses it for stuff like <strong>interrupts, signals, and other kernel shenanigans</strong>.</li><li>If you mess with it, your code might crash like a cheap Windows 95 game.</li></ul><p>Think of it like that one neighbor who said “don’t park there” and but if you do, u got a ticket.</p><h3>How Signals Come In and Mess With Your Stack</h3><p>Imagine you’re chilling in your program, RSP pointing somewhere safe, doing your thing. Then BAM! SIGINT hits by some user pressed Ctrl+C, or maybe the kernel just wants to ruin your day.</p><p>Here’s what goes down:</p><ol><li>CPU switches you <strong>from user mode → kernel mode</strong>.</li><li>It pushes a tiny bit of state automatically (RIP, flags, CS, SS).</li><li>Kernel saves <strong>all your registers</strong> into a nice little struct called pt_regs on the <strong>kernel stack</strong>.(remember this pt_reg well…u see it whole a lot later)</li></ol><p>Now, don’t confuse this pt_regs with your task_struct or some hidden magic.it’s just a struct sitting <strong>on your private kernel stack</strong>, holding all the juicy CPU state like RAX, RBX, RSP, RIP, etc.</p><h3>Kernel Stack vs User Stack !!Now Who’s Holding What?</h3><ul><li><strong>Kernel stack</strong> = your CPU state while the kernel is busy handling your ass</li><li><strong>User stack</strong> = your normal program’s stack, plus signal frames when signals hit</li></ul><p>When a signal is delivered, the kernel says:</p><blockquote><em>“Hey, let me build a backup of this CPU state for later.”</em></blockquote><p>It copies pt_regs → <strong>user stack signal frame</strong>. Now the <strong>kernel modifies its copy of pt_regs</strong> to make RIP point to <strong>your handler</strong> and RSP point to the <strong>top of that signal frame</strong>.</p><p>Now Now keep in mind: your handler can push/pop locals all it wants. The kernel doesn’t care honestly .it knows where the <strong>signal frame</strong> actually is thanks to a <strong>trampoline pointer at the top</strong>.But More on that later.</p><h3>But What About Context Switches?</h3><p>Your CPU ain’t always yours. Linux scheduler says “ok boomer, time to swap you out.”</p><ul><li>Before swapping, the kernel saves <strong>all callee-saved registers</strong> into the <strong>kernel stack</strong> (the same stack holding pt_regs).</li><li>Then it shoves the <strong>RSP of the kernel stack</strong> into your task_struct’s thread pointer.</li><li>Switches RSP → next task’s kernel stack → restores registers → boom, you’re some other process now.</li></ul><p><strong>Key insight:</strong> The <strong>task_struct never holds all register states</strong> its just a pointer to the kernel stack. Efficient, cache-friendly, and fast as hell.</p><h3>Signal Delivery, RSP Moves, and Trampolines</h3><p>Now here’s the juicy part i promised u earlier that we’ll cover... You must be probably thinking:</p><blockquote><em>“Yo, but what if I push/pop locals in my handler? Won’t that break the offsets?”</em></blockquote><p>Nah, homie. The kernel doesn’t give a fuck about your handler’s RSP after it starts. Why?</p><ul><li>Trampoline at the <strong>top of the signal frame</strong> knows where the frame <strong>actually starts</strong>.</li><li>rt_sigreturn syscall reads the saved pt_regs from <strong>that frame</strong>, not from your moving RSP.</li></ul><p>Flow:</p><ol><li>Handler runs, moves RSP, pushes locals, whatever.</li><li>Handler hits ret → goes to <strong>kernel trampoline</strong> (remember, normal ret would fuck up if it tried to pop the original RIP).</li><li>Trampoline does syscall rt_sigreturn</li><li>Kernel copies <strong>user stack signal frame → kernel pt_regs</strong></li><li>iretq → CPU jumps back to <strong>exactly where you were before signal</strong>, all registers restored.</li></ol><p>Thats it u dont even know wtf just happend….</p><h3>Key Takeaways For Assembly Nerds</h3><ol><li><strong>Red zone</strong> = 128 bytes below RSP, don’t touch in leaf functions.</li><li><strong>Kernel stack pt_regs</strong> = authoritative CPU state while kernel is handling signals.</li><li><strong>User stack signal frame</strong> = backup copy, used for restoring after handler finishes.</li><li><strong>Handler can push/pop locals freely</strong>, kernel uses trampoline + offsets to find pt_regs.</li><li><strong>rt_sigreturn</strong> = magic syscall that copies frame → kernel pt_regs → iret back to original context.</li><li><strong>Normal ret in handler</strong> = bad news, must hit trampoline → syscall.</li><li><strong>Context switches</strong> save RSP of kernel stack, not full registers in task_struct.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a487a7a4ee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wait… The CPU Handles the Stack Automatically?]]></title>
            <link>https://medium.com/@bhushithahashan/wait-the-cpu-handles-the-stack-automatically-ba6ead09d2c8?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6ead09d2c8</guid>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[x86-assembly]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 15:21:53 GMT</pubDate>
            <atom:updated>2026-02-19T15:21:53.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJlpPkXtD62sGXfTWqt8tg.png" /></figure><p>I was just scrolling… Just casually going through some low-level stuff.</p><p>Then I saw this line,</p><blockquote><em>“The stack is a piece of memory. It is the only place where the CPU handles memory automatically.”</em></blockquote><p>And I paused.</p><p>Not because I didn’t know what the stack was.<br>I know push. I know pop. I know call and ret. I’ve written assembly before.</p><p>But something about that sentence felt… off.</p><p>Like bro what do you mean “only place where the CPU handles memory automatically”?<br>Memory is memory. RAM is RAM. What is this dramatic nonsense?</p><p>So I had to actually stop and think.Then I slowed down and mentally expanded what push really does.</p><p>And that’s when it hit me.</p><p>I wasn’t missing knowledge. I was missing perspective.</p><p>So I decided to write this.because sometimes you “know” something for years, but you don’t really see it until one random sentence forces you to.</p><h3>The Stack Is Not Special Memory</h3><p>Let’s kill the myth first.</p><p>The stack is not some sacred region carved out by the gods of silicon.</p><p>It’s just memory.</p><p>Literally the same RAM your heap lives in.<br>Same physical memory. Same bytes. Same electricity flipping bits.</p><p>There’s no “stack chip.”<br>No “stack hardware zone.”</p><p>So what makes it different?</p><p>Not the memory.</p><blockquote>The instructions.</blockquote><h3>The “Automatic” Part Is the Real Story</h3><p>When you write:</p><pre>push rax</pre><p>You didn’t specify:</p><ul><li>What address to use</li><li>Where in memory to write</li><li>How to adjust anything</li></ul><p>But something definitely happened.</p><p>The CPU silently did:</p><pre>rsp -= 8<br>memory[rsp] = rax</pre><p>You didn’t say “use rsp.”<br>You didn’t say “subtract 8.”<br>You didn’t say “store at this address.”</p><p>The instruction already <em>knows</em> to use RSP.</p><p>That’s the automatic part.</p><p>The stack isn’t special.</p><p>The <strong>instructions are wired to treat RSP specially.</strong></p><p>And that’s the subtle thing I had known but didn’t consciously realize before.</p><h3>Compare It to Normal Memory</h3><p>If you want to write to heap memory:</p><pre>mov [rbx], rax</pre><p>You must:</p><ul><li>Know the address</li><li>Put it in a register</li><li>Explicitly tell the CPU where to write</li></ul><p>Nothing automatic.</p><p>The CPU isn’t like:</p><p>“Oh you probably meant some default area bro.”</p><p>Nope.</p><p>It does exactly what you say. No babysitting.</p><p>But with push/pop/call/ret?</p><p>The CPU goes:</p><p>“I got you. I’ll handle the pointer movement.”</p><p>That’s different.</p><h3>“CALL and RET “The Real Mind Bender</h3><p>When you do,</p><pre>call func</pre><p>You think:<br>“Jump to function.”</p><p>But the CPU is doing some sneaky stuff behind your back:</p><pre>rsp -= 8<br>memory[rsp] = return_address<br>rip = func</pre><p>It stores the return address automatically.</p><p>You never said:<br>“Store this address here.”</p><p>It just does it.</p><p>Then:</p><pre>ret</pre><p>Does:</p><pre>rip = memory[rsp]<br>rsp += 8</pre><p>Again ,automatic.</p><p>The CPU is literally managing memory for you.</p><p>That’s wild.</p><p>Everywhere else in assembly, you are the adult.<br>On the stack, the CPU becomes your overprotective mom.</p><h3>So Why Only the Stack?</h3><p>Because the architecture defines special semantics for certain instructions.</p><p>push, pop, call, ret ,they are hardwired to use RSP.</p><p>There is no equivalent for heap memory.</p><p>There’s no instruction like:</p><pre>push_heap rax</pre><p>The CPU does not care about your malloc.<br>It does care about RSP.</p><p>That’s the difference.</p><h3>And This Is Where Exploit Dev Gets Spicy</h3><p>Now here’s where it becomes dangerous.</p><p>If,</p><pre>ret</pre><p>automatically loads RIP from memory pointed by RSP…</p><p>Then if someone overwrites that memory…</p><p>They control RIP.</p><p>That’s not magic.<br>That’s just the CPU doing exactly what it was designed to do.</p><p>Stack overflows aren’t some mysterious vulnerability.</p><p>They’re just:</p><p>“CPU trusted memory at RSP.”</p><p>And someone corrupted it.</p><p>Boom. Control flow hijack.</p><h3>The Mental Shift</h3><p>Before, I “knew” how push worked.After thinking about that sentence, I realized that the stack isn’t special because of memory.</p><p>It’s special because the CPU implicitly manipulates it.</p><p>That’s the difference between:</p><ul><li>Memorizing assembly</li><li>Understanding architecture</li></ul><p>And that’s the kind of understanding that changes how you think.</p><h3>The Final Realization</h3><p>If I do this:</p><pre>sub rsp, 8<br>mov [rsp], 123</pre><p>Did I use the stack?</p><p>Technically yes.</p><p>But the CPU didn’t help me.</p><p>That wasn’t automatic behavior.</p><p>That was just normal memory access using RSP.</p><p>The stack only becomes “special” when you use instructions that implicitly manage it.</p><p>That’s the whole thing.</p><p>And somehow that small distinction makes everything click.</p><h3>End of story</h3><p>Sometimes you “know” something.But you don’t see it.And one well-worded sentence hits differently.</p><p>The stack isn’t magic.</p><p>It’s just the only memory region the CPU babysits.</p><p>And once you realize that, assembly feels less mysterious and more mechanical.</p><p>And honestly?</p><p>That’s when it starts getting fun as hell.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6ead09d2c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your CPU Hates Your “Efficient” Structs]]></title>
            <link>https://medium.com/@bhushithahashan/your-cpu-hates-your-efficient-structs-b4a916adcb9f?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a916adcb9f</guid>
            <category><![CDATA[x86]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[c-language]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 23:08:14 GMT</pubDate>
            <atom:updated>2026-01-18T09:45:24.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gbz1FN54LjyXob-ZHEdofw.png" /></figure><h3>How I Learned That Padding Isn’t Waste</h3><p>I used to pack my structs tight.</p><p>No padding. No “wasted” bytes. Just clean, compact layouts that felt smart and intentional. I’d look at a memory dump and feel good about myself.</p><p>Then things got weird.</p><p>Nothing was <em>wrong</em> exactly. The values were correct. The logic checked out. But performance felt… heavy. Like the CPU was dragging its feet. And every once in a while, something would crash for reasons that made absolutely no sense.</p><p>That’s when I learned about the <strong>data stitching nightmare</strong>.</p><h3>CPUs Don’t Think in Bytes</h3><p>As programmers, we think in bytes.<br>CPUs don’t.</p><p>Modern CPUs move memory in <strong>fixed-width chunks </strong>usually 8 bytes at a time on x86–64. SIMD instructions move 16 bytes, sometimes more. Memory isn’t a stream of individual bytes to the hardware. It’s lanes. Blocks. Rows.</p><p>Think of it like a parking lot where every spot is exactly 8 feet wide.</p><p>Now imagine you do this:</p><pre>struct BadIdea {<br>    char  c;<br>    long  x;<br>};</pre><p>Looks harmless. But here’s what you just asked the CPU to do.</p><p>You put a single byte first. Then you dropped an 8 byte value right after it. That long starts one byte into a lane and spills into the next one.</p><p>You didn’t store data.<br>You <strong>split it across boundaries</strong>.</p><h3>The Straddle Problem</h3><p>Here’s the physical reality:</p><pre>+--------+------------+-----------------------+<br>| Lane   | Addresses  | What&#39;s Inside         |<br>+--------+------------+-----------------------+<br>| Lane 1 | 8–15       | c + 7 bytes of x      |<br>| Lane 2 | 16–23      | 1 byte of x + junk    |<br>+--------+------------+-----------------------+</pre><pre>Lane 1 (8–15):   c | x0 | x1 | x2 | x3 | x4 | x5 | x6<br>Lane 2 (16–23):  x7 | ?? | ?? | ?? | ?? | ?? | ?? | ??</pre><p>To load that long, the CPU can’t just grab it.</p><p>It has to:</p><ul><li>load the first lane</li><li>throw away the char</li><li>load the second lane</li><li>mask out garbage</li><li>stitch the pieces together</li></ul><p>Even on CPUs that <em>support</em> unaligned access, this isn’t free. The single load instruction you wrote turns into multiple internal micro operations.</p><p>You asked for one thing.<br>The CPU did five.</p><h3>What This Looks Like When the CPU Doesn’t Help You</h3><p>If you’ve ever done this manually in assembly, you know how ugly it gets:</p><pre>movzx rax, byte [9]<br>movzx rbx, byte [10]<br>shl rbx, 8<br>or  rax, rbx<br>; repeat... and repeat... and repeat</pre><p>One memory load becomes a parade of shifts, masks, and ORs. Registers get burned. Pipelines stall. Performance quietly dies.</p><p>This is why misalignment doesn’t show up as a bug ,it shows up as <em>mystery slowness</em>.</p><h3>The Stack Makes This Worse</h3><p>Now take this mistake and put it on the <strong>stack</strong>.</p><p>On x86–64, there’s a hard rule enforced by the ABI:<br><strong>the stack must be 16-byte aligned before a function call</strong>.</p><p>Why? Because modern code uses SSE instructions that move 16 bytes at once.</p><pre>movaps xmm0, [rsp]   ; requires 16-byte alignment</pre><p>If rsp is off by even 8 bytes, this instruction doesn’t slow down.</p><p>It crashes.</p><p>And here’s the trap: a call instruction <em>automatically</em> pushes an 8-byte return address. If you don’t realign the stack after that, you’re already broken.</p><p>That’s why function prologues exist. Not for style. For survival.</p><h3>Padding Is Not Waste</h3><p>Here’s the fix:</p><pre>struct GoodIdea {<br>    char  c;<br>    char  _pad[7];<br>    long  x;<br>};</pre><p>You leave 7 bytes unused. On purpose.</p><p>Now x starts exactly where the CPU wants it. One load. No stitching. No tricks. No micro-ops hiding under the hood.</p><p>Those 7 bytes aren’t waste. They’re <strong>rent</strong> you pay so the hardware doesn’t make your life miserable.</p><h3>The Tradeoff Nobody Tells You About</h3><p>In 2026:</p><ul><li>RAM is cheap</li><li>CPU cycles are not</li></ul><p>If you trade a few bytes of memory to save dozens of cycles in hot paths, you win. Every time.</p><p>This matters in real places:</p><ul><li>kernels</li><li>allocators</li><li>networking stacks</li><li>databases</li><li>game engines</li><li>real-time systems</li></ul><p>Anywhere memory gets touched a lot, alignment becomes performance.</p><h3>The Lesson I Had to Learn the Hard Way</h3><p>Padding isn’t a compiler quirk.<br>Alignment isn’t an optimization.</p><p>It’s the <strong>contract</strong> between your code and the hardware.</p><p>If you respect it, the CPU works with you.<br>If you fight it, the CPU does arts and crafts behind your back and charges you for it.</p><p>Align your data.<br>Align your stack.</p><p>And stop being byte wise and cycle foolish.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a916adcb9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CPU Data Geometry:Why the Compiler Wastes Memory and Why It’s Right??]]></title>
            <link>https://medium.com/@bhushithahashan/cpu-data-geometry-alignment-padding-and-execution-8fbd44f3c83e?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fbd44f3c83e</guid>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 16:40:53 GMT</pubDate>
            <atom:updated>2026-01-14T00:13:42.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ixdDXLjwDi1FHhZaXXe1g.png" /></figure><p>At some point, every low-level programmer hits the same moment of disbelief.</p><p>You define a struct that, by basic arithmetic, should be 9 bytes.<br>You print sizeof op.</p><p><strong><em>The result:The compiler calmly replies: 16.</em></strong></p><p>Your first instinct is usually frustration:</p><p><strong><em>“Why are you wasting my memory? I didn’t ask for this.”</em></strong></p><p>That reaction is reasonable if you’re thinking like a programmer who reasons in variables and bytes.</p><p>But the compiler is not optimizing for <em>human intuition</em>.<br>It is optimizing for <strong>how CPUs physically load and execute data</strong>.</p><p>To understand alignment and padding, you have to temporarily stop thinking in terms of “variables at addresses” and start thinking in terms of <strong>how instructions pull data through hardware pipelines</strong>.</p><h3>Memory access is block-based, not byte-based</h3><p>One of the most important things we don’t realize is this:</p><blockquote><strong><em>CPUs do not fetch single bytes from memory.</em></strong></blockquote><p>Modern CPUs move memory in <strong>blocks</strong>.</p><p>On most modern x86–64 systems:</p><ul><li>Cache line size is typically <strong>64 bytes</strong></li><li>When data is not already in cache, the CPU loads <strong>the entire 64-byte cache line</strong></li><li>This applies to <strong>everything</strong>:</li></ul><ol><li>local variables</li><li>global variables</li><li>static data</li><li>struct fields</li><li>array elements</li></ol><p>If your program reads a single char, the CPU still pulls <strong>64 bytes</strong> into cache.</p><p>This immediately reframes performance:</p><blockquote><em>Speed is not about “how many bytes a variable uses”<br>It’s about </em><strong><em>how many cache lines and load operations are required</em></strong></blockquote><h3>Cache makes memory fast ,but not magically flexible</h3><p>At this point, a natural thought arises:</p><blockquote><em>“If the CPU already loads 64 bytes at once, why does alignment still matter?”</em></blockquote><p>This is a critical misconception.</p><p>Cache affects <strong>where data comes from</strong>.<br>Alignment affects <strong>how the CPU loads that data into registers</strong>.</p><p>Even after data is in cache, the CPU still uses <strong>fixed-width load instructions</strong>:</p><ul><li>char → 1 byte load</li><li>short → 2 byte load</li><li>int → 4 byte load</li><li>long / double → 8 byte load</li></ul><p>These load instructions are backed by <strong>dedicated hardware paths</strong>.<br>Those paths are optimized for <strong>aligned addresses</strong>.</p><p>Cache speeds up memory access.<br>Alignment simplifies instruction execution.</p><p>They solve different problems.</p><h3>What alignment actually means</h3><p>Alignment is a rule about <strong>where a value is allowed to begin in memory</strong> so that the CPU can load it efficiently.</p><p>On a typical x86–64 system:</p><ul><li>char → alignment 1 → any address</li><li>short → alignment 2 → even addresses</li><li>int → alignment 4 → multiples of 4</li><li>long / double → alignment 8 → multiples of 8</li></ul><p>These rules are not arbitrary.<br>They are chosen so that <strong>one load instruction can fetch one complete value</strong> without extra work.</p><h3>Why a misaligned is slower</h3><p>Let’s make this tangible.</p><p>Consider memory addresses:</p><pre>0 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 15</pre><p>An aligned int at address 4:</p><ul><li>Uses bytes 4–7</li><li>Loaded with <strong>one aligned 32-bit load</strong></li><li>One instruction, clean execution</li></ul><p>Now an int at address 3:</p><ul><li>Uses bytes 3–6</li><li>Crosses internal alignment boundaries</li><li>CPU must:</li></ul><ol><li>load more data than necessary</li><li>shift bits</li><li>mask unwanted bytes</li><li>merge results</li></ol><p>On x86, this is allowed ,but slower.<br>On many RISC architectures, this would <strong>trap and crash</strong>.Alignment exists to guarantee:</p><blockquote><strong><em>One instruction = one value</em></strong></blockquote><h3>Misalignment: allowed, expensive, or illegal</h3><p>Different CPUs handle misalignment differently:</p><ul><li><strong>x86</strong>: allows it, but adds extra cycles</li><li><strong>ARM / RISC-V / MIPS</strong>: may trap</li><li><strong>Kernel and embedded code</strong>: often assumes alignment is correct</li></ul><p>Because compilers must generate <strong>portable and predictable code</strong>, they always assume:</p><ul><li>Misalignment is unacceptable</li><li>Padding must be inserted</li><li>Alignment must be preserved everywhere</li></ul><p>This is not conservatism ,it’s correctness.</p><h3>Padding: the cost you see vs the cost you avoid</h3><p>Example:</p><pre>struct A {<br>    char c;<br>    long x;<br>};</pre><p>Layout:</p><ul><li>c at offset 0</li><li>7 bytes of padding</li><li>x at offset 8</li></ul><p>Why not place x at offset 1?</p><p>Because that would force <strong>every access to </strong><strong>x</strong> to use a slower load path or be illegal on some CPUs.</p><p>Padding trades a few bytes of memory,</p><ul><li>for simpler instructions</li><li>fewer micro-ops</li><li>better portability</li><li>better performance</li></ul><p>The compiler chooses execution speed over memory tightness.</p><h3>Globals follow the same alignment rules</h3><p>This behavior is not limited to structs.</p><p>Globals:</p><pre>char g1;<br>int  g2;</pre><p>You don’t control their addresses.</p><p>The compiler and linker:</p><ul><li>choose placement</li><li>insert padding</li><li>align variables correctly</li></ul><p>Even when you don’t see it, alignment rules are being enforced globally.</p><p>Memory layout is <em>always</em> shaped around CPU load requirements.</p><h3>Why structs are padded at the end</h3><p>This is where many people get confused.</p><p>Consider:</p><pre>struct B {<br>    char   a;<br>    double b;<br>    int    e;<br>    short  c;<br>    char   d;<br>};</pre><p>Offsets:</p><ul><li>a → 0</li><li>padding → 1–7</li><li>b → 8–15</li><li>e → 16–19</li><li>c → 20–21</li><li>d → 22</li></ul><p>The struct now ends at byte 23.</p><p>Largest alignment requirement is 8.</p><p>So the compiler pads the struct to <strong>24 bytes</strong>.</p><p><strong>Why?</strong></p><p>Because arrays exist.</p><pre>struct B arr[10];</pre><p>If the struct were 23 bytes:</p><ul><li>arr[1] would start at 23</li><li>b would be misaligned</li><li>Every access would be slower or invalid</li></ul><p><strong>By padding the end:</strong></p><ul><li>every struct instance starts aligned</li><li>every field stays aligned</li><li>arrays remain safe and fast</li></ul><p>End padding is not optional,it’s structural.</p><p>the next step is to <strong>see how this affects cache lines</strong>, which is another layer of optimization beyond alignment</p><h3>cache line optimization</h3><p>Up to this point, alignment has mostly been about <em>correctness</em>: making sure every field in a struct starts at an address the CPU is happy with. That’s where padding between fields and at the end of structs comes from. But once alignment is satisfied, there is another, deeper layer of reality that starts to matter “<strong>cache lines”</strong>.</p><p>CPU does not really “see” individual structs or variables when accessing memory. From the cache’s perspective, memory is chopped into fixed 64-byte chunks, and everything inside those chunks is fetched together, whether you use it or not.</p><p>Now consider an array of structs where each struct is <strong>24 bytes</strong>:</p><pre>Struct 0 → 0–23<br>Struct 1 → 24–47<br>Struct 2 → 48–71</pre><p>The first cache line (0–63) holds Struct 0, Struct 1, and <strong>part of Struct 2</strong>. Accessing Struct 2 therefore spills into the next cache line, forcing the CPU to load <strong>two cache lines instead of one</strong>. This is correct but slower.</p><p>Field alignment ensures values are readable efficiently.<br>Cache-line alignment determines <strong>how many cache fills are needed</strong>.</p><h3>Why Kernels Pad Structs</h3><p>In hot paths, kernels often pad structs so each one fits entirely inside a cache line. Padding a 24-byte struct to <strong>32 bytes</strong> means exactly two structs fit in one 64-byte cache line, and no struct ever crosses a boundary.</p><p>This wastes memory on purpose to guarantee <strong>predictable, single-fetch access</strong>.</p><p>Alignment is about correctness.<br>Cache-line padding is about speed.</p><h3>Cache lines and alignment reinforce each other</h3><p>Now everything connects.</p><ul><li>Cache loads happen in <strong>64-byte blocks</strong></li><li>Load instructions still require <strong>aligned addresses</strong></li><li>Alignment ensures fields don’t straddle cache lines unnecessarily</li><li>Padding prevents extra loads and instruction splitting</li></ul><p>Even with cache hits, misalignment still costs CPU work.</p><p>Cache makes memory fast.<br>Alignment makes instructions simple.</p><p>Both are required.</p><h3>Structs are you designing CPU-friendly data types</h3><p>This is the mindset shift.</p><p>A struct is not just grouped variables.</p><p>It is:</p><blockquote><strong><em>A new data type whose layout must obey the CPU’s execution rules</em></strong></blockquote><p>Field order determines:</p><ul><li>number of load instructions</li><li>instruction complexity</li><li>cache behavior</li><li>portability</li></ul><p>This is why kernel structs often look padded and “ugly”.</p><p>They are optimized for <strong>execution</strong>, not appearance.</p><h3>What alignment really is</h3><p>At some point you realize the problem was never “padding” or “structs” or even C.</p><p>The problem was the mental model.</p><p>Alignment isn’t wasted memory.<br>It isn’t compiler weirdness.<br>And it definitely isn’t an arbitrary rule someone invented to make your life harder.</p><blockquote>Alignment is simply the shape data has to take so real hardware can move it efficiently.</blockquote><p>That’s all.</p><p>Padding isn’t bloat. It isn’t sloppy. It isn’t the compiler being lazy. Padding is the space the compiler intentionally leaves so the CPU can take the fast path every single time. It’s permission for the hardware to use its wide load units, its clean fetch patterns, its predictable pipelines instead of falling back to slow, fragmented, byte by byte recovery work.</p><p>Once that idea lands, a lot of long-standing confusion just dissolves.</p><p>sizeof stops feeling like a lie.<br>Struct field order stops looking cosmetic.<br>Cache behavior stops feeling like black magic.</p><p>You stop seeing memory as “a bag of bytes” and start seeing it as something with shape, rhythm, and constraints. You begin to notice that performance isn’t about clever tricks or saving a few bytes here and there instead it’s about giving the CPU data in a form it can consume without friction.</p><p>And that’s the real shift.</p><p>You stop fighting the compiler.<br>You stop assuming it’s wasting space.<br>You stop trying to outsmart rules that come from physics and silicon.</p><p>Instead, you start doing what low-level programming is actually about:<br>designing data that flows naturally through the machine.</p><p>At that point, alignment isn’t a rule anymore.</p><p>It’s just how things work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fbd44f3c83e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filters in Jakarta EE: The Real Street-Level Shit]]></title>
            <link>https://medium.com/@bhushithahashan/filters-in-jakarta-ee-the-real-street-level-shit-2216b071a1bf?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2216b071a1bf</guid>
            <category><![CDATA[jakarta]]></category>
            <category><![CDATA[jakarta-ee]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-filtering]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 18:14:00 GMT</pubDate>
            <atom:updated>2025-08-29T18:14:00.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*5oIZByjyWATyAJ68" /><figcaption>source:<a href="https://www.linkedin.com/learning/jakarta-ee-servlets/filters">https://www.linkedin.com/learning/jakarta-ee-servlets/filters</a></figcaption></figure><p>Yo, when I first started banging out Jakarta EE web apps, my shit was basic AF. Login here, register there, slap a session on the user, boom ! they’re “logged in.” That was it. I didn’t even know the filtering game existed back then. But I knew this: I was generating a session, that session got <strong>stored somewhere</strong>, and I could toss attributes on it. Every request from that user? Tagged. Identifiable. My tiny brain was like, “Damn, this session shit’s doing <em>something important</em>.”</p><h3>First Taste of Real Filtering</h3><p>I mean, sure, I had no clue what filtering really meant, but I could see the hints. I peeked at other people’s JSPs, and holy crap, some folks were doing slick moves, way cleaner than my “just post a welcome message with the username” hack. I saw the classic pattern: grab the session, check if it’s null, if yes → kick that sucker back to login, <strong>no session? No welcome mat.</strong> If you <strong>got a session? Step right in, homeboy.</strong></p><p>I was like, “Damn, that’s actually smart. I can do that too.”</p><p>Later, while diving deeper into projects like a curious little code rat, I stumbled on a whole package called filters. Inside? Folks implementing the Filter interface like wizards. And there it was <strong>the same session check I had in my hacky JSP</strong>, but now: clean, structured, reusable. Mind blown. That’s when I realized the real <strong>power of filters</strong> in Jakarta EE. They’re not just fancy code; they’re a way to take control, cut boilerplate, and make your app smarter without repeating yourself like a moron.</p><p>So Even though it’s been a while, I figured, why the hell not write something about filtering in Jakarta EE? I’m not talking about CORS, CSRF, or all that enterprise noise they’re a whole topic on their own but at the end of the day still are <strong>filters</strong>. Herer we talking about is <strong>raw, simple filtering</strong>. Just a clean <strong>auth filter</strong> example to get the point across.</p><h3>Container Breakdown: From Raw TCP to Servlet</h3><p>Now Enough bullshit. Let’s get into the “WTF is filtering?”</p><p>You know when you’re running your Jakarta web app in a container, let’s say Tomcat; the TCP layer, the socket, just feeds raw data into your container. How the hell do you turn that raw mess into something meaningful? That’s on the application layer — in other words your <strong>Tomcat container.</strong></p><p>Tomcat parses the incoming HTTP packets using its HTTP parser, chewing through that raw TCP garbage like a boss, figuring out the request URI so it knows which app gets the goods. Then it wraps all that real HTTP chaos inside an HttpServletRequest object ,and yes this baby is loaded with built-in methods so you can grab headers, parameters, cookies, session data, or even modify content on the fly without touching a single raw byte.</p><p>At the same time, Tomcat spins up a corresponding HttpServletResponse that wraps the response. This isn’t just some placeholder; it’s a full blown, buffered shell, collecting headers and body until it’s ready to flush that sh*t back down the TCP socket to the client.</p><p>Next, the container peeks into its <strong>servlet mapper</strong>, which is basically a per-app map of URL patterns to servlet instances. It figures out which servlet owns this request’s URI and HTTP method, then calls the servlet’s service() method. That’s the classic &quot;here’s your request, do your thing&quot; move.</p><h3>Enter the Filter</h3><p>But hold up,where the hell does the filter even fit in this whole damn circus? Chill, no need to panic. Just ride with me, keep your seatbelt on, and I promise by the end this sh*t will click harder than your first “hello world” actually working.</p><p>Before we jam the filter into the servlet map and let it start bossing requests around, let’s peek at a simple filter interface implementation for authentication and see what’s really going on under the hood:</p><pre>@WebFilter(&quot;/LandingPage&quot;)<br>public class AuthFilter implements Filter {<br>  @Override<br>  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)<br>    throws IOException, ServletException {<br>    HttpServletRequest req = (HttpServletRequest) request;<br>    HttpServletResponse res = (HttpServletResponse) response;<br>    HttpSession session = req.getSession(false);<br>    if (session == null || session.getAttribute(&quot;username&quot;) == null) {<br>      res.sendRedirect(req.getContextPath() + &quot;/login.jsp&quot;); // stop here<br>    } else {<br>      chain.doFilter(request, response); // continue to servlet<br>    }<br>  }<br>}</pre><h3>Breaking Down the Filter Code</h3><p>First, let’s roll through this simple auth filter and really dig into it. Go through it with me, line by line, and even without me spoon-feeding it, you’ll start to feel where the hell this filter fits in on the request’s messy journey through Tomcat.</p><p>Here, we’re slapping this auth filter on a landing page, and the first thing you gotta notice is how doFilter rocks ServletRequest instead of HttpServletRequest. Think of ServletRequest as the OG parent of HttpServletRequest the universal wrapper that doesn’t give a damn what protocol you’re throwing at it.</p><p>For now, ignore that FilterChain shit... we’ll deal with that beast later. Focus on the filter itself first; trust me, you’ll see how it all clicks once you get this part down.</p><h3>Why ServletRequest Instead of HttpServletRequest?</h3><p>Now why the hell do we use ServletRequest instead of HttpServletRequest or HttpServletResponse?</p><p>It’s because Tomcat ain’t just a one-trick pony serving HTTP. The container could theoretically handle FTP, WebSockets, or some other freaky protocol. That’s why the filter interface rocks the generic ServletRequest .it’s protocol-agnostic, flexible, and ready to handle whatever sh*t you throw at it.</p><p>Here, we cast to HttpServletRequest because we know we’re deep in HTTP territory. If this were some other protocol — FTP, WebSockets or whatever we’d have to cast to the appropriate request type for that shit.</p><h3>The Double Wrap Game</h3><p>Basically, you’re unwrapping the container’s generic wrapper so you can talk to the request in the right language without breaking anything. We already know the raw request is packed inside HttpServletRequest, but the filter still spits in the generic ServletRequest language. So what do we get? Haha, a double wrap, man.</p><p>Now we gotta unwrap that crap to grab our same old familiar HTTP goodies the headers, parameters, session info and what not by using methods like getHeader(), getParameter(), and getSession() without wrecking the container’s flow.</p><h3>The Session Check</h3><p>Now as in the code snippet, once we’re done with the casting and got that familiar HttpServletRequest wrapper that helps us slice and dice HTTP, we can start checking the session.</p><p>If the session’s busted or invalid, we slam a redirect and bail. If it’s good, we call chain.doFilter(req, res).</p><p>yo!</p><p>Hold up, suddenly another doFilter kicks in. WTF, right?</p><h3>FilterChain Exposed</h3><p>Alright, let’s backtrack a bit and break down what we glossed over earlier: what the hell is this FilterChain and that doFilter dance?</p><p>Don’t worry, we’ll make it crystal. As before, lemme drop some simple pseudo-code that imitates the real FilterChain class. Trust me, once you see it laid out, it’s gonna click hard.</p><pre>class FilterChain {<br>  private List&lt;Filter&gt; filters; // [AuthFilter, LoggingFilter, etc.]<br>  private int currentPosition = 0;<br>  private Servlet targetServlet;<br>  public void doFilter(ServletRequest req, ServletResponse res)<br>      throws IOException, ServletException {<br>    if (currentPosition &lt; filters.size()) {<br>      Filter nextFilter = filters.get(currentPosition++);<br>      nextFilter.doFilter(req, res, this);<br>    } else {<br>      targetServlet.service(req, res); // finally run servlet<br>    }<br>  }<br>}</pre><h3>Relay Race of Filters</h3><p>When we call doFilter inside the chain, we’re just running one damn filter we just implement here.</p><p>So yeah, your confusion is fair, man I get it. You’re thinking, “Wait, we just added one filter, and inside that filter we’re calling another? Where the hell is that coming from?” Chill, lemme break it down.</p><p>First off, in this example we’re just doing a simple filter, purely to explain the mechanics. But in real-world apps, you got a whole damn army like Auth, Logging, CORS, CSRF, you name it. We need a way to run one filter after another, and only after everything passes does it finally hit the servlet.</p><p>And do not forget that like with servlets, we never call this filter manually it’s all IoC magic, handled by the container. Just like sessions are stored in a map and servlets are mapped per URL, Tomcat keeps a <strong>filter mapping table</strong>.</p><p>This FilterChain object holds a reference to that mapping. The container doesn’t give a flying damn about our filter implementation. It just builds a FilterChain, stuffs the mapping table inside, and calls doFilter. Every time doFilter gets called, it moves the chain forward to the next filter.</p><p>And finally, by the time all filters are through, we are calling the servlet.</p><h3>Why We Pass the Same req and res</h3><p>And yeah That’s why we pass the already-casted req and res objects along. As by the time the servlet actually runs, it’s working with the proper HTTP-wrapped objects (HttpServletRequest and HttpServletResponse). Every filter gets a shot at inspecting or modifying them before the servlet sees a damn thing.</p><p>This is the beauty: the container’s running the show, the filters are just players, and doFilter is the baton passed down the chain, one bad-ass step at a time.</p><h3>Where Do Filters Fit?</h3><p>Finally, answering the question we skipped earlier: where does the filter fit in the map? Always <strong>before passing the request and response to the servlet</strong>.</p><ul><li><strong>Filters get their chance first, decide what to do (block, modify, redirect, log, etc.), and only then does the servlet execute if all filters pass.</strong></li></ul><p>Think of your Filter implementation (like AuthFilter) as a <strong>soldier</strong> standing in line, but it doesn’t get called directly by the container. The <strong>container</strong> doesn’t care about your individual soldiers ,it only knows about the <strong>filter chain</strong>, the <strong>lineup of all filters</strong> mapped to that URL.</p><h3>The Flow Recap</h3><p>Here’s the <strong>whole damn ride, front to back</strong></p><ol><li>A request hits your servlet via the container.</li><li>Container looks at the <strong>URL</strong> and checks the <strong>filter mapping table</strong>.</li><li>It creates a <strong>FilterChain</strong> object for that request — basically a queue with all filters mapped to that URL + the target servlet at the end.</li><li><strong>Container calls the first filter</strong> by invoking doFilter() on the first one.</li><li>Inside that filter, if you call chain.doFilter(req, res), it <strong>automatically moves to the next filter</strong> in the chain.</li><li>Finally, once the chain has exhausted all filters, the <strong>target servlet’s </strong><strong>service() method</strong> is called.</li></ol><p>So yes <strong>container triggers only the first filter by calling the chain’s </strong><strong>doFilter() once. Just once.</strong> That’s it. The container doesn’t care about your AuthFilter, your LoggingFilter, or your buddy’s WeirdCustomFilter. It only talks to the chain. After that, the <strong>chain takes over</strong>, hopping from filter to filter until the servlet.</p><p>Your individual filters <strong>never call each other directly</strong> they just call chain.doFilter() and the chain handles the rest.</p><p>It’s like a relay race: container hands the baton to the first runner, and the baton keeps getting passed down the line until it reaches the finish line (your servlet).</p><p>So yeah, that’s the gospel of Jakarta EE filters. They’re not magic, they’re not black boxes, they’re just a badass checkpoint system standing between the raw-ass socket chaos and your pretty servlet code. Every request is a journey;</p><blockquote><strong>raw TCP → HTTP parse → request/response wrappers → filters squad → servlet → response flush.</strong></blockquote><p>Think of filters as your bouncers. Some let you in, some kick you out, some just pat you down and log your ID, but all of them stand before the main event. The servlet is the club and you don’t even see the DJ until the filters are done with you.</p><p>So next time you drop a filter in your app, don’t just see it as boilerplate. See it as part of the <strong>street-level defense and polish system</strong> of your web app. It’s the armor, the gatekeepers, the secret sauce that keeps your shit clean and under control.</p><p>End of story. Filters ain’t optional ,they’re the real f*cking deal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2216b071a1bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tech Isn’t the Disruptor ;Business Models Are!!]]></title>
            <link>https://medium.com/@bhushithahashan/tech-isnt-the-disruptor-business-models-are-66f2b0456ba9?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f2b0456ba9</guid>
            <category><![CDATA[disruption]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 05:44:17 GMT</pubDate>
            <atom:updated>2025-08-18T05:44:17.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tech Isn’t the Disruptor ;Business Models Are!!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*mmL4DNDcuuoZYaRn.jpg" /><figcaption>img source:<a href="https://www.theoctopusnews.com/interesting-reasons-small-businesses-fail/">https://www.theoctopusnews.com/interesting-reasons-small-businesses-fail/</a></figcaption></figure><p>Everybody keeps parroting this line: <em>“technology is disrupting everything.”</em><br> Bullshit. Tech doesn’t disrupt a damn thing on its own.</p><p>GPS didn’t walk into a taxi stand and say “yo, you’re done.”<br> The iPhone didn’t knock on Blockbuster’s door and tell them to die.<br> AI isn’t gonna show up tomorrow and fire your whole team.</p><p>Tech is just the hammer. The real disruption? That comes from people who grab the hammer and start building a better business model while everyone else is still debating the blueprint.lemme show you what i mean…</p><h4>Uber vs. Taxis</h4><p>Uber didn’t invent GPS. Or smartphones. Or online payments.<br> Taxis had access to the same exact stuff.<br> But taxis were stuck in their ancient rent-seeking bullshit. So Uber stitched the existing tech together with a better model: tap a button, car shows up, no cash, no arguments. Boom. Overnight taxis went from “default” to “why the hell would I ever call one again?”</p><h4>Banks vs. Fintech</h4><p>Banks had online banking. They had apps. They had more money and more tech people than fintechs could dream of.<br> But they buried everything under red tape, old processes, and “this is how we’ve always done it.”<br> Fintechs came in leaner, automated everything with DevOps-style pipelines, obsessed over customer experience, and suddenly millions of people ditched the bank apps that looked like Windows XP.<br> Banks didn’t lose to “new tech.” They lost to better <strong>execution + business model.</strong></p><h4>Netflix vs. Blockbuster</h4><p>Streaming video? Internet pipes? Media servers? All existed.<br> Blockbuster even had the content rights.<br> But their model was built on late fees and physical stores. Netflix came along and said:<br> “Flat subscription. No late fees. Watch whenever the hell you want.”<br> Same tech. Different model. One survived. One is a meme.</p><h4>Airbnb vs. Hotels</h4><p>Hotels had booking sites for years. But Airbnb asked:<br> “What if anyone could be a host, and trust is handled by reviews instead of marble lobbies?”<br> Tech was already there. The magic was the model.</p><h3>The Pattern</h3><p>It repeats over and over.<br> Amazon vs. bookstores. Spotify vs. CDs. Tesla vs. car dealerships. Even in insurance ,digital-first startups are eating 100-year-old giants alive.</p><p>Here’s the uncomfortable truth:<br> <strong>You didn’t get disrupted by technology. You got disrupted because you were too damn slow, too damn comfortable, and too damn blind to change your business model.</strong></p><h3>How Not to Get Killed</h3><p>If you’re building or running a business, tattoo this list somewhere:</p><ol><li><strong>Adopt fast, don’t sit on tech</strong><br> Cloud, AI, automation, DevOps.this isn’t optional “future shit.” It’s baseline. If it’s out there, assume your competitor is already testing it.</li><li><strong>Customer obsession or die</strong><br> Disruptors win because life is easier for the customer. Uber = no haggling. Netflix = no late fees. Amazon = next-day everything. If your customer experience sucks, you’re already bleeding out.</li><li><strong>Automate like crazy</strong><br> Speed is everything. CI/CD, infra-as-code, monitoring are not buzzwords, survival tactics. If you can’t release faster than your competition, you’ll always be chasing.</li><li><strong>Kill your own legacy first</strong><br> Don’t be Blockbuster. If a new model threatens your cash cow, nuke it yourself before someone else does.</li><li><strong>Business model &gt; shiny tech</strong><br> AI, blockchain, cloud.maan cool tools. But ask: <em>what customer problem am I solving differently?</em> If you can’t answer that, no amount of tech will save you.</li></ol><p><strong>Tech doesn’t kill businesses. Shitty business models do.</strong></p><p>Use tech as the weapon, but win the war with smarter models, faster execution, and a relentless focus on customers.</p><p>Because if you don’t? Someone else will grab the same tech, run circles around you, and you’ll be the next cautionary tale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f2b0456ba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Java SE to Java EE: Making Sense of Enterprise Java]]></title>
            <link>https://medium.com/@bhushithahashan/from-java-se-to-java-ee-making-sense-of-enterprise-java-ff557d9b63f5?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff557d9b63f5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jakarta]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[java-ee-basics]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 12:13:23 GMT</pubDate>
            <atom:updated>2025-08-14T12:13:23.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u7IYFaD82l1zy1a-" /><figcaption>img source:<a href="http://www.muylinux.com/">www.muylinux.com</a></figcaption></figure><p>When I was learning java as a language Ihave only had worked with c before.That foundation sure helped me grasp the language and get familiar with it,but more than that Java changed how I think about solving enterprise-level problems ,how to design in modular patterns, and how to stop seeing everything purely from the computer’s perspective and start modeling real world components. It was a door opening moment for me.</p><p>But while I was learning Java, I came across Java EE now, in modern terms, Jakarta EE. Whether you call it Java EE or Jakarta EE, my first reaction was, “What the fuck is this? Isn’t it just Java? Or is it a new language on the JVM separate from Java SE? Why do we even need Java EE when I’m doing fine with Java SE?” I got fed up with all the nuances. Even after a bunch of videos and tutorials, I only half understood what Java EE/Jakarta EE really was.</p><p>I know there are other enterprise options out there like Spring and they’ve changed the direction of Java itself to some extent. So my goal here isn’t to teach you how to build a Java EE application (trust me, you can pick that up in days maybe faster with AI and all the resources out there). My goal is to give you a clear picture of the <strong>whys </strong>and <strong>whats</strong> behind the leap from Java SE to Jakarta EE, and clear out the nuances that tripped me up. So let’s get into it without wasting more time.</p><h3>Why Java EE Was Introduced</h3><p>You already know Java.Heck, you’ve probably built some cool stuff with its core libraries and the magic of the JVM. But wait ….Java isn’t just <em>one</em> thing. It’s the language, the core libraries, and the JVM. Three separate components, but together they form what’s called <strong>Java SE</strong>.</p><p>So what the hell is <strong>Java EE</strong> then? To really get that, we’ve gotta rewind back to the late 1990s. The internet was exploding, businesses were rushing online, and the way applications were being built started shifting fast. The companies and developers using Java at the time weren’t satisfied with just Java SE. They wanted to use Java for big stuff.Banking systems, online shopping platforms, airline booking systems, corporate portals, you name it.</p><p>But here’s the kicker: to pull that off, systems needed way more than just loops and classes. They needed <strong>web access, database access, transaction management, security, scalability</strong>,<strong> and the ability to talk to other systems — system-to-system communication</strong>. And when devs tried to build all this with plain old Java SE, things got ugly real quick.</p><p>Like… have you ever tried managing raw TCP sockets just to handle an HTTP request in Java? Yeah, sounds like a fucking nightmare, right? You’re probably frustrated just thinking about it. <em>Been there, done that.</em></p><p>And it wasn’t just technical pain. Times were changing ,projects weren’t one lone dev hacking away anymore. These apps were massive, with teams of devs working together. But here’s the problem.In Java SE, there was <em>never just one way</em> to do something. Everyone coded shit their own way. No standards. So if you switched companies or even just had to read a teammate’s code man you’d waste days or weeks just figuring out what the hell they were doing. That was a huge cost for companies (money down the drain) and a massive headache for devs (stress, frustration, and time wasted).</p><p>And don’t even get me started on JDBC. Writing mountains of boilerplate transaction code line after line of crap you <em>know</em> is repetitive and boring, but you still had to type it out because, well, there was no other way. Absolute pain in the ass.</p><p>So yeah with all those headaches, lack of standards, and growing complexity, it became painfully obvious that Java needed something bigger ,something to tackle these enterprise-level problems head-on. That’s where Java EE came into the picture.</p><h3>What is Java EE/Jakarta EE</h3><p>Alright, so we’ve ranted enough about how Java SE alone made enterprise devs want to flip their desks. Now let’s talk about <strong>Jakarta EE</strong> ,the thing that swooped in to fix those headaches.</p><p>First off, Jakarta EE is <strong>not a new language</strong>. It’s not some weird cousin of Java SE. It’s basically a <strong>set of specifications</strong> a standard rulebook that says</p><blockquote>“Hey devs, here’s the official way to build enterprise apps in Java so you don’t spend 80% of your life reinventing sockets, transactions, and security.”</blockquote><p>Now, focus on those key points <strong>the official way of building</strong> and <strong>reinventing sockets, transactions, etc.</strong> It’s kinda like when networking protocols were introduced back in the day. Before protocols, every vendor had their own way of doing things, their own set of rules. So companies or users were stuck: either commit to that one vendor forever, or throw everything away and start fresh with a new one.</p><p>Sound familiar? That’s exactly like the mess we just described earlier innit?no standards, impossible collaboration, companies chained to specific devs, and devs chained to specific products they happened to know.</p><p>But then protocols came along in networking. Everyone agreed on a common set of standards. Suddenly, systems could talk to each other, and boom the internet took off at rocket speed. You really think the internet would’ve grown this insanely fast without common protocols? Hell no.</p><p>That’s exactly what happened with enterprise systems once <strong>Java EE (now Jakarta EE)</strong> showed up. It gave everyone a standard playbook. Now, even though each business’s logic is unique, the <strong>general structure of an enterprise app is shared</strong>. Devs can move between projects and companies without losing their minds, and teams can actually collaborate without spending months deciphering each other’s spaghetti.</p><p>And it’s not just rules on paper Jakarta EE brought APIs too.</p><p>So those raw sockets? Get the fuck outta here.</p><p>Buffers and manually reorganizing HTTP requests? Nope.</p><p>Jakarta EE’s like,</p><blockquote><em>“Here’s the request body. What do you wanna do with it?”</em></blockquote><p>Transactions? Easy peasy.<br> JDBC boilerplate? Pretty much gone.</p><p>Think of <strong>Jakarta EE as Java SE plus a bunch of enterprise-grade features glued on top</strong>. Here’s what that looks like in real life…</p><h4>1. Web Stuff: Servlets &amp; JSP</h4><p>Back in Java SE land, if you wanted to build a web app, you had to manually deal with sockets, HTTP headers, sessions, cookies yeah right ,absolute madness.</p><p>Jakarta EE said, <em>“Screw that. Here’s Servlets.”</em> Now instead of wrangling raw TCP sockets, you just write,</p><pre>@WebServlet(&quot;/hello&quot;)<br>public class HelloServlet extends HttpServlet {<br>    protected void doGet(HttpServletRequest req, HttpServletResponse res) <br>            throws IOException {<br>        res.getWriter().println(&quot;Hello, World!&quot;);<br>    }<br>}</pre><p>Boom. The server (Tomcat, WildFly, GlassFish, etc.) handles all the messy socket crap for you. You just focus on your app logic. Later, JSP and JSF made it even easier to mix Java with HTML for building dynamic web pages.</p><h4>2. Database Hell → JPA (Java Persistence API)</h4><p>Remember JDBC? Writing 200 lines of code to just insert a record? Yeah, Jakarta EE fixed that with JPA.</p><p>Instead of this:</p><pre>Connection con = DriverManager.getConnection(...);<br>PreparedStatement ps = con.prepareStatement(&quot;INSERT INTO users ...&quot;);<br>ps.setString(1, &quot;John&quot;);<br>ps.executeUpdate();</pre><p>Now you just do:</p><pre>User user = new User(&quot;John&quot;);<br>entityManager.persist(user);</pre><p>Done. No more endless boilerplate. You think in terms of <strong>objects</strong>, not raw SQL statements.</p><h4>3. Transactions: JTA (Java Transaction API)</h4><p>Imagine you’re building an <strong>online shopping site</strong>. A customer places an order, you need to:</p><ol><li>Deduct money from their account.</li><li>Reduce inventory stock.</li><li>Confirm the order.</li></ol><p>If step 2 fails, step 1 better roll back, or you’ve just stolen money from a customer. In JDBC, you’d be juggling try/catch/finally with endless commit/rollback logic.</p><p>With JTA in Jakarta EE, you can just annotate:</p><pre>@Transactional<br>public void placeOrder(Order order) {<br>    paymentService.charge(order);<br>    inventoryService.reserve(order);<br>    orderRepository.save(order);<br>}</pre><p>If one step fails, <strong>everything rolls back automatically</strong>. Cleaner. Safer. Saner.</p><h4>4. Scalability &amp; Business Logic: EJB</h4><p>Enterprise JavaBeans (EJB) get a lot of hate, but back in the day they solved <em>huge</em> problems: distributed systems, security, transactions, and scalability.</p><p>Example: you want to build a <strong>banking system</strong> where thousands of transactions hit your servers at the same time. With EJBs, you didn’t have to reinvent concurrency control or clustering; the container handled it. You just wrote your business logic, and the app server dealt with scaling.</p><h4>5. Messaging: JMS (Java Message Service)</h4><p>Picture an airline booking system. When someone books a flight:</p><ul><li>Payment service has to process the ticket.</li><li>Email service has to send a confirmation.</li><li>Loyalty service has to add points.</li></ul><p>You don’t want one giant monolithic method doing all this at once. Instead, JMS lets you publish a message to a queue (“New booking confirmed”), and each service picks it up asynchronously. Cleaner, faster, and services don’t block each other.</p><h4>6. Security APIs</h4><p>Ever rolled your own login system? It’s usually half-baked and hackable. Jakarta EE standardized authentication and authorization. You can declare roles like @RolesAllowed(&quot;ADMIN&quot;) and the container enforces it for you. No more duct-taping your own security rules.</p><h4>7. Standards = Less WTF Moments</h4><p>And the best part? Because Jakarta EE is a <strong>specification</strong>, different vendors (WildFly, Payara, OpenLiberty, etc.) implement it the <em>same way</em>. That means your code is portable. You’re not locked into one company’s weird hacks. If you switch jobs, you won’t waste 3 weeks figuring out how someone else reinvented session management because everyone’s following the same damn rules.</p><p>Alright, so now you’ve got the picture of Jakarta EE gives you standards, APIs, and a way out of the boilerplate hellhole. You can build a web app, talk to databases, handle transactions, all that good enterprise stuff.</p><p>But at some point you’re probably sitting there thinking:</p><blockquote><em>“Yeah, cool… I got the application setup, I got my Servlets and beans… but wait a second </em><strong><em>where the fuck is my </em></strong><strong><em>main() method?</em></strong><em> Who’s actually gonna run all this code?”</em></blockquote><p>Exactly. That’s the moment every dev stares at their Jakarta EE project like: <em>“Bruh… did I miss a step?”</em></p><p>Well, you didn’t miss anything. That’s just where <strong>Inversion of Control (IoC)</strong> kicks in.</p><h3>IoC :Who the Hell Runs My Code?</h3><p>Alright, so in plain old <strong>Java SE</strong> life is simple. You’ve got your cute little main() method, you fire it up, and boom <strong>you’re the boss</strong>. You decide what runs first, you glue shit together, and if something blows up… well congrats, it’s your dumpster fire.</p><pre>public class App {<br>    public static void main(String[] args) {<br>        UserService service = new UserService();<br>        service.sayHello();<br>    }<br>}</pre><p>Clean. Straightforward. <strong>You’re God here.</strong></p><p>But then you move to <strong>Jakarta EE</strong> (or even Spring) and suddenly… <em>“Wait, where the fuck is my </em><em>main()? Who’s pushing the button? Who’s starting this party?”</em></p><p>You don’t write one. Instead, you just throw some random-looking annotations on classes like:</p><pre>@WebServlet(&quot;/hello&quot;)<br>public class HelloServlet extends HttpServlet {<br>    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {<br>        res.getWriter().println(&quot;Hello, World!&quot;);<br>    }<br>}</pre><p>Notice something missing? Yep no main(). No “Hey Java, please run this class.”<br> So how the hell does this even work? Enter the <strong>application server</strong>, aka the grown-ass adult in the room.</p><p><strong>WildFly, Tomcat, Payara, GlassFish</strong> ,these beasts are <strong>containers</strong>. They already have their own big-ass bootstrap process (their own hidden main() buried deep in the belly of the beast).</p><p>Here’s the magic:</p><ul><li>When the server boots, it scans your code like some nosy landlord going through your drawers.</li><li>Sees @WebServlet(&quot;/hello&quot;) → <em>“Ah, nice. This guy wants to handle </em><em>/hello. I’ll hook him into my HTTP pipeline.”</em></li><li>Sees an EJB → <em>“Okay, banker boy wants transactions and scalability, I gotchu.”</em></li><li>Sees @Path(&quot;/api&quot;) → <em>“Cool, REST endpoint incoming.”</em></li><li>JMS listeners, CDI beans… same deal.</li></ul><p>You don’t tell it what to do anymore. You just <strong>declare</strong> shit, and the container goes like,</p><blockquote><em>“Don’t worry kid, I’ll take it from here.”</em></blockquote><p>And that’s the whole point of <strong>Inversion of Control (IoC):</strong></p><ul><li><strong>Java SE</strong> → You call the framework. (You’re the boss, but you’re also the janitor, the cashier, and the cook.)</li><li><strong>Jakarta EE</strong> → The framework calls <em>you</em>. (You’re just chilling while the container does the heavy lifting.)</li></ul><h4>Real-World Analogy</h4><ul><li><strong>Java SE</strong> → Cooking at home. You buy the groceries, chop the onions, cry about it, cook, eat, and then cry again while washing dishes.</li><li><strong>Jakarta EE</strong> → Walking into a restaurant kitchen like Gordon Ramsay. You scream, <em>“I want pasta!”</em> and the kitchen staff (the container) handles all the grunt work. You just slap your recipe (business logic) down and look important.</li></ul><p>So yeah, these servers (WildFly, Tomcat, Payara, etc.) are like <strong>monster engines</strong> already running their own hidden main(). Your annotated classes are basically <strong>plugins</strong> they snap into the system at runtime.</p><p>That’s <strong>IoC in action</strong> — you stop babysitting every damn detail, and you let the container be the responsible adult.</p><p>And here’s the kicker: the container doesn’t just run your shit, it can also <strong>wire your shit together automatically</strong>. That’s the other half of the magic <strong>Dependency Injection.</strong></p><h3>Dependency Injection</h3><p>So now you get it <strong>the container runs your code, not you.</strong><br> You’re no longer writing a main(), you’re just writing “hey, this is what I want to happen when X goes down” and the container’s like <em>“say less, fam.”</em></p><p>But hold up… you’re probably thinking:</p><blockquote><em>“Cool, the container runs my shit. But wait… who the hell gives me the objects I need? Am I supposed to </em><em>new up everything as before?And how?where?”</em></blockquote><p>Exactly. You don’t want to spend your life sprinkling new everywhere like salt on cheap fries. That’s messy, that’s fragile, and when your app scales, it turns into dependency spaghetti.</p><p>This is where the second half of the magic comes in: <strong>Dependency Injection (DI)</strong>, powered by CDI in Jakarta EE.</p><p>Think of it like this:</p><ul><li><strong>In Java SE</strong> → you’re the one wiring objects together right,</li></ul><pre><br>UserRepository repo = new UserRepository();<br>UserService service = new UserService(repo);</pre><ul><li>You’re the electrician here, connecting all the wires by hand. One wrong move, and boom!!lights out.</li><li><strong>But In Jakarta EE</strong> → you just say:</li></ul><pre>@Inject<br>UserService service;</pre><ul><li>And the container’s like: <em>“No worries, bro, I’ll figure out which </em><em>UserService you meant, build it, wire in its dependencies, and drop it on your lap ready to go.”</em></li></ul><p>You don’t new shit anymore ,you just declare what you need, and boom, it’s delivered fresh, dependency-free, and ready to use.</p><p>So first the container took away your need to babysit the main() method. Now it’s also taking away your need to wire everything together manually. That’s <strong>IoC + DI tag-teaming</strong> to make enterprise development way less of a headache.</p><p>So yeah, <strong>Jakarta EE wasn’t about giving you “new Java.”</strong> It was about giving you a set of <em>official standards and APIs</em> that made building massive, real-world apps actually possible without pulling your hair out.</p><p>It took the wild chaos of Java SE for enterprise work and turned it into a structured, predictable, team-friendly framework.</p><p>Like moving from a messy garage with random tools everywhere… to a workshop where everything’s labeled, standardized, and ready to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff557d9b63f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[✨ Glow-Up Goals: Why Smart Workplaces Know When to Learn & Shift]]></title>
            <link>https://medium.com/@bhushithahashan/glow-up-goals-why-smart-workplaces-know-when-to-learn-shift-f69f6733e464?source=rss-4cb2798e1fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69f6733e464</guid>
            <dc:creator><![CDATA[Bhushitha Hashan]]></dc:creator>
            <pubDate>Sun, 25 May 2025 17:43:27 GMT</pubDate>
            <atom:updated>2025-05-25T17:47:03.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XZvTP9VnoZHmMbekjqv6g.png" /></figure><p>We’re living in the age of constant upgrades. Your phone updates itself in the background. Your playlists are algorithmically curated. Even the way we say “hello” at work has evolved.</p><p>So why should the way organizations work stay stuck in the early 2000s?So it only makes sense that workplaces grow too, right?</p><p>Let’s talk about two powerful forces behind workplaces that actually <em>work</em> for people:<br> <strong>Organizational learning</strong> and <strong>cultural change</strong>.</p><p>They’re not buzzwords. They’re the behind-the-scenes magic that makes a place feel innovative, human, and actually enjoyable.</p><h3>Organizational Learning: The Collective Brain That Levels Up</h3><p>Imagine a team where only one person knows how to do something efficiently. Now imagine that person leaves.</p><p><em>Chaos.</em></p><p>Organizational learning prevents that. It’s the idea that learning shouldn’t sit in silos. When one person figures something out, the team should benefit. When mistakes happen, lessons should be shared — not swept under the rug.</p><p>Think:</p><ul><li>Shared knowledge systems (not just one spreadsheet buried in someone’s desktop)</li><li>Encouraging curiosity and experimentation</li><li>Reflecting on wins <em>and</em> failures</li></ul><p>It’s not about perfection. It’s about progress. If teams grow together, they move faster, adapt better, and waste less time reinventing the wheel.</p><h3>Cultural Change: When the Vibe Evolves with the People</h3><p>Culture is more than office snacks ,fun fridays or bean bags in the breakroom. It’s how people communicate. How decisions are made. Who gets heard — and who doesn’t.</p><p>Cultural change is what happens when organizations realize that the old way isn’t working for everyone. It’s about shifting the vibe to match what people actually need today.</p><p>That might look like:</p><ul><li>Moving from top-down leadership to more collaborative models</li><li>Making space for diverse voices, not just the loudest ones</li><li>Evolving values as the team grows</li></ul><p>The culture of an organization shapes every interaction,how feedback is given, how trust is built, how innovation happens. If the culture’s stuck or stale, so are the people. If it grows, so do they.</p><h3>Why It Matters</h3><p>You don’t need to be employed right now to appreciate this stuff. It’s not just corporate theory. It’s the real-life difference between workplaces that feel draining and those that feel energizing.</p><p>In companies that learn and adapt:</p><ul><li>People feel heard</li><li>Growth is intentional, not accidental</li><li>The work feels aligned with something bigger than just tasks</li></ul><p>If you’ve ever felt the difference between a job that lifts you up and one that grinds you down, you already know how much culture and learning shape everything.</p><h3>The Glow-Up Is Real</h3><p>Smart organizations know that staying static is not a vibe.</p><p>They invest in their people, evolve their mindsets, and treat learning as something ongoing — not just an onboarding phase. That’s where the real glow-up happens.</p><p>Not just better profits.<br> Better humans.<br> Better energy.<br> Better <em>everything</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69f6733e464" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>