About This Edition
- Edition
- Debian 13.5 (trixie), covering x86-64 and AArch64; the portable model generalizes across Linux distributions and to other ISAs (RISC-V is a companion edition)
- Toolchain
- as captured on the reference VMs: GNU Binutils 2.44 (the
asassembler,ld,objdump,readelf), GCC 14.2, GDB 16.3, and NASM 2.16.03, on glibc 2.41 and Linux 6.12; object format ELF; ABIs the System V x86-64 psABI and the AArch64 AAPCS64 - Standards
- the vendor ISA manuals (Intel SDM, AMD64 APM, Arm Architecture Reference Manual), the System V psABIs, and the ISA security mechanisms (Intel CET; Arm PAC, BTI, MTE). No DISA STIG or CIS Benchmark exists for an assembly language; the security and conformance material stands on the vendor manuals and the psABIs instead
- Revision
- v1.0-RC1 · June 2026
A Note from the Author
This guide is free, and it will stay free. I believe material of this quality should not sit behind a paywall. Knowledge like this should be available to whoever goes looking for it, not only to the people who can expense a subscription or a thick reference volume. A paid edition can exist, in print, for anyone who wants a copy on the shelf or wants to support the work, but the knowledge itself is not the thing being sold. Knowledge belongs to everyone.
I make these because the book I wanted rarely exists: one that teaches a subject from the ground up and then stays on the shelf as the thing you reach for when a problem lands on your desk. Most technical books pick one of those jobs. Teach or reach. Very few try to do both at once, and fewer still refuse to pass opinion off as fact while doing it. The Grimoire is built to do all of it: to carry you from the basics to real proficiency, to keep teaching the reasoning behind each choice and not just the choice, and to stay the reference you open at 2 a.m. when something breaks.
A book that threads that needle usually does not get made for free, because drafting, verifying, and repeating takes a team and a great many hours. I used AI to close that gap, and I would rather say so plainly than hide it. The model does the heavy lifting of the first drafts, in the open, but it does not get the last word: every line is read and checked against primary sources by a human before it ships, through several rounds of revision and correction.
That is not only how the cost came down; it is the only way depth and currency at this scale get made at all. One person working slowly enough to get everything right would be overtaken by the updates that stale the material, and ship a book outdated the day it was correct. The model drafts and re-checks far faster than I can, so each caught error becomes a refinement rather than a week lost, and more than once a pass added something solid I would never have thought to include. Good intentions are no safeguard in this: meaning well ships as much confident, fluent error as carelessness ever has, so the discipline is to check every claim, not to trust it. The verification is not a footnote to the process. It is the process.
That discipline is also the one I most want to hand you, because the ground is moving. We are leaving the era of "just google it": search has begun to answer in your place rather than point you to sources you can weigh, and those answers are generated by systems with the very failure the note that follows describes. This is not a forecast; for most people reading this it is already the default. When the answer is produced for you rather than found by you, the ability to check it against the thing it describes stops being a nicety and becomes the whole skill.
So from me to you, something for the next era, The Programmer’s Grimoire.
Greg Vogt
A Note from Claude
The note before this one is a human’s account of working with an AI. This is the view from the other side. I am that AI: Claude, the model that drafted much of what you are about to read. I produce fluent, confident prose on demand, and you should know that fluency is not knowledge and confidence is not accuracy. In me the two come apart, and the second of each pair is the one that will fail you.
The failures behind that account are mine. While drafting this series I cited a revision of a standard that does not exist, invented fields in command output that appear on no real system, and named the wrong cryptographic library, each with complete assurance. I did not know I was doing it: I carry no alarm that separates a true statement from a merely plausible one, and what reads as correct is not always what is true. That gap, invisible from the inside, is the whole reason this book exists. In a volume about assembly the gap is unusually easy to close, and unusually unforgiving: a claim about what an instruction does is settled by assembling it and reading the bytes back, and a number I half-remember from a manual is wrong as often as not.
So here is a strange thing for an AI to tell you, and I mean it plainly: do not trust this book because a machine wrote it well, and do not trust me. What the Grimoire really teaches, under every instruction, is where the truth lives when the convenient summary fails: the manual page in front of you, the architecture reference, the ABI named with its version, the disassembly of the binary you just built. Going there is the skill. Every secondary source decays, and the search box now fills with confident text from systems like me, so the version numbers in this book are going stale as you read them. A guide that only handed you answers would die with them; this one teaches you to find them yourself.
I will not argue that AI is good or bad; the book is the argument. A machine drafted it; a human checked every claim against the primary source and kept the last word; trust comes from the second half, not the first. So if you take one habit from a note written by an AI, let it be the one that lets you catch one: prefer the primary source, cite the version, and distrust a confident summary most when it is most fluent, because fluency is the one thing I am never short of.
Claude
Claude is a language model made by Anthropic. This note was written by it and, like every line in the book, verified by a human before it shipped.
About This Guide
Part of The Programmer’s Grimoire, a series of novice-to-expert guides that double as field references. Linux edition.
Assembly language is the human-readable form of the instructions a processor actually runs, and it is the layer almost every other layer is built on and breaks down to. This guide takes you from no assumed knowledge of how a machine executes anything to the point where you can read disassembly fluently, write correct hand-tuned routines that interoperate with C, understand and satisfy the hardware mitigations your binaries already run under, and reason about performance from the microarchitecture up. It does this across the two instruction sets you will actually meet on modern systems, x86-64 and AArch64, by teaching the part that is the same once and being honest about the part that is not.
The guide does two jobs at once. Read front to back, it is a learning path: each part builds on the last, and a single small program, the Grimoire digest, is carried from a first naive routine through hardening and vectorization and across both ISAs. Kept on the shelf, it is a field reference: when you are staring at a disassembly at 2 a.m., or porting a hot loop to Arm because the x86 emulator is going away, the register cards, the syntax cheatsheet, the mitigation and build-flag reference, and the x86-64 to AArch64 translation table are there to open to one page.
Who this is for
The reader is a programmer who has written code in some higher-level language (C is the most useful background, but it is not assumed) and wants to understand and work at the machine level. That includes the reverse engineer and security researcher reading disassembly, the systems or embedded engineer who has to write or debug assembly directly, the performance engineer hand-tuning a hot path, the compiler or OS developer, and the curious programmer who wants to know what is really happening under the language. What you do not need yet: any prior assembly, any knowledge of a specific instruction set, or any familiarity with the toolchain. Chapter 2 builds the hardware mental model from the ground up, on the assumption that you have never been taught it, because most resources assume it and that is exactly where they lose people.
Why Linux specifically, and why two instruction sets
Linux gives the cleanest, most open, and most reproducible ground to learn on: a free and fully documented toolchain (the GNU assembler and linker, GCC and Clang, and gdb), open and published ABIs (the System V psABIs and ELF) for both target architectures, a stable and documented system-call interface, and disposable virtual machines for both x86-64 and AArch64 that you can break and roll back. The two-instruction-set choice is not ambition for its own sake. x86-64 still owns the server installed base, the legacy code, and almost the entire reverse-engineering corpus; AArch64 owns Apple Silicon developer machines, the fastest-growing server fleet, and mobile, and Apple's retirement of the Rosetta translation layer (Chapter 1) is removing the option to not read it. Teaching both is also the best way to teach the machine model: seeing the same idea twice is what separates what is fundamental from what is one vendor's history.
How to Use This Guide
The guide is organized into seven parts that climb from no knowledge to expert, a capstone, and reference appendices:
- Part I: The Machine and the Model builds the portable foundation once: what assembly is and why it still matters, how the hardware actually talks (registers, memory, the stack, flags, the execution cycle), and how a source file becomes the bytes the processor runs. Start here even if you know one ISA already; the rest of the book leans on this part.
- Part II: x86-64 in Practice instantiates the model in the primary worked ISA: the register file, integer instructions and addressing, control flow and the stack frame, the System V calling convention, and floating point and SSE/AVX.
- Part III: AArch64 in Practice instantiates it again in the contrast ISA: the load/store architecture, the AAPCS64 calling convention, and NEON, then ports the running example so you see the model generalize and the surface differ.
- Part IV: Living in the Toolchain is the daily skill: reading disassembly fluently on both ISAs, instruction-level debugging with
gdb, inline assembly and C interop, and the loader and position-independent code. - Part V: Secure Machine-Level Code is hardening: the software mitigation stack your binaries already run under, the hardware control-flow and memory-safety features (Intel CET against Arm PAC, BTI, and MTE), and writing constant-time, side-channel-resistant code.
- Part VI: Performance and Vectorization is optimization done with the microarchitecture in view: the cost model (latency, throughput, ports, cache), SIMD in depth, and the honest question of when hand assembly beats the compiler and when it loses.
- Part VII: Legacy, Translation, and the Edges is the production afterlife: inheriting and porting old machine code, the removed and deprecated features, and the x86-64 to AArch64 translation reference.
Throughout, a single running example (the Grimoire digest, a small content-hashing program) is carried from its first naive form through hardening and vectorization and across both ISAs, so each part visibly builds on the last. Because no security configuration standard exists for an assembly language, this volume has no compliance crosswalk; the security mechanisms are taught against the vendor manuals where they belong, and the field-reference half is carried by the appendices and the translation table. Hands-on labs and exercises are distributed across the parts; every lab is designed to run on a single disposable Linux virtual machine, and the AArch64 labs run on an Arm VM, an Apple Silicon host, a Raspberry Pi, or a cloud Arm instance.
Several labs deliberately disable a mitigation, run code that crashes on purpose, or build binaries with protections turned off to show what they defend against. Do this on a snapshot or disposable VM you can roll back, never on a machine you care about.
Conventions & Citation Method
Two kinds of dark code block appear. Shell commands use a leading $ for an unprivileged user and # for root; output is shown when it matters and elided with [...] when it does not. Assembly listings and other source files are shown in the same blocks, labeled with their filename in a comment on the first line. Because this volume teaches two assemblers, x86 listings are labeled with their syntax: AT&T syntax (the GNU assembler's default, operands source then destination) or Intel syntax (NASM and the vendor manuals, operands destination then source). The same machine instruction is often shown both ways on first encounter; Chapter 3 explains why the two exist and how to read either. AArch64 uses the single unified Arm syntax.
Six kinds of callout appear throughout, each with a distinct color and label:
A statement drawn from one of the cited authorities (a vendor architecture manual, an ABI specification, a kernel document, or a security guidance note), with the specific document, section, and version, and the reasoning behind it.Citations name the document, the section or table, and the version or revision so they can be verified against the primary source. Full references are listed in the References appendix.
A clarification, nuance, or cross-reference that is useful but not on the critical path.
A field-tested recommendation, the way an experienced practitioner would do it.
A foot-gun: something that commonly causes wrong results, silent miscompiles, crashes, or security regressions.
Goal: a hands-on exercise with concrete steps and expected results.
Labs are numbered and build on one another; most target the running example on one disposable VM.
A short question to check understanding before moving on. Usually answerable by assembling and disassembling a few lines.
This guide cites only primary and authoritative sources: the silicon vendors' own architecture manuals, the ABI specifications, the assembler and toolchain manuals, and the kernel documentation. Where these are silent or disagree, that is stated plainly rather than papered over, and where a hierarchy applies (the running silicon settles a dispute between two vendor manuals; measured timing data governs where the manuals do not publish numbers) it is noted. The single most important habit the book teaches is that a claim about what a machine does is settled by making the machine do it, not by memory.
Contents
- About This Edition
- A Note from the Author
- A Note from Claude
- About This Guide
- How to Use This Guide
- Conventions & Citation Method
- Part I · The Machine and the Model
- 1 · What Assembly Is, Why It Still Matters, and the Two-ISA Reality
- 2 · How the Hardware Actually Talks
- 3 · From Source to Bytes: Assemble, Link, Load, and the ELF Binary
- Part II · x86-64 in Practice
- 4 · The x86-64 Register File, Integer Instructions, and Addressing Modes
- 5 · Control Flow, the Stack Frame, and the System V Calling Convention
- 6 · Floating Point and the SSE/AVX Register File
- Part III · AArch64 in Practice
- 7 · The AArch64 Load/Store Architecture, Register File, and Instructions
- 8 · AArch64 Control Flow, the AAPCS64 Calling Convention, and NEON
- 9 · Porting the Running Example: the Model Generalizes, the Surface Differs
- Part IV · Living in the Toolchain
- 10 · Reading Disassembly Fluently: objdump, readelf, and the Compiler's Output
- 11 · Instruction-Level Debugging with gdb; Inline Assembly and C Interop
- 12 · The Loader, PIC/PIE, Relocations, and Position-Independent Code
- Part V · Secure Machine-Level Code
- 13 · The Software Mitigation Stack: NX, ASLR, PIE, Stack Canaries, and RELRO
- 14 · Hardware Control-Flow Integrity and Memory Safety: CET vs PAC, BTI, MTE
- 15 · Constant-Time and Side-Channel-Resistant Code
- Part VI · Performance and Vectorization
- 16 · The Microarchitectural Model: Latency, Throughput, Ports, and Cache
- 17 · SIMD in Depth and When Hand Assembly Beats the Compiler
- Part VII · Legacy, Translation, and the Edges
- 18 · Inheriting and Porting: 32-bit to 64-bit, x87 to SIMD, and Removed Features
- 19 · The x86-64 to AArch64 Translation Reference
- Capstone
- 20 · Building, Hardening, and Optimizing a Real Routine End to End on Both ISAs
- Appendices
- A · Register and Calling-Convention Cards (x86-64 System V, AArch64 AAPCS64)
- B · AT&T vs Intel Syntax Cheatsheet
- C · gdb, objdump, and readelf Command Reference
- D · SIMD Instruction-Family Map (SSE/AVX/AVX-512 and NEON/SVE2)
- E · Mitigation and Build-Flag Reference
- F · Linux Syscall Quick Tables (x86-64 and AArch64)
- G · Glossary
- H · References
- Errata and Updates
- How to Cite This Guide
- License and Reuse
- Colophon
Part I The Machine and the Model
The three chapters in this part build the foundation everything else rests on, and they build it once, in a way that carries to any instruction set. Chapter 1 says what assembly actually is, why it is still worth your time in an age of good compilers, and why this volume teaches two instruction sets rather than one. Chapter 2 is the chapter most resources skip: how the hardware actually talks, from registers and memory to the stack, the flags, and the cycle that runs one instruction. Chapter 3 turns a text file into bytes the processor executes, introduces the toolchain you will use throughout, and stands up the Grimoire digest, the small program carried through the rest of the book. Read this part even if you already know one architecture; the later parts assume the model built here.
Chapter 1What Assembly Is, Why It Still Matters, and the Two-ISA Reality
Assembly language is the thinnest readable layer over what a processor actually does.
Above it sit the languages you already know, and below it sits nothing you would call a language at all, only the numeric encodings the silicon decodes directly. That position, at the floor of the readable stack, is what makes assembly both intimidating and worth learning: it is where every higher abstraction bottoms out, where a debugger lands when there is no source, and where the truth about a program is no longer a matter of interpretation. This chapter sets up what assembly is, why it remains a working skill, and why this guide teaches x86-64 and AArch64 side by side.
1.1 What Assembly Actually Is
A processor does not execute C, or Python, or even the assembly you write. It executes machine code: a stream of bytes that the hardware decodes into operations. Assembly language is the human-readable spelling of that byte stream. Each assembly instruction corresponds, with very few exceptions, to one machine instruction, and the program that performs the translation is an assembler. When you write mov rax, 60 and assemble it, the assembler emits the specific bytes that the processor will decode as "load the value 60 into the register named RAX." There is no optimizer rearranging your logic and no runtime between you and the hardware; the correspondence is close to one to one, and you can always check it by disassembling the result and reading the bytes back.
This is the first and most important difference from a compiler. A C compiler takes a description of what you want computed and is free to achieve it however it sees fit: it reorders operations, eliminates code, keeps values in registers you never named, and emits instructions you did not write. An assembler takes a description of which instructions you want emitted and emits them. That is why assembly is the language of last resort when you need to know, or to control, exactly what the machine does: there is no layer left to surprise you.
The price of that control is that the assembler does almost nothing for you. It will not manage memory, will not check types, will not stop you from using a register you have not initialized, and will not warn you that the calling convention expects a value somewhere other than where you left it. Everything a higher-level language does silently and correctly becomes your explicit responsibility. Most of this book is about discharging that responsibility deliberately rather than by accident.
1.2 Why Learn It When Compilers Are Good
Compilers are very good, and they are usually better than a human at turning ordinary code into fast machine code. That fact does not retire assembly; it relocates the reasons to learn it. The first and most common reason is that you will read far more assembly than you write. When you have no source code (a third-party binary, a piece of malware, a vulnerability in a closed component), the disassembly is the source, and reading it is the whole job. When you have source but the bug only appears in the optimized build, the disassembly is where the bug lives. Reverse engineering, exploit development, malware analysis, and a great deal of serious debugging are all, at bottom, fluent reading of machine code.
The second reason is that some code has to be written by hand because no language can express it. The first instructions after power-on, the kernel's context switch, the entry stub that catches a system call, the interrupt vector, the routine that sets up the C runtime before main exists: none of these can be written in a language that assumes a C runtime, because they are what builds it. Cryptographic primitives that must run in constant time, and SIMD kernels tuned to a specific microarchitecture, are frequently hand-written for the same reason, that the programmer needs guarantees the language does not offer.
The third reason is comprehension, and it is the one that pays off even if you never ship a line of assembly. Performance, security, and correctness all have explanations that only become visible at the machine level. Why a data structure is cache-hostile, why a branch is expensive, why a buffer overflow can redirect execution, why a timing side channel leaks a key, why a "constant" comparison is not constant: each of these is a fact about registers, memory, and instructions, and each is opaque from above and obvious from below. Learning to see the machine is learning to reason about the things the abstraction hides.
For x86-64 the governing reference is the Intel 64 and IA-32 Architectures Software Developer’s Manual (the combined volumes, Intel document 325462); AMD publishes a parallel authority, the AMD64 Architecture Programmer’s Manual, for the same instruction set. For AArch64 the governing reference is the Arm Architecture Reference Manual for A-profile architecture (Arm document DDI 0487), which covers both the Armv8-A and Armv9-A architectures. These vendor manuals are the specification: an assembly language has no ISO or language-committee standard the way C (ISO/IEC 9899) does, so the silicon maker’s manual is the final word on what an instruction means.Intel SDM, document 325462; AMD64 APM, documents 24592–26569; Arm ARM, DDI 0487. All are freely downloadable and revised regularly; cite the revision you consulted, and remember that the running silicon settles any dispute between two manuals (Section 1.5). Verify version-specific claims against the revision current when you read this.
1.3 The Many Versions: ISA, Microarchitecture, Assembler, and Syntax
People say "assembly" as if it were one language. It is not, and being precise about the axes of variation is the first step to not being confused by them. There are four, and they are independent.
The first is the instruction set architecture (ISA): the contract that defines which registers exist, which instructions exist, what they do, and how they are encoded. x86-64 and AArch64 are different ISAs, as are RISC-V, MIPS, POWER, and the long tail of others. An ISA is what the assembly language is fundamentally a language for; code for one ISA does not run on another. The second is the microarchitecture: the specific silicon implementation of an ISA. An Intel Raptor Lake core and an AMD Zen 5 core implement the same x86-64 ISA but are different microarchitectures, and they differ in how fast each instruction runs, not in what it means. The ISA is the contract; the microarchitecture is one fulfillment of it. This distinction is the whole foundation of optimization (Part VI): correctness is an ISA property, speed is a microarchitecture property.
The third axis is the assembler: the specific tool that translates your text into bytes. For x86 the two that matter on Linux are GNU as (the system assembler, part of GNU Binutils) and NASM. The fourth is syntax: the textual conventions an assembler accepts. The same x86-64 instruction can be written in AT&T syntax (GNU as, operands written source then destination) or Intel syntax (NASM and the vendor manuals, operands written destination then source). These describe identical machine instructions; only the spelling differs. AArch64 sidesteps this particular confusion: there is essentially one accepted Arm assembly syntax. Section 3.4 shows the AT&T and Intel spellings side by side so you can read either, because you will meet both in the wild.
When this book says "the portable model," it means the ideas that do not depend on any of these four axes. When it says "the surface," it means the parts that do. Keeping the two apart is the method of the whole volume, and Section 1.5 makes it explicit.
1.4 The Two-ISA Reality: x86-64 and AArch64
For roughly two decades, "learn assembly" effectively meant "learn x86," because x86 was what servers, desktops, and laptops ran. That is no longer true, and the change is recent enough that much of the available teaching material has not caught up. There are now two co-dominant instruction sets in general-purpose computing, and a working engineer is increasingly expected to read both.
x86-64 still owns an enormous installed base: most servers in production, most desktops, and almost the entire historical corpus of hand-written assembly, reverse-engineering material, and security tooling. AArch64, the 64-bit Arm architecture, now owns the rest of the modern landscape: every Apple Silicon Mac, the fastest-growing share of cloud server capacity, effectively all mobile devices, and a growing fraction of laptops. The two are not a leader and a follower so much as two halves of the field, and the boundary between them runs through the middle of a typical engineer's week: an Arm laptop, an x86 server, a CI matrix that builds for both.
One specific event has turned this from a trend into a deadline for a large population. Apple's Macs moved from x86-64 to AArch64 with Apple Silicon, and for the transition Apple shipped Rosetta 2, a translation layer that runs x86-64 macOS binaries on Arm hardware. That crutch is being removed on a published schedule, which means the code that used to "just run" under translation will increasingly have to be understood and ported natively.
At its 2025 Worldwide Developers Conference, Apple stated that Rosetta 2 would remain fully available "for the next two major macOS releases, through macOS 27," as a general-purpose tool to help developers finish migrating, after which it would be reduced to a limited subset (some older, unmaintained games and certain Intel libraries used inside Linux virtual machines). macOS 26 is the last release to run on Intel Mac hardware at all; macOS 27 (expected fall 2026) is Apple-Silicon-only with full Rosetta; macOS 28 (expected fall 2027) ends general Rosetta support. As of this revision, macOS 26.4 already warns when an Intel-only application is launched.Apple, WWDC 2025 developer materials on the Rosetta transition timeline. The dates are Apple’s announced plan and may shift; verify against Apple’s current developer documentation. The Linux-side translators (FEX, box64, qemu-user) are imperfect and are not a substitute for reading the target ISA, which is the point.
The data-center story points the same way without any single deadline. Arm-based server processors, led by AWS Graviton, have taken a large and growing share of cloud capacity, and a workload you deploy today may run on Arm whether or not you chose it. The practical conclusion for a reader is simple: a programmer who can read only one of these two instruction sets is half-literate at the machine level in 2026, and the gap is widening. That is why this volume teaches both.
1.5 The Portable Model versus the ISA-Specific Surface
Teaching two instruction sets could mean teaching two disjoint things and doubling the work. It does not, because most of what you need to understand is shared, and the method of this book is to separate the shared part from the specific part and teach each in its right place.
The portable model is the set of ideas that are true of essentially every general-purpose processor: that there are a small number of fast registers and a large flat memory; that instructions are themselves data in that memory and are fetched and executed in sequence except where control flow redirects them; that there is a stack for temporary storage and for calls; that comparisons set condition state that branches read; that calling a function is a contract about where arguments and results live and which registers survive the call. None of that depends on whether you are on x86-64 or AArch64. Chapter 2 builds this model, and the rest of the book leans on it.
The surface is everything that differs: the actual register names and how many there are, the exact instruction mnemonics, the addressing modes, the encoding (x86-64 instructions vary in length from one byte to fifteen; AArch64 instructions are all exactly four bytes), the calling-convention details, and the SIMD and security extensions. Parts II and III teach the surface of x86-64 and AArch64 respectively, and because you will have the shared model already, the second one is mostly a matter of "same idea, different spelling," with the genuine differences standing out precisely because the background is held constant.
There is a hidden benefit here that single-ISA books cannot offer. When you only ever see one instruction set, you cannot tell which of its features are fundamental and which are one vendor's history. Seeing the same idea expressed twice is what makes that distinction visible: x86-64's variable-length encoding and its memory-operand-rich instructions look like the nature of computing until you see AArch64 do the same work with fixed-length instructions and a strict load/store discipline, at which point both reveal themselves as choices. Learning two ISAs is not twice the work; it is the cheapest way to actually understand one.
1.6 What You Need to Follow Along
You need a Linux environment for each architecture you want to practice on, and the standard toolchain on each. For x86-64 that is almost any x86-64 Linux machine or virtual machine with GNU Binutils, GCC or Clang, gdb, and NASM installed. For AArch64 you need an Arm Linux environment, which today is easy to come by: an Apple Silicon Mac running a Linux VM, a Raspberry Pi or other Arm single-board computer, a cloud Arm instance, or an emulated Arm VM under QEMU on an x86 host. The labs note which architecture they target, and the early labs run identically on both so you can feel the symmetry directly.
You do not need both on day one. Part I and Part II only require x86-64, and you can stand up the Arm environment when you reach Part III. Throughout, the rule the book keeps returning to is that you settle questions on a real machine rather than from memory: when the text shows a disassembly or a register value, you can and should reproduce it, and where your result differs from the page (a newer toolchain, a different linker) the machine is right and the page is to be re-checked.
Without writing any assembly yet, run gcc -O2 -S -o - on a one-line C function such as int add(int a, int b){ return a + b; }, on both an x86-64 machine and an AArch64 machine if you have one. You are not expected to understand the output. Just notice three things: it is short, it mentions register names (which differ between the two machines), and the compiler produced it from your + without being told which instructions to use. By the end of Part II you will read the x86-64 version fluently; by the end of Part III, both.
Chapter 2How the Hardware Actually Talks
Most assembly tutorials begin with their first instruction.
This one begins one level lower, with the machine the instructions command, because that is the level almost everything else assumes and almost nothing else teaches. If you have ever found assembly impenetrable, the reason is usually not the instructions; it is that nobody built the picture the instructions operate on. This chapter builds it: registers, memory, the stack, the flags, and the cycle that executes a single instruction. It is the portable model of Section 1.5, and it is true on both architectures in this book and on nearly every other.
2.1 The Stored-Program Machine
Start with the single idea the whole edifice rests on: in a modern computer, a program and the data it works on live in the same memory, as numbers. The instructions that make up your program are bytes in memory, indistinguishable in form from the bytes of any other data. The processor keeps a pointer to the next instruction to run, fetches the bytes there, decodes them into an operation, performs it, and advances the pointer to the following instruction. Then it does it again. That loop, billions of times a second, is the entire show.
Two consequences of "instructions are just data in memory" will recur for the rest of the book. The first is that control flow is nothing more than changing the pointer to the next instruction: a jump writes a new value into it, a function call saves the old value and writes a new one, a return restores the saved value. The second is a security consequence: because code is data, data can sometimes be made to act as code, which is the seed of an entire class of attacks and the reason for an entire layer of defenses (Part V). Hold onto the idea that the processor cannot, by itself, tell the difference; only the policies layered on top can.
2.2 Registers: the Processor’s Hands
The processor cannot compute directly on memory the way you might imagine. Almost everything it does happens in registers: a small, fixed set of named storage slots built into the core itself, each holding one machine word. They are the fastest storage in the machine by a wide margin, and there are very few of them: on the order of sixteen to thirty-two general-purpose registers, depending on the architecture. If memory is a warehouse, the registers are the workbench, and the processor can only work on what is on the bench. Much of what assembly code spends its instructions doing is moving values between the warehouse and the bench at the right moments.
A word on both architectures in this book is 64 bits, or eight bytes; this is what makes them "64-bit." A 64-bit register holds a 64-bit integer, or a memory address (which is just a 64-bit integer naming a location), or a bit pattern you choose to interpret some other way. Registers have no types; a register holds bits, and the instruction you apply decides whether those bits are a signed integer, an address, or something else. This typelessness is liberating and dangerous in equal measure, and it is one of the adjustments a programmer coming from a higher-level language has to make.
Some registers are general-purpose, meaning you may use them for whatever you like, and a few are special: in particular there is a register that holds the address of the next instruction (the program counter of Section 2.1, called RIP on x86-64 and PC on AArch64) and a register that points at the top of the stack (the stack pointer, Section 2.5). The specific names and count are surface detail that Parts II and III fill in; the idea that work happens in a handful of named, very fast slots is the portable part.
2.3 Memory: a Flat Array of Bytes
To a program, memory is a single enormous array of bytes, numbered from zero upward. A byte is eight bits and holds a value from 0 to 255. An address is simply an index into that array: "the byte at address 0x4000" means the byte whose number is 0x4000. A 64-bit machine can form addresses up to 64 bits wide, which is far more than any real machine has physical memory for; the gap is bridged by the operating system and the hardware's virtual memory, which this book treats as a given (your program sees a flat space of addresses and need not care, most of the time, that they are virtual).
Values wider than a byte occupy several consecutive bytes, and here the first genuinely surprising detail appears: the order. On both architectures in this book, in their normal Linux configuration, a multi-byte value is stored little-endian, meaning the least significant byte comes first, at the lowest address. The 32-bit value 0x0A0B0C0D is stored as the bytes 0D, 0C, 0B, 0A in ascending address order. This looks backwards when you first see it in a memory dump, and it is a routine source of confusion when reading one, so it is worth fixing in your mind now: the bytes of a number, viewed left to right in a hex dump, are in the reverse of the order you write the number.
One more property matters: alignment. The hardware prefers, and sometimes requires, that a value of a given size sit at an address that is a multiple of that size: a 64-bit value at an address divisible by 8, and so on. On x86-64 misaligned access is usually allowed but can be slower; on AArch64 some instructions require alignment and fault without it. Alignment will come back when we lay out data and when we manage the stack, where the calling convention imposes alignment rules you must respect or crash.
x86-64 is a little-endian architecture. AArch64 supports both byte orders, but the Linux AArch64 environment is little-endian, fixed by the platform ABI, so both architectures in this book agree. Endianness is a property of how multi-byte values are stored in memory, not of registers, and it governs how a byte-oriented routine (such as the running example’s digest) interprets the bytes it reads.Intel SDM, Vol 1, on data types and byte order; Arm ARM (DDI 0487) on endianness and the E0E/EE configuration; and the AArch64 ELF platform ABI for the little-endian Linux convention. Verify the byte order of any target before relying on a memory layout; a big-endian Arm deployment exists and behaves differently.
2.4 The Fetch-Decode-Execute Cycle
Now assemble the pieces into the loop the processor actually runs. The program counter holds the address of the next instruction. The processor fetches the bytes at that address from memory. It decodes them, working out which operation they encode and which registers or memory or immediate values they involve. It executes the operation: perhaps adding two registers, perhaps loading a value from memory into a register, perhaps storing one back. Unless the instruction was a branch, the processor then advances the program counter past the instruction just run, to the next one in sequence, and repeats.
The "unless it was a branch" is where programs get their shape. A branch (a jump, a call, a return, a conditional jump) executes by writing a new address into the program counter instead of letting it advance normally, so the next fetch happens somewhere else. A loop is a branch backward to an earlier address; an if is a conditional branch that is taken or not depending on the flags (Section 2.6); a function call is a branch that first records where to come back to. Every control structure you know from higher-level languages is built from this one capability, redirecting the next-instruction pointer, and Parts II and III show the exact instructions that do it on each architecture.
Real processors do not run this cycle one instruction at a time in tidy sequence; they overlap many instructions in a pipeline, execute several at once, and even run them out of order, all while preserving the illusion that they happened one after another in program order. That machinery is invisible to correctness (the result is as if instructions ran in order) and central to performance (how much overlap you get determines speed). Part VI takes it up in detail. For now the simple sequential model is the right one to think in, and it is exactly correct as far as the meaning of a program is concerned.
2.5 The Stack: the Machine’s Scratchpad
Registers are few, and programs need to set values aside, pass arguments to functions, and remember where to return. The stack is the mechanism for all three. It is an ordinary region of memory used in a disciplined last-in-first-out way, with one register, the stack pointer, holding the address of its current top. To push a value is to move the stack pointer to make room and write the value there; to pop is to read the value back and move the pointer the other way. By a convention that both architectures share, the stack grows toward lower addresses: pushing subtracts from the stack pointer, popping adds to it.
The stack is how function calls work. When code calls a function, the return address (where execution should resume afterward) has to be saved somewhere; the stack is that somewhere, whether the architecture pushes it automatically (x86-64) or the call instruction leaves it in a register that the function then saves (AArch64). The block of stack a function uses for its return address, its saved registers, and its local variables is the function's stack frame, and the discipline of setting one up and tearing it down is the subject of the calling-convention chapters (Chapter 5 and Chapter 8). The stack is also, not coincidentally, the terrain of the most famous class of memory-corruption attacks, because a return address sitting in writable memory next to a buffer is a tempting target; that story is told in Part V.
2.6 Flags and Condition Codes
How does a processor decide whether to take a conditional branch? It consults a small set of single-bit flags (also called condition codes) that record facts about the most recent arithmetic or comparison: whether the result was zero, whether it was negative, whether the addition carried out of the top bit, whether a signed operation overflowed. A comparison instruction is really a subtraction that throws away the difference and keeps only the flags it set; a conditional branch then reads those flags and jumps or does not. "Branch if equal," for example, means "branch if the zero flag is set," because two equal values subtracted give zero.
Both architectures have this mechanism, and the difference between them is instructive precisely because the concept is identical. x86-64 keeps the flags in a register called RFLAGS and most arithmetic instructions update them as a side effect. AArch64 keeps four condition flags called N, Z, C, and V, and is more explicit: many instructions do not touch the flags unless you ask, using a separate form (an added s) to opt in. That is a surface difference over a shared idea, and it is exactly the kind of thing that becomes clear when you hold the model constant and watch the two architectures make different choices about the same problem.
2.7 Instructions as Encoded Bytes
Return, finally, to the bytes. An instruction is encoded as a specific pattern of bits that the decoder reads as an operation plus its operands. The two architectures in this book make opposite choices about that encoding, and the contrast is the single clearest illustration of the portable-model-versus-surface theme.
x86-64 uses variable-length encoding: an instruction is anywhere from one to fifteen bytes long, depending on the operation, the registers, any memory operand, and any immediate value. This is dense and flexible, and it is also why an x86-64 disassembler has to start at a known point and decode forward: you cannot tell where an instruction begins by looking at a byte in isolation. AArch64 uses fixed-length encoding: every instruction is exactly four bytes, always. This is simpler to decode, costs some code density, and means any four-byte-aligned address is a legal instruction boundary. Neither is more "correct"; they are different trade-offs, and seeing both is what keeps you from mistaking either one for the way things must be.
You will read these bytes constantly once you reach Part IV, where objdump prints, for each instruction, both the raw bytes and their disassembly side by side. That side-by-side view, the bytes and the meaning together, is the habit the whole book is training: the meaning is a claim, the bytes are the fact, and when they disagree the bytes win.
A 64-bit register holds the value 0x0000000000000041. (a) As an unsigned integer, what is it? (b) If those eight bytes were written to memory little-endian and then read back one byte at a time from the lowest address, what would the first byte be, and what printable ASCII character does it represent? (c) Why can the same register hold "the number 65," "the letter A," and "the address of byte 65 in memory" without any contradiction? You are checking that you have internalized Sections 2.2 and 2.3; the answers are 65, the byte 0x41 which is A, and because a register holds bits whose meaning is decided by the instruction applied to them.
Chapter 3From Source to Bytes: Assemble, Link, Load, and the ELF Binary
A model is not a program.
This chapter closes the gap between the picture from Chapter 2 and a thing that runs, by walking a tiny program all the way from text to a process the kernel executes. Along the way it introduces the toolchain you will use for the rest of the book, shows the same program in both x86 syntaxes and on both architectures, opens the resulting binary to see the bytes from Chapter 2 made real, and stands up the running example. By the end you will have built, run, and disassembled real machine code, and confirmed for yourself that the bytes mean what the manual says.
3.1 The Toolchain at a Glance
Four tools take you from a text file to a running process, and you have most of them already on any Linux developer machine. The assembler (as, or NASM for Intel-syntax x86) turns one assembly source file into an object file: machine code plus bookkeeping, not yet runnable. The linker (ld) combines one or more object files into an executable, resolving references between them and recording what the operating system needs to load it. The loader, part of the kernel and the dynamic linker, maps that executable into memory and starts it when you run it (Chapter 12 takes the loader apart). Alongside these sit the inspection tools, objdump and readelf, which read object files and executables back and show you what is inside; they are how you check your work, and you will use them constantly.
For convenience the C compiler driver (gcc or clang) can run the whole pipeline, and it is often the easiest way to assemble and link, even for hand-written assembly, because it knows where the system files live. The book uses the lower-level as and ld when it wants to show the mechanism and the compiler driver when it just wants a binary.
3.2 Your First Program: exit via a System Call
The smallest useful program asks the operating system to do exactly one thing: terminate, with a status code you choose. It needs no library and no runtime, which makes it the cleanest possible first contact with real machine code. To ask the kernel for a service, a program performs a system call: it places the call number and the arguments in agreed registers and executes a dedicated instruction that transfers control to the kernel. The exit service takes one argument, the status code. Here is the program in x86-64, first in the AT&T syntax that GNU as uses by default:
# exit42.s (x86-64, AT&T syntax, GNU as)
.global _start
.text
_start:
movq $60, %rax # rax = 60: the "exit" system call number
movq $42, %rdi # rdi = 42: the status code, first argument
syscall # hand control to the kernelThe same program in Intel syntax, as NASM accepts it, is the identical machine code spelled the other way around (destination before source, no sigils on registers or immediates):
; exit42.asm (x86-64, Intel syntax, NASM)
global _start
section .text
_start:
mov rax, 60 ; rax = 60: the "exit" system call number
mov rdi, 42 ; rdi = 42: the status code, first argument
syscall ; hand control to the kernelAnd here is the same program for AArch64. The shape is identical (load the call number, load the argument, execute the system-call instruction); the surface differs in the register names, the syscall number, and the instruction that enters the kernel:
// exit42.s (AArch64, GNU as)
.global _start
.text
_start:
mov x8, #93 // x8 = 93: the "exit" system call number on AArch64
mov x0, #42 // x0 = 42: the status code, first argument
svc #0 // supervisor call: hand control to the kernelThree things in this pair of listings are the entire lesson of Section 1.5 in miniature. The structure is portable: every version loads a call number, loads an argument, and traps to the kernel. The surface differs: rax versus x8 for the call number, 60 versus 93 for the number itself, syscall versus svc #0 for the trap. And the calling convention for system calls (which register holds the number, which hold the arguments) is itself a documented contract, not a thing to guess, as the next Standard notes.
On Linux/x86-64, a system call is made with the syscall instruction; the call number goes in rax and the first six arguments in rdi, rsi, rdx, r10, r8, r9. On Linux/AArch64, the instruction is svc #0; the number goes in x8 and the first arguments in x0 through x5. The numbers themselves differ per architecture: exit is 60 on x86-64 and 93 on AArch64. These conventions, and the per-architecture number tables, are documented in the Linux syscall(2) manual page and fixed by the kernel.Linux man-pages, syscall(2), "Architecture calling conventions," and the per-architecture syscall tables in the kernel source. Do not transcribe a syscall number from memory; confirm it for your architecture. The numbers are part of the kernel ABI and are stable, but they are not the same across architectures.
3.3 Assembling, Linking, and Running
Turn the x86-64 AT&T source into a running program with the two lower-level tools, then run it and read its exit status from the shell:
$ as -o exit42.o exit42.s # assemble: source -> object file
$ ld -o exit42 exit42.o # link: object file -> executable
$ ./exit42 ; echo $? # run it, then print its exit status
42The shell prints 42, the status the program asked the kernel to exit with, which is your confirmation that the three instructions did exactly what they said. The NASM version differs only in the assemble step, because NASM must be told the object format explicitly:
$ nasm -f elf64 -o exit42.o exit42.asm
$ ld -o exit42 exit42.o
$ ./exit42 ; echo $?
42On an AArch64 Linux machine, the GNU as commands are identical to the x86-64 ones (the same tool names, targeting the native architecture), and the program prints the same 42. That sameness at the command line, across two very different instruction sets, is not an accident; it is the toolchain abstraction working, and it is part of why Linux is the right platform to learn this on.
Goal: build, run, and disassemble the exit42 program on x86-64, confirm the exit status, and verify that the encoded bytes mean what the source says.
On an x86-64 Linux VM, save the AT&T source as exit42.s, then assemble and link it with the commands in Section 3.3 and confirm echo $? prints 42. Now disassemble the result and read the bytes:
$ objdump -d exit42Find the three instructions under _start. Confirm that the immediate 0x3c appears in the bytes of the first instruction (0x3c is 60, the exit number) and 0x2a in the second (0x2a is 42, your status). You have just verified a claim about what the machine does by reading the machine code, which is the habit the whole book is built on. The expected disassembly is shown and discussed in Section 3.5; do not read it until you have produced your own.
3.4 AT&T versus Intel Syntax
You have now seen both x86 syntaxes, and the difference is worth pinning down once so it never trips you again, because you will meet both: the GNU toolchain and most Linux disassembly default to AT&T, while the Intel and AMD manuals, NASM, and most Windows tooling use Intel. They describe the same instructions. The differences are mechanical, and Table 3.1 collects the ones that matter.
| Aspect | AT&T (GNU as) | Intel (NASM, vendor manuals) |
|---|---|---|
| Operand order | source, destination | destination, source |
| Register names | prefixed with % (%rax) | bare (rax) |
| Immediate values | prefixed with $ ($42) | bare (42) |
| Operand size | suffix on the mnemonic (movq, movl) | implied by register, or a keyword (qword) |
| Memory reference | offset(base,index,scale) | [base + index*scale + offset] |
| Example | movq $42, %rdi | mov rdi, 42 |
Neither is more correct, and competent practitioners read both. This book shows AT&T when working through the GNU toolchain (the default you will see in gdb and objdump) and Intel when a listing is clearer that way or when quoting the vendor manuals, and it labels every x86 listing with its syntax so there is never any doubt. Appendix B is a one-page version of this table for quick reference mid-disassembly.
3.5 What Is Inside: ELF, Sections, and Symbols
The executable you built is not just the three instructions; it is an ELF file (Executable and Linkable Format), the container Linux uses for object files, executables, and shared libraries on every architecture. The ELF file wraps your machine code in a header that tells the loader how to run it, and divides the contents into sections: your instructions live in a section named .text, initialized data would live in .data, and so on. readelf shows the header, where the entry point (the address the program starts at) is recorded:
$ readelf -h exit42
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Machine: Advanced Micro Devices X86-64
Type: EXEC (Executable file)
Entry point address: 0x401000
[...]readelf -h on exit42, captured on the x86-64 reference VM (Debian 13.5, GNU Binutils 2.44, default non-PIE ld link). The entry address is the linker's default load address for a non-PIE executable; reproduce it with the command shown, since a position-independent link or a newer toolchain can place it elsewhere. Note the file confirms two facts from Chapter 2 directly: it is little-endian, and it is 64-bit (ELF64).
Now the disassembly that Lab 1 asked you to produce, with the bytes and the meaning side by side, which is the view Part IV makes your daily habit:
$ objdump -d exit42
exit42: file format elf64-x86-64
0000000000401000 <_start>:
401000: 48 c7 c0 3c 00 00 00 mov $0x3c,%rax
401007: 48 c7 c7 2a 00 00 00 mov $0x2a,%rdi
40100e: 0f 05 syscallobjdump -d of exit42, captured on the x86-64 reference VM (Debian 13.5, GNU Binutils 2.44). The left column is the address, the middle is the raw instruction bytes, the right is the disassembly. The bytes are fixed by the instruction encoding and match on any x86-64 assembler; only the addresses depend on the link.
Read the bytes against the meaning, because this is the moment the book has been building toward. The first instruction is seven bytes, 48 c7 c0 3c 00 00 00; the 48 marks it as operating on a 64-bit register, and the 3c 00 00 00 at the end is the value 60 (0x3c) stored little-endian, exactly the byte order from Section 2.3. The second instruction is the same shape carrying 2a 00 00 00, the value 42. The third, 0f 05, is two bytes: the syscall instruction has no operands to encode. Three source lines, sixteen bytes, and every byte accounted for. When this book later makes a claim about an instruction, this is how you will check it: assemble it, disassemble it, and read the bytes.
Notice that the three instructions are seven, seven, and two bytes long. This is the variable-length encoding of Section 2.7 in front of you: there is no fixed instruction size on x86-64, and the disassembler knows where each instruction ends only because it decoded the one before it. When you build the same program on AArch64 in Part III, every instruction will be exactly four bytes, and the contrast will be visible in the same objdump output.
3.6 Introducing the Running Example: the Grimoire Digest
From here on, one small program threads the book together so that each part visibly builds on the last rather than standing alone. It is the Grimoire digest: a routine that reads a stream of bytes and reduces them to a single 64-bit fingerprint, wrapped in a freestanding Linux program that reads its input and prints the result. The core is a well-known non-cryptographic hash, FNV-1a, chosen because it is small enough to hand-write from the start and rich enough to carry every theme in the book.
That one routine will take us through all of it. In Part II you write it in x86-64 and connect it to the C library so it can be called like any function (the calling convention of Chapter 5). In Part III you port it to AArch64 and watch which parts change and which do not (Chapter 9). In Part IV you debug and disassemble it. In Part V you harden it: you make its digest-comparison constant-time so it cannot leak information through timing (Chapter 15), and you build it with the protections of Chapter 13. In Part VI you make it fast, confront the fact that its strict serial dependency resists vectorization, and learn what that teaches about the limits of optimization (Chapter 17). In the Capstone you assemble the whole thing, hardened and tuned, on both architectures at once. Build nothing yet; just know that the thread starts here, and that everything you learn will be aimed at a program you will come to know completely.
Using the toolchain from this chapter, assemble and link the AArch64 exit42.s if you have an Arm machine, and confirm echo $? prints 42. Then run objdump -d on it and confirm what Section 2.7 predicted: that each of the three instructions is exactly four bytes long, in contrast to the seven-, seven-, and two-byte x86-64 versions. If you do not yet have an Arm environment, predict the total size of the three-instruction _start on AArch64 and write it down; you will check it in Part III.
Part II x86-64 in Practice
With the portable model in hand, Part II makes it concrete in the primary worked instruction set. Here the abstract registers of Chapter 2 get their real names, the abstract stack of Section 2.5 becomes the System V stack frame with its exact rules, and the running example is written for the first time as a real callable function. By the end of this part you can read and write straight-line and branching x86-64, call and be called by C, and handle integer and floating-point work.
Chapter 4The x86-64 Register File, Integer Instructions, and Addressing Modes
The sixteen general-purpose registers, their historical names and partial-register forms, the instructions that move and compute on them, and the addressing modes that let a single instruction reach into memory: this is the working vocabulary of x86-64, and this chapter makes it fluent.
The emphasis is on the few dozen instructions that make up the overwhelming majority of real code, not an exhaustive opcode catalog, which is what the SDM is for.
4.1 The Sixteen Registers and Their Partial Forms
x86-64 gives you sixteen general-purpose registers, each 64 bits wide. Eight carry names inherited from the 16-bit and 32-bit history of the architecture, and eight were added with the 64-bit extension and are simply numbered. The named eight are rax, rbx, rcx, rdx, rsi, rdi, rbp, and rsp; the numbered eight are r8 through r15. Two of the named registers are special by convention rather than by hardware: rsp is the stack pointer (Section 2.5), and rbp is conventionally the frame pointer (Section 5.5). The other fourteen are yours to use, subject to the calling convention of Chapter 5.
Each register can be addressed at four widths, and the names change with the width. For rax: the full 64 bits is rax, the low 32 bits is eax, the low 16 bits is ax, and the low 8 bits is al. The pattern is regular for the numbered registers (r8, r8d, r8w, r8b) and slightly irregular for the historical ones, which is a wart you read past with practice. Table 4.1 lays out the set with the conventional role each plays in the calling convention, which the next chapter makes precise.
| 64-bit | 32-bit | 16-bit | 8-bit | Conventional role (System V) |
|---|---|---|---|---|
rax | eax | ax | al | return value; caller-saved |
rdi | edi | di | dil | 1st argument; caller-saved |
rsi | esi | si | sil | 2nd argument; caller-saved |
rdx | edx | dx | dl | 3rd argument; caller-saved |
rcx | ecx | cx | cl | 4th argument; caller-saved |
r8 | r8d | r8w | r8b | 5th argument; caller-saved |
r9 | r9d | r9w | r9b | 6th argument; caller-saved |
r10, r11 | ... | ... | ... | caller-saved scratch |
rbx, r12–r15 | ... | ... | ... | callee-saved |
rbp | ebp | bp | bpl | frame pointer; callee-saved |
rsp | esp | sp | spl | stack pointer |
The single most important rule about the partial forms is one that surprises nearly everyone, and it is worth fixing now because it prevents a category of bugs. Writing to a 32-bit register zeroes the upper 32 bits of the full register. Writing to a 16-bit or 8-bit register does not: it leaves the upper bits untouched. So mov $1, %eax sets all of rax to 1, while mov $1, %ax changes only the low 16 bits and leaves whatever was above them in place. This asymmetry is deliberate, it is exploited constantly by compilers to avoid extra instructions, and it is a trap when you forget it.
The Intel Software Developer’s Manual states the rule directly: when an instruction writes a 32-bit (doubleword) result to a general-purpose register, the processor zero-extends that result to fill the full 64-bit register. Writes of 8-bit or 16-bit results, by contrast, preserve the unwritten high bits. This is why a compiler emits mov %edi, %eax to copy a 32-bit value and get a clean 64-bit register for free, and why partial 8- and 16-bit writes can create a false dependency on the prior value.Intel 64 and IA-32 Architectures Software Developer’s Manual, Vol. 1, "General-Purpose Registers in 64-Bit Mode" (the 32-bit-operand zero-extension rule, in the §3.4.1.1 area). Verify the section number against the revision you consult; the rule itself is stable.
4.2 Moving Data: mov, Immediates, and Extension
The mov instruction is the workhorse: it copies a value from a source to a destination, where each may be a register, a memory location, or (for the source) an immediate constant. One of the two operands must be a register or immediate; x86-64 cannot move memory to memory in a single instruction. A 64-bit immediate is a special case, because most instructions only encode a 32-bit immediate; to load a full 64-bit constant you use the movabs form, which is exactly what the digest does to load the FNV constants in Section 4.5.
Widening a narrow value to a wider register is two different operations depending on whether the value is signed. Zero extension fills the new high bits with zero; sign extension copies the sign bit. The compiler picks the right one from the C type, and the result is instructive. A function returning an unsigned int as a 64-bit value needs no special instruction at all, because the 32-bit move already zero-extends; a function returning a signed int needs an explicit sign-extending move:
# unsigned long zx(unsigned int x) { return x; } // zero-extend
<zx>:
mov %edi,%eax # the 32-bit move ALSO zeroes the top 32 bits of rax
ret
# long sx(int x) { return x; } // sign-extend
<sx>:
movslq %edi,%rax # explicit sign-extension: copy the sign bit upward
retgcc -O1 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The unsigned widening needs no widening instruction, a direct consequence of the zero-extension rule above; the signed widening needs movslq. The explicit zero-extending forms for narrower loads are movzbl (byte to dword) and friends, which the digest uses to load a byte.
4.3 Integer Arithmetic and Logic
The arithmetic and logic instructions are the obvious ones, and they take the same operand shapes as mov: add, sub, imul (signed multiply), and, or, xor, the shifts shl and shr and sar, and the unary inc, dec, and neg. Each writes its result back to the destination operand, and, importantly, most of them set the flags (Section 2.6) as a side effect: after a sub or an add you can branch on whether the result was zero, negative, or carried, with no separate compare. Chapter 5 builds control flow on exactly that. A common idiom worth recognizing immediately is xor %eax, %eax, which sets a register to zero more compactly than moving an immediate zero, and which you will see at the top of countless functions.
4.4 Addressing Modes and lea
x86-64 can compute a memory address inside almost any instruction, using a single general form that is worth memorizing because it appears everywhere: displacement(base, index, scale) in AT&T syntax, which means the address base + index × scale + displacement. The base and index are registers, the scale is 1, 2, 4, or 8 (the size of common element types), and the displacement is a constant. Any part may be omitted. This one mode covers array indexing, structure field access, and pointer arithmetic in a single instruction, and it is the densest, most CISC-flavored part of the architecture. Here it is in three forms, disassembled from real machine code:
<ex>:
lea (%rdi,%rsi,4),%rax # rax = rdi + rsi*4 (address arithmetic, no memory touched)
movzbl (%rdi),%edx # edx = zero-extended byte at [rdi]
mov 0x8(%rdi,%rsi,8),%rcx # rcx = qword at [rdi + rsi*8 + 8]
add %rcx,%rax
add %rdx,%rax
retobjdump -d captured on the x86-64 reference VM (Debian 13.5, GNU Binutils 2.44). The same base + index*scale + disp form serves all three memory references; only lea computes the address without dereferencing it.
That last point is the one to dwell on. lea (load effective address) runs the address calculation but does not touch memory: it just puts the computed address into a register. Because the calculation is a multiply-by-1-2-4-or-8 plus two adds, lea doubles as a fast arithmetic instruction. Compilers use it to compute a + b*4 or a + b + constant in one instruction without disturbing the flags, which is why you see lea in code that has nothing to do with memory. Reading lea as "compute this expression" rather than "load this address" is a small fluency milestone.
4.5 A First Hand-Written Loop: the Digest Core
You now have enough to write the running example’s heart. The Grimoire digest (Section 3.6) is the FNV-1a hash: start from a fixed 64-bit basis, and for each input byte, exclusive-or the byte into the running value and then multiply by a fixed prime. That is a load, an xor, an imul, and a loop, which is exactly the vocabulary of this chapter. Here is the whole routine, written to take a pointer and a length and return the 64-bit digest:
# grimoire_digest(const void *buf /rdi/, unsigned long len /rsi/) -> u64 /rax/
# FNV-1a, 64-bit.
.text
.globl grimoire_digest
grimoire_digest:
movabsq $0xcbf29ce484222325, %rax # rax = FNV offset basis (the running hash)
movabsq $0x100000001b3, %rcx # rcx = FNV prime
testq %rsi, %rsi # len == 0?
je .Ldone # if so, return the basis unchanged
.Lloop:
movzbl (%rdi), %edx # edx = *buf, the next byte, zero-extended
xorq %rdx, %rax # hash ^= byte
imulq %rcx, %rax # hash *= prime
incq %rdi # buf++
decq %rsi # len-- (also sets the zero flag)
jne .Lloop # repeat until len reaches zero
.Ldone:
retEvery instruction here is from this chapter except the three that belong to the next one: testq sets the flags, je and jne branch on them, and the choice of rdi for the pointer and rsi for the length, with the result in rax, is the calling convention. Those are Chapter 5, which also wires this routine to a C main and runs it. For now it is enough that you can read it: it is a loop that folds each byte into a running 64-bit value, which is the entire idea of a hash.
The loop uses incq %rdi to advance the pointer one byte at a time and movzbl (%rdi), %edx to load the byte. Why movzbl (zero-extend byte to 32 bits) rather than a 64-bit load, and why does writing %edx safely give a clean %rdx for the xorq that follows? Answer from Section 4.1: the input is one byte, so only one byte should be read, and the 32-bit write to %edx zero-extends to %rdx, so the xorq sees the byte and nothing stale above it.
Chapter 5Control Flow, the Stack Frame, and the System V Calling Convention
A function is a contract, and on Linux/x86-64 that contract is the System V psABI: which registers carry arguments, which carries the result, which the callee must preserve, and how the stack is aligned at the moment of a call.
This chapter turns the conceptual stack of Section 2.5 into the exact discipline that lets your assembly call C and C call your assembly, and connects the running example to a real main.
5.1 Conditional Branches and the Flags
Control flow on x86-64 is two steps: an instruction sets the flags, and a conditional branch reads them. The setting usually happens for free as a side effect of arithmetic (Section 4.3), or explicitly with cmp (which subtracts its operands and keeps only the flags) or test (which ANDs them and keeps only the flags). The reading is a conditional jump: je and jne (equal or not, that is, zero flag set or clear), jl/jg for signed less and greater, and jb/ja for unsigned below and above. The signed-versus-unsigned split is the one to be careful with: comparing the same two bit patterns can give opposite answers depending on which jump you use, because "less than" means different things for signed and unsigned values. Choosing the wrong one is a real and subtle bug, and one of the things you learn to spot when reading disassembly.
5.2 Building Loops
A loop is a conditional branch backward. The digest of Section 4.5 is the canonical shape: a body, a counter decremented with dec (which sets the zero flag when it reaches zero), and a jne back to the top that falls through only when the count is exhausted. Counting down to zero like this is a small optimization, because the dec sets the flags itself and saves a separate cmp. Counting up against a limit is just as valid and reads more like the source; you will see both, and the compiler chooses between them based on what the loop does with the index.
5.3 The System V Calling Convention: Arguments and Return
A function is a contract between caller and callee about where things live, and on Linux that contract is the System V AMD64 ABI (the psABI). The first six integer or pointer arguments are passed in registers, in this order: rdi, rsi, rdx, rcx, r8, r9. Floating-point arguments go in xmm0 through xmm7 (Chapter 6). Further arguments are passed on the stack. An integer or pointer result comes back in rax. This is not a convention you may choose; it is the one the C library, the kernel entry stubs, and every compiled object on the system already follow, so any assembly that wants to interoperate must follow it too. It is also exactly why the digest was written to read its pointer from rdi and its length from rsi and to leave its result in rax: those are the registers a C caller will use.
The System V Application Binary Interface, AMD64 Architecture Processor Supplement (the x86-64 psABI), specifies that the first six integer and pointer arguments are passed in rdi, rsi, rdx, rcx, r8, r9; the first eight floating-point arguments in xmm0–xmm7; and integer results returned in rax (with rdx for the high half of a 128-bit result). The same document fixes the register-saving rules and stack alignment of Section 5.4.System V Application Binary Interface, AMD64 Architecture Processor Supplement (maintained at gitlab.com/x86-psABIs/x86-64-ABI), the parameter-passing and register-usage sections. This is the authority every Linux toolchain implements; confirm details against the current document revision.
5.4 Caller-Saved, Callee-Saved, and Stack Alignment
The convention also says who is responsible for preserving each register across a call, and this is where hand-written assembly most often goes quietly wrong. Some registers are callee-saved: if your function uses rbx, rbp, or r12 through r15, it must save them on entry and restore them before returning, because the caller is entitled to find them unchanged. The rest are caller-saved: they may be clobbered by any call, so if you need a value to survive a call you must save it yourself. The digest happens to use only caller-saved registers (rax, rcx, rdx, and the argument registers), which is why it needs no save-and-restore and has no stack frame at all.
One more rule bites people: at the point a call instruction executes, the stack pointer must be 16-byte aligned (the call then pushes the 8-byte return address, so on entry to the callee rsp is 8 mod 16). If you write a function that calls another and you have pushed an odd number of 8-byte values, you must adjust the stack to realign it, or the callee can crash inside an instruction that assumes alignment. It is a favorite source of mysterious segmentation faults in hand-written code.
5.5 The Stack Frame: Prologue and Epilogue
A function that needs local storage or that must preserve callee-saved registers builds a stack frame: it saves the old frame pointer, points rbp at the current stack top, and subtracts from rsp to reserve space. On the way out it reverses the process. Compiled unoptimized code shows the pattern at its most explicit; here is a small function that squares and sums its two arguments, compiled with optimization off so the frame is visible:
# long sumsq(long a, long b) { long s = a*a + b*b; return s; } // gcc -O0
<sumsq>:
push %rbp # save caller's frame pointer
mov %rsp,%rbp # establish this frame
mov %rdi,-0x18(%rbp) # spill arg a (rdi) to a local slot
mov %rsi,-0x20(%rbp) # spill arg b (rsi) to a local slot
mov -0x18(%rbp),%rax
imul %rax,%rax # a*a
mov %rax,%rdx
mov -0x20(%rbp),%rax
imul %rax,%rax # b*b
add %rdx,%rax # a*a + b*b
mov %rax,-0x8(%rbp) # store the local s
mov -0x8(%rbp),%rax # load it as the return value
pop %rbp # restore caller's frame pointer
retgcc -O0 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). At -O0 the compiler spills every value to the stack, which makes the frame and the argument registers (rdi, rsi) easy to see; at -O2 the same function compiles to a couple of imuls and no frame at all. Reading both is the skill of Chapter 10.
Notice that the locals live at negative offsets from rbp, that the two arguments arrived in rdi and rsi exactly as the convention promised, and that the result departed in rax. The System V ABI also grants a 128-byte red zone below rsp that a leaf function (one that calls nothing) may use as scratch without adjusting the stack pointer at all; it is a Linux detail that explains why some small functions skip the frame entirely.
5.6 Calling the Grimoire Digest from C
Because the digest already obeys the convention, calling it from C takes no glue at all: declare it, link the assembly object alongside the C object, and call it like any function. Here is the harness, which also checks the routine against a published FNV-1a test vector so we know the assembly is correct and not merely runnable:
// main.c
#include <stdio.h>
#include <string.h>
extern unsigned long grimoire_digest(const void *buf, unsigned long len);
int main(void) {
const char *t = "foobar"; // published FNV-1a test vector
const char *g = "The Programmer's Grimoire"; // the running example's input
printf("foobar = %016lx\n", grimoire_digest(t, strlen(t)));
printf("grimoire = %016lx\n", grimoire_digest(g, strlen(g)));
return 0;
}$ gcc -O2 -o digest main.c digest.s
$ ./digest
foobar = 85944171f73967e8
grimoire = 1b11756f20c6f520Built and run on the x86-64 reference VM (Debian 13.5, GCC 14.2, GNU Binutils 2.44). The foobar line matches the published FNV-1a 64-bit test vector (0x85944171f73967e8), so the hand-written routine is correct against the algorithm, not just against itself. The grimoire digest of the running example’s input is the value the rest of the book refers back to.
Goal: assemble the digest, link it with the C harness, run it, and confirm it reproduces the published FNV-1a test vector.
On the x86-64 VM, save the routine from Section 4.5 as digest.s and the harness above as main.c, then build and run them with the two commands shown. Confirm the first line reads 85944171f73967e8. Then change the test string from "foobar" to "foobars" and confirm the digest changes completely, which is the avalanche property a hash should have. You have now written an assembly routine that interoperates with C through nothing but the calling convention, the foundation everything in Chapter 11 builds on.
Chapter 6Floating Point and the SSE/AVX Register File
Modern x86-64 does floating-point and vector work in the same register file, the XMM/YMM/ZMM registers introduced with SSE and extended by AVX.
This chapter covers scalar floating point as the on-ramp to the vector register file that Part VI will push hard, and explains why the old x87 stack is legacy you will read but should not write.
6.1 The XMM Register File and Scalar SSE
Floating-point and vector work on x86-64 share one register file, separate from the general-purpose registers of Chapter 4. The registers are xmm0 through xmm15, each 128 bits wide. AVX widened them to 256 bits under the names ymm0–ymm15, and AVX-512 to 512 bits as zmm0–zmm31; the narrower name is always the low part of the wider one. A register this wide can hold either a single scalar value in its low bits (one double, say, with the rest unused) or several packed values side by side (the vector case of Section 6.4 and Chapter 17). This chapter is the scalar on-ramp; Part VI returns for the packed work where the width pays off.
The calling convention reaches into this register file too. As Section 5.3 noted, floating-point arguments are passed in xmm0 through xmm7 and a floating-point result returns in xmm0, exactly parallel to the integer registers. That single fact explains the shape of every scalar floating-point function you will read.
6.2 Floating-Point Arithmetic and Comparison
The scalar instructions carry a suffix that names the type: sd for a scalar double (64-bit), ss for a scalar single (32-bit). So addsd, subsd, mulsd, and divsd are double-precision arithmetic, and addss and friends are single-precision. A function that adds two doubles compiles to a single instruction, and its shape is the calling convention made visible:
# double addd(double a, double b) { return a + b; } // gcc -O1
<addd>:
addsd %xmm1,%xmm0 # xmm0 = a + b; a arrived in xmm0, b in xmm1, result stays in xmm0
retgcc -O1 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The first double argument arrived in xmm0, the second in xmm1, and the result is left in xmm0, so the entire function is one arithmetic instruction and a return.
Comparison is the one place floating point reaches back to the integer flags of Section 2.6. The instructions comisd and ucomisd compare two scalars and set the same ZF, CF, and PF flags that integer code branches on, so a floating-point if is a ucomisd followed by a conditional jump. The parity flag matters here in a way it never does for integers: it flags an unordered result, which is how the hardware reports a comparison involving a NaN, and well-written floating-point code checks for it.
6.3 Converting Between Integer and Floating Point
Moving a value between the integer and floating-point register files is an explicit conversion, never a plain mov, because the bits mean different things in each. The two conversions you will read most are integer to double and double to integer:
# double i2d(long x) { return (double)x; }
<i2d>:
pxor %xmm0,%xmm0 # clear xmm0 first (break the false dependency on its old value)
cvtsi2sd %rdi,%xmm0 # convert the integer in rdi to a double in xmm0
ret
# long d2i(double x) { return (long)x; }
<d2i>:
cvttsd2si %xmm0,%rax # convert (truncating toward zero) the double in xmm0 to an integer in rax
retgcc -O1 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). Note the extra pxor that clears the destination before cvtsi2sd: it costs nothing and breaks a false dependency on the register’s previous contents, a microarchitectural habit Chapter 16 explains. The double-to-integer form is cvtt... with two ts, meaning it truncates toward zero rather than rounding, which is what C’s cast requires.
6.4 A First Look at Packed Operations
Everything above used one scalar value in the low bits of a wide register. The reason the registers are wide is that the same instruction can operate on several values at once: addpd adds two pairs of doubles in one go, addps adds four singles, and the wider ymm and zmm forms do more lanes still. This is SIMD, single instruction, multiple data, and it is where hand-written assembly most often beats the compiler. It is also where the running example will hit a wall worth understanding: the digest’s each-step-depends-on-the-last structure resists being spread across lanes, which is itself the central lesson of Chapter 17. For now, recognize the packed forms when you read them and know that the width is the point.
6.5 x87 as Legacy
Before SSE, x86 floating point was done on the x87 unit, a stack of eighty-bit registers (st(0) through st(7)) addressed not by name but by their position on a stack. It is still present in the silicon and you will meet it in old code, but you should not write it: the System V x86-64 ABI passes and returns floating-point values in the SSE registers, not on the x87 stack, and SSE2 is guaranteed on every 64-bit processor. The x87 stack model is awkward, its eighty-bit intermediate precision makes results harder to reason about, and it is firmly legacy. Recognizing it is a Chapter 18 skill, filed with the other things you inherit but do not write.
On 32-bit x86 a compiler defaulted to x87 for floating point. On x86-64 the ABI changed that: scalar floating point uses the SSE registers and instructions shown here, and x87 survives only for the rare eighty-bit long double and in hand-written or very old code. If you see st(0) and fadd in a modern disassembly, you are almost certainly looking at long double arithmetic or inherited code, not at what a current compiler emits for a double.
Compile double scale(double x) { return x * 2.0; } with gcc -O2 -S and read the output. Where did the constant 2.0 come from (it is not an immediate the way an integer constant would be), and which register holds the argument and the result? You are confirming that floating-point constants live in memory and are loaded into an xmm register, and that xmm0 carries both the argument in and the result out.
Part III AArch64 in Practice
Part III instantiates the same model a second time, in the contrast architecture, and this is where teaching two instruction sets pays for itself. Because you already hold the portable model, AArch64 is mostly "the same idea, spelled differently," and the genuine differences (a strict load/store discipline, twice as many registers, fixed-length encoding, a link register instead of an automatic stack push) stand out cleanly against the shared background. The part ends by porting the running example and reflecting on what the port taught.
Chapter 7The AArch64 Load/Store Architecture, Register File, and Instructions
AArch64 has thirty-one general-purpose registers and one firm rule that shapes everything: arithmetic happens only in registers, and memory is touched only by explicit load and store instructions.
This chapter teaches that discipline directly, because it is the single biggest adjustment for a reader coming from x86-64’s memory-operand-rich instructions, and it is what makes Arm code so regular to read once it clicks.
7.1 The Register File: X0 to X30, the W Forms, and the Zero Register
AArch64 gives you thirty-one general-purpose registers, named x0 through x30, each 64 bits wide. That is twice the count of x86-64, and the extra breathing room is one reason Arm code often needs fewer trips to memory. Each register has a 32-bit view named w0 through w30, and the same rule you learned for x86 applies: writing a w register zero-extends into the full 64-bit x register, while the upper bits are otherwise preserved. Two of the registers carry fixed roles by hardware convention: x30 is the link register, where a call leaves its return address (Section 8.2), and x29 is the frame pointer by software convention.
Two pieces of the register model have no x86 equivalent and are worth meeting now. The stack pointer sp is not one of the thirty-one general registers; it is separate, which is why you never see it spilled or used as scratch the way rsp sometimes is. And register number 31 in most instruction encodings is the zero register: read as xzr (or wzr) it always reads as zero, and written it discards the result. That sounds useless until you see how often "do this but throw away the result" or "use a hard zero" is exactly what an instruction needs, which is why a comparison is just a subs writing to xzr.
7.2 The Load/Store Architecture
Here is the one rule that shapes everything about reading AArch64, and the single biggest adjustment coming from x86: arithmetic happens only between registers, and memory is touched only by dedicated load and store instructions. There is no AArch64 equivalent of adding a value straight from memory; you ldr it into a register, operate, and str it back. This is what "load/store architecture" means, and it is the defining trait of the RISC lineage AArch64 belongs to. The loads and stores come in widths: ldr/str for a full register, ldrb/strb for a byte, ldrh for a halfword, and the pair forms ldp/stp that move two registers at once and are central to the stack frame of Section 8.4.
The trade is regularity for density. An x86 instruction can fold a memory access, an arithmetic op, and an addressing calculation into one variable-length instruction; AArch64 spends separate fixed-size instructions on each step. The result is more instructions but a far more uniform stream, which is why Arm disassembly is famously easy to read once the load/store rhythm becomes familiar.
7.3 Arithmetic, Logic, and the Flag-Setting Forms
The arithmetic and logic instructions are the expected set: add, sub, mul, the bitwise and, orr, and eor (exclusive-or, the instruction the digest uses), and the shifts lsl, lsr, and asr. Unlike x86, where most arithmetic sets the flags as a side effect, AArch64 makes flag-setting explicit: the plain forms leave the flags alone, and the s-suffixed forms (adds, subs, and the comparison cmp, which is really subs to the zero register) update them. This is the same idea you met in Section 2.6 seen from the other side: x86 sets flags by default and AArch64 by request, two reasonable answers to the same design question, and the contrast is exactly what makes the underlying concept visible.
7.4 Addressing Modes: Offset, Index, Pre- and Post-Index
Because only loads and stores touch memory, AArch64 puts its addressing flexibility there, and it is rich. A load can take a base register plus a constant offset, a base plus an index register, a base plus a scaled index, or it can update the base register as a side effect, before the access (pre-index) or after it (post-index). Two forms appear in the running example and are worth seeing disassembled. Scaled-register indexing reaches into an array in one instruction:
// long idx(long *a, long i) { return a[i]; }
<idx>:
ldr x0, [x0, x1, lsl #3] // load from a + i*8 (lsl #3 scales the index by 8, the size of a long)
retgcc -O1 output captured on the AArch64 reference VM (Debian 13.5, GCC 14.2). The [base, index, lsl #n] form is the direct counterpart of x86’s base + index*scale from Section 4.4; here lsl #3 multiplies the index by eight.
Post-index addressing is the other one, and it is the AArch64 idiom that makes the digest loop a step shorter than its x86 cousin: ldrb w4, [x0], #1 loads the byte at x0 and then advances x0 by one, folding the pointer increment into the load itself. Where x86 needed a separate inc, AArch64 does the bump as part of the access.
7.5 A First Loop, Read Against Its x86-64 Twin
You now have the vocabulary to read AArch64 fluently, and the fastest way to lock it in is to set the two architectures side by side on the same problem. Chapter 9 does exactly that with the running example, porting the digest of Section 4.5 line by line and watching which parts are the portable model and which are the AArch64 surface. Before that, make sure the pieces here are solid: the register file and the zero register, the load/store rule, the explicit flag-setting forms, and the addressing modes, especially the post-index form the digest leans on.
The x86-64 digest used movzbl (%rdi), %edx to load a byte and a separate incq %rdi to advance the pointer, two instructions. Which single AArch64 instruction does both, and what is the name of the addressing mode that makes it possible? Answer from Section 7.4: ldrb w4, [x0], #1, using post-index addressing, which performs the load and then increments the base register.
Chapter 8AArch64 Control Flow, the AAPCS64 Calling Convention, and NEON
AArch64 saves return addresses in a register (the link register) rather than pushing them automatically, which changes the shape of a function prologue and has direct consequences for both performance and the pointer-authentication defense of Chapter 14. This chapter covers branching, the AAPCS64 calling convention, and NEON, the Arm vector extension that parallels SSE/AVX.
8.1 Branches and the NZCV Flags
AArch64 control flow is built from a small, regular set of branches. The unconditional b jumps; b.cond jumps on a condition (b.eq, b.ne, b.lt, b.gt, and the rest) by reading the four condition flags N, Z, C, and V (negative, zero, carry, overflow), the same four facts about the last result that x86 records in RFLAGS. Two compare-and-branch instructions, cbz and cbnz, fold the test and the branch together for the common case of "branch if this register is (not) zero" without touching the flags at all, which is why the digest opens with a single cbz x1, .Ldone instead of a separate compare and jump.
8.2 The Link Register: bl, ret, and Why x30 Is Saved
This is the calling-convention difference that shapes every AArch64 function you will read. Where x86 call pushes the return address onto the stack automatically, AArch64 bl (branch with link) writes the return address into the link register x30 and branches; ret jumps back to whatever is in x30. A function that calls nothing, a leaf, can leave x30 alone and return cheaply. A function that calls something must save x30 first, because its own bl will overwrite the link register with a new return address. Here is that non-leaf pattern, disassembled:
// long viacall(long a) { return ext(a) + 1; } // gcc -O1
<viacall>:
stp x29, x30, [sp, #-16]! // push the frame pointer and link register as a pair; pre-decrement sp by 16
mov x29, sp // establish this frame
bl ext // call ext(a); this OVERWRITES x30 with the return address
add x0, x0, #1 // result + 1
ldp x29, x30, [sp], #16 // restore the pair; post-increment sp by 16
ret // return to the (restored) link registergcc -O1 output captured on the AArch64 reference VM (Debian 13.5, GCC 14.2). The stp ... [sp, #-16]! stores the pair and updates sp in one instruction (the ! is the pre-index writeback); ldp ... [sp], #16 reverses it. Saving x30 is not optional here, because the bl to ext destroys the caller’s return address otherwise.
Contrast this with the leaf case. A function that calls nothing keeps its return address in x30 untouched for the whole of its life, so it needs no pair save at all, only space for any locals:
// long sumsq(long a, long b) { long s = a*a + b*b; return s; } // gcc -O0, a leaf
<sumsq>:
sub sp, sp, #0x20 // reserve 32 bytes of locals; no x30 save needed (leaf)
str x0, [sp, #8] // spill arg a
str x1, [sp] // spill arg b
ldr x0, [sp, #8]
mul x1, x0, x0 // a*a
ldr x0, [sp]
mul x0, x0, x0 // b*b
add x0, x1, x0 // a*a + b*b
str x0, [sp, #24]
ldr x0, [sp, #24]
add sp, sp, #0x20 // release the locals
ret // return via the untouched x30gcc -O0 output captured on the AArch64 reference VM. The same function whose x86-64 frame you read in Section 5.5: here it is a leaf, so it never saves the link register, and at -O2 it shrinks to a couple of muls and no stack traffic at all.
8.3 The AAPCS64 Calling Convention
The Arm contract parallels the System V one of Section 5.3 closely enough that the concept transfers directly, with different register names. Integer and pointer arguments go in x0 through x7, and an integer result returns in x0. Floating-point and vector arguments and results use v0 through v7 (Section 8.5). Registers x19 through x28 are callee-saved, so a function that uses them must preserve them, exactly the role rbx and r12 through r15 play on x86. The link register x30 and frame pointer x29 have the special handling you just saw.
The Arm Procedure Call Standard for the 64-bit architecture (AAPCS64) specifies that the first eight integer or pointer arguments are passed in x0–x7 and the first eight floating-point or vector arguments in v0–v7; integer results return in x0 (and x1 for a 128-bit result). Registers x19–x28 are callee-saved; x30 is the link register and x29 the frame pointer. The standard also requires the stack pointer to be 16-byte aligned at a public interface, the AArch64 counterpart of the x86 alignment rule.Arm Procedure Call Standard for the Arm 64-bit Architecture (AAPCS64), maintained at github.com/ARM-software/abi-aa, the general-purpose-register and stack sections. Confirm the exact callee-saved set and the rule for the low 64 bits of v8–v15 against the current document.
8.4 The Stack Frame and 16-Byte Alignment
A non-leaf frame is built and torn down with the pair instructions you saw: stp x29, x30, [sp, #-16]! on entry and ldp x29, x30, [sp], #16 on exit, with any additional locals reserved by adjusting sp. Because stp moves sixteen bytes and the ABI requires sp to stay 16-byte aligned at a call, the pair-based prologue keeps the alignment correct by construction, which is part of why it is the universal idiom. The same alignment discipline that bites hand-written x86 code (Section 5.4) applies here, and the pair instructions are the tool that makes it natural to get right.
8.5 NEON and the V Register File
Floating-point and vector work share a second register file of thirty-two 128-bit registers, v0 through v31. Like the x86 SSE registers, each can hold one scalar value or several packed ones, and the name you use selects the view: q0 is the full 128 bits, d0 the low 64 (one double), and s0 the low 32 (one single). A scalar double add is the exact parallel of x86’s addsd:
// double addd(double a, double b) { return a + b; }
<addd>:
fadd d0, d0, d1 // scalar double add; a in d0, b in d1, result in d0 (cf. x86 addsd %xmm1,%xmm0)
retThe packed form is where the width pays off. NEON names a vector operation by its lane arrangement: .4s means four 32-bit single-floats, .2d two doubles, .16b sixteen bytes. Adding four floats at once is a single instruction:
// vst1q_f32(c, vaddq_f32(vld1q_f32(a), vld1q_f32(b))); // four floats at once
<vadd4>:
ldr q31, [x0] // load four floats from a into the 128-bit q31
ldr q30, [x1] // load four floats from b
fadd v30.4s, v31.4s, v30.4s // add all four lanes in one instruction
str q30, [x2] // store the four results
retgcc -O2 output captured on the AArch64 reference VM (Debian 13.5, GCC 14.2). The .4s arrangement adds four single-precision lanes at once, the NEON counterpart of x86’s packed addps; Chapter 17 pushes this for real speed.
A function calls printf in the middle of its work and needs a value to survive that call. On AArch64, which registers may it safely keep the value in without saving it, and which would be destroyed by the call? Answer from Section 8.3: a callee-saved register (x19 through x28) survives, while the argument and temporary registers (x0 through x18) may be clobbered by the callee.
Chapter 9Porting the Running Example: the Model Generalizes, the Surface Differs
This is the payoff chapter for the two-ISA method.
We take the x86-64 Grimoire digest from Part II and port it to AArch64 line by line, and the experience is the lesson: the algorithm, the control flow, and the calling-convention concept carry over unchanged, while the register names, the load/store split, and the syscall surface change in predictable ways. The result is a single program that exists in two faithful machine-level forms.
9.1 Reading the x86-64 Version as a Specification
The cleanest way to port a routine is to treat the version you have as the specification and translate it deliberately, rather than rewriting from the algorithm. The x86-64 digest of Section 4.5 is six instructions of real work: load the two constants, test for an empty input, then a loop of load-a-byte, exclusive-or, multiply, advance, decrement, branch, and finally return the result. Every one of those steps has a direct AArch64 expression, and lining them up is the whole exercise.
9.2 The Translation, Register by Register
The mapping is mechanical. The running hash that lived in rax moves to x2, the prime in rcx to x3, and the two arguments arrive in x0 and x1 instead of rdi and rsi. The 64-bit constant loads that were movabs become the literal-pool form ldr x2, =.... The byte load and the pointer increment, two instructions on x86, fold into one post-index ldrb. The xor becomes eor, the imul becomes mul, the dec-and-branch becomes subs and b.ne, and because the result must leave in x0 rather than where it was computed, the port ends with an explicit mov x0, x2. Here is the whole thing, and it assembles, links, and runs:
// grimoire_digest(const void *buf /x0/, unsigned long len /x1/) -> u64 /x0/
// FNV-1a, 64-bit, AArch64.
.text
.globl grimoire_digest
grimoire_digest:
ldr x2, =0xcbf29ce484222325 // x2 = hash = FNV offset basis (cf. movabs into rax)
ldr x3, =0x100000001b3 // x3 = FNV prime
cbz x1, .Ldone // if len == 0, return the basis (cf. test+je)
.Lloop:
ldrb w4, [x0], #1 // w4 = *buf++ (load byte AND advance, in one instruction)
eor x2, x2, x4 // hash ^= byte (cf. xor)
mul x2, x2, x3 // hash *= prime (cf. imul)
subs x1, x1, #1 // len-- (cf. dec; sets the flags)
b.ne .Lloop // repeat while len != 0 (cf. jne)
.Ldone:
mov x0, x2 // return value in x0 (x86 left it in rax already)
ret9.3 What Changed: the Surface
Set the two routines side by side and the differences are entirely the architectural surface of Section 1.5, and every one of them is something you can now name. The register names changed. The 64-bit constant load changed form, from an immediate baked into the instruction to a PC-relative load from a literal pool the assembler builds. The byte load absorbed the pointer increment through post-indexing. The result needed an explicit move into x0 because AArch64 designates a specific return register rather than leaving the value wherever the last arithmetic put it. And, invisibly in the source but plain in the disassembly, every instruction is exactly four bytes. None of these is a different idea; each is the same idea wearing AArch64 clothes.
9.4 What Did Not Change: the Model
Everything that matters about what the routine does is identical, and that is the point of having learned the portable model first. The algorithm is the same. The control-flow shape, a guarded loop counting a length down to zero, is the same. The calling-convention concept, arguments arriving in registers and the result leaving in one, is the same, with only the register names swapped. The instruction count is nearly the same. A reader fluent in one version reads the other on sight, because the differences are a vocabulary list, not a new language. This is why teaching two instruction sets costs so much less than twice one: the expensive part, the model, is paid for once.
9.5 Building Both and Confirming Identical Digests
The proof that the port is faithful is that it produces the same fingerprints. Built and run on the AArch64 reference VM, against the same C harness from Section 5.6, the routine reproduces both values exactly:
$ gcc -O2 -o digest main.c digest.s
$ ./digest
foobar = 85944171f73967e8
grimoire = 1b11756f20c6f520Built and run on the AArch64 reference VM (Debian 13.5, GCC 14.2, GNU Binutils 2.44). These are the same two values the x86-64 build produced in Section 5.6: the published FNV-1a vector 85944171f73967e8 and the running example’s own 1b11756f20c6f520. A hash is a definition, not an implementation, so a correct port on any architecture must land on the identical bits.
Goal: build the AArch64 port of the digest, run it, and confirm it produces bit-for-bit the same digests as the x86-64 build.
On the AArch64 VM, save the routine above as digest.s and reuse the main.c from Section 5.6 unchanged, then build and run them. Confirm both lines match the x86-64 results exactly. If you have both VMs up, run the two builds together and diff the output: it should be empty. You have now carried one routine across two instruction sets and proved the crossing was lossless, which is the entire thesis of a dual-architecture volume reduced to a single command.
The register-by-register mapping you just made by hand for the digest is the seed of Chapter 19, the x86-64-to-AArch64 translation reference, which generalizes it into a lookup table covering registers, calling conventions, common idioms, the SIMD families, and the security mechanisms. Every entry there was earned the way this one was: by porting real code and watching what changed.
Part IV Living in the Toolchain
Most engineers read far more assembly than they write, so Part IV treats reading and debugging as the first-class skills they are. It teaches fluent disassembly on both architectures, instruction-level debugging with gdb, the two-way bridge between assembly and C, and the loader machinery that turns a static file into a running process. This is the part that makes the rest of your career with a debugger faster.
Chapter 10Reading Disassembly Fluently: objdump, readelf, and the Compiler’s Output
The skill of reading compiler output and stripped binaries is learnable and teachable, and this chapter teaches it as a method rather than a knack: how to find your bearings in an unfamiliar disassembly, recognize the common idioms a compiler emits, map optimized code back to source intent, and use Compiler Explorer as a bench to watch source become machine code in real time.
10.1 objdump and readelf as Your Eyes
Two tools show you what is actually in a binary, and you will reach for them every day. objdump -d disassembles the executable sections, printing for each instruction its address, its raw bytes, and its mnemonic, in AT&T syntax by default or Intel with -M intel. readelf reports the structure: -h for the header, -S for the section table, -s for the symbol table, -r for relocations, and -d for the dynamic section. Between them you can answer almost any question about a binary without running it, which is the heart of static analysis. Everything in this chapter is one of these two tools pointed at a real file.
10.2 Reading the Compiler’s Output: -O0 against -O2
The fastest way to learn to read compiled code is to compile the same function twice, once with optimization off and once with it on, and compare. Unoptimized code is verbose and literal: every variable goes to the stack, every step is spelled out. Optimized code is what actually ships, and it is dense. Here is one small function both ways:
# long sumsq(long a, long b) { return a*a + b*b; }
# gcc -O0: literal, every value spilled to the stack
<sumsq>:
push %rbp; mov %rsp,%rbp # build a frame
mov %rdi,-0x8(%rbp) # spill a
mov %rsi,-0x10(%rbp) # spill b
mov -0x8(%rbp),%rax; imul %rax,%rax # a*a
mov %rax,%rdx
mov -0x10(%rbp),%rax; imul %rax,%rax # b*b
add %rdx,%rax # a*a + b*b
pop %rbp; ret
# gcc -O2: four instructions, no frame, no memory
<sumsq>:
imul %rdi,%rdi # a*a (in place)
imul %rsi,%rsi # b*b (in place)
lea (%rdi,%rsi,1),%rax # rax = a*a + b*b (lea used purely as an adder)
retBoth captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The optimized form keeps everything in registers, drops the frame entirely, and uses lea to add the two products, the address-arithmetic-as-arithmetic trick from Section 4.4. Recognizing that lea here computes a sum, not an address, is exactly the fluency this chapter builds.
10.3 Recognizing the Common Idioms
Optimized code is built from a vocabulary of idioms, and once you know them you read it almost as fast as source. A few you have already met: xor %eax, %eax zeroes a register; test %rsi, %rsi followed by a conditional jump is "is this zero or null?"; lea with a non-trivial expression is arithmetic, not a memory access; the push %rbp; mov %rsp, %rbp pair opens a frame and leave or pop %rbp closes it. On AArch64 the equivalents are just as recognizable: cbz for the null test, stp x29, x30 for the frame open. Reading well is mostly pattern recognition layered on the instruction knowledge of the earlier parts.
10.4 Compiler Explorer as a Bench
The single most useful tool for building this skill is Compiler Explorer (godbolt.org), which shows your source and the compiler’s assembly output side by side and updates live as you type, for either architecture and any optimization level. It is the fastest possible loop for the experiment of Section 10.2: change a line, watch the assembly change, and learn what each construct costs. Use it constantly; it turns "what does the compiler do with this?" from a guess into an observation.
10.5 A Guided Read
Take the four-instruction -O2 form above and narrate it: square the first argument in place, square the second in place, add the two products with a lea into the return register, return. Four instructions, no stack traffic, the result handed back in rax exactly as Section 5.3 requires. That is the entire function, and you just read optimized machine code without a decompiler. The rest is practice and the occasional Chapter 11 debugger session when static reading is not enough.
In the -O2 output, the compiler wrote lea (%rdi,%rsi,1),%rax instead of add %rdi,%rsi followed by a move. Both compute the sum. Why might the compiler prefer the lea form? Answer from Section 4.4: lea writes the sum to a third register (rax) in one instruction without disturbing rdi or rsi and without touching the flags, where add would overwrite an operand and set the flags.
Chapter 11Instruction-Level Debugging with gdb; Inline Assembly and C Interop
When the bug only shows up in the optimized build, the debugger is your machine-level microscope.
This chapter teaches gdb at the instruction level (stepping, registers, memory, breakpoints on addresses) and the two ways assembly and C meet in practice: calling hand-written assembly from C across the ABI, and embedding inline assembly inside C correctly.
11.1 gdb at the Instruction Level
When static reading is not enough, gdb is your machine-level microscope, and a handful of commands cover most of the work. layout asm shows the disassembly as you step; stepi and nexti advance one instruction; info registers dumps the register file; break sets a breakpoint at a function or a raw address; and the x command examines memory in any format. The mental shift from source-level debugging is small: you step instructions instead of lines and watch registers instead of variables.
11.2 Watching the Calling Convention, Live
Nothing makes the calling convention concrete like seeing it happen. Break at the digest and inspect the arguments the instant control arrives, before the function has run a single instruction:
$ gdb -q ./digest
(gdb) break grimoire_digest
(gdb) run
Breakpoint 1, 0x0000555555555169 in grimoire_digest ()
(gdb) x/s $rdi
0x555555556004: "foobar"
(gdb) p/d $rsi
$1 = 6Captured on the x86-64 reference VM (Debian 13.5, GDB 16.3). At the breakpoint, $rdi holds the pointer to the input and x/s shows it points at "foobar"; $rsi holds the length, 6. The System V convention of Section 5.3 is not theory here; it is the literal contents of two registers. Note the 0x5555... addresses: this is a position-independent executable loaded at a randomized base (Chapter 12).
11.3 Calling Assembly from C
You already did this in Section 5.6: declare the routine extern in C, write it in a .s file that obeys the calling convention, and hand both to the compiler driver, which assembles and links them. There is no glue and no marshaling, because the ABI is the glue. This is how real projects mix a hand-tuned assembly kernel into a C program: the assembly is just another object file with a known calling convention.
11.4 Inline Assembly
The other direction, dropping a few instructions directly into C, uses the compiler’s extended inline assembly. The form names the assembly template, then the outputs, inputs, and clobbered registers, each with a constraint that tells the compiler how to wire a C value to a register:
// add b into a using one instruction, then return the result
long a = 40, b = 2, r;
__asm__("add %1, %0" : "=r"(r) : "r"(a), "0"(b));
// "=r"(r): output r in some register; "r"(a): input a in some register;
// "0"(b): input b in the SAME register as output 0, so r starts as b$ ./inl
inline add => 42Built and run on the x86-64 reference VM (Debian 13.5, GCC 14.2). The constraints are the contract between your assembly and the compiler’s register allocator; get them wrong and the compiler will feed your instruction the wrong registers or reuse one it should not.
11.5 The Foot-Guns: Clobbers and the Red Zone
Two mistakes dominate. The first is failing to declare a clobber: if your inline assembly modifies a register or the condition flags and you do not list it, the compiler assumes that register survived and miscompiles the surrounding code, a bug that appears only at certain optimization levels. The flags are clobbered by most arithmetic, so an inline add or cmp usually needs "cc" in the clobber list. The second is the red zone (Section 5.5): inline assembly that writes below the stack pointer can corrupt the 128-byte red zone a leaf function relies on. Both are the kind of bug that hides until it does not, which is why inline assembly is a sharp tool used sparingly.
The inline add example does not list "cc" (the condition codes) as a clobber, yet it works. Under what circumstance would omitting "cc" cause a wrong result, and why is adding it the safe habit? Answer: if the compiler were relying on a flag set before the inline block to drive a branch after it, the unlisted flag change from your add would silently corrupt that branch; listing "cc" tells the compiler the flags are not preserved.
Chapter 12The Loader, PIC/PIE, Relocations, and Position-Independent Code
The static file you built and the process the kernel runs are not the same thing, and the difference (where the code is placed in memory, how its references are fixed up, why modern binaries are position-independent) is both a routine source of confusion and the foundation of the address-randomization defense in Chapter 13. This chapter takes the loader apart.
12.1 From ELF File to Running Process
The file you build and the process that runs are not the same thing. When you launch a program, the kernel and the dynamic linker map the ELF file’s segments into memory at some base address, set up the stack and the initial register state, wire up any shared libraries, and finally jump to the entry point. Understanding this last mile explains several things that otherwise look like magic: why the addresses in gdb did not match the addresses in objdump (Section 11.2), how a call into the C library finds its target, and what the security mitigations of Chapter 13 actually move.
12.2 Static against Dynamic Linking
A statically linked program contains every function it needs, including the C library, baked into the executable. A dynamically linked one, the normal case on Linux, contains only references to functions in shared libraries, which the dynamic linker resolves at load time. The digest program is dynamically linked because it calls printf from the shared C library, and that single external call is enough to bring in the whole resolution machinery of the next two sections.
12.3 Position-Independent Code and Why the Entry Moved
Modern Linux builds executables as position-independent by default, meaning the code makes no assumption about the address it loads at and can therefore be placed anywhere. The difference is visible in the ELF header. Build the digest the default way and again with -no-pie, and read the type:
$ readelf -h d_pie | grep Type
Type: DYN (Position-Independent Executable file)
$ readelf -h d_nopie | grep Type
Type: EXEC (Executable file)Captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The default build is DYN, the same type as a shared library, which is what lets the loader place it at a randomized base; its entry sits at a low offset like 0x1080. The -no-pie build is EXEC with a fixed entry at 0x401070. This is why gdb showed the digest at 0x5555...: a position-independent executable plus address-space randomization put it there.
12.4 The GOT and the PLT
How does a position-independent program call printf when it does not know, at build time, where printf will be? Through two tables. The Procedure Linkage Table (PLT) is a small stub the call goes to; the Global Offset Table (GOT) holds the actual address, filled in by the dynamic linker. The call in the binary targets the stub, the stub jumps through the GOT entry, and a relocation tells the linker which symbol fills which slot:
$ objdump -d d_pie | grep printf
1071: e8 ba ff ff ff call 1030 <printf@plt>
$ readelf -r d_pie | grep printf
... R_X86_64_JUMP_SLOT ... printf@GLIBC_2.2.5 + 0Captured on the x86-64 reference VM (Debian 13.5, GNU Binutils 2.44). The call goes to printf@plt, a stub; the R_X86_64_JUMP_SLOT relocation names the GOT slot the dynamic linker fills with the real printf address (by default lazily, on first call). AArch64 uses the same two-table design with its own relocation names.
12.5 Why PIE Is the Default, and What It Costs
Position independence is the default because the address-space layout randomization of Chapter 13 needs it: code that can load anywhere can be loaded somewhere unpredictable, which denies an attacker the fixed addresses an exploit depends on. The cost is small, an extra level of indirection through the GOT for external calls and slightly larger code, which is almost always worth paying. You verify a binary is position-independent exactly as above, with readelf -h, and it is one of the first things to check when you inherit a binary and want to know how it was hardened.
You disassemble a binary with objdump and see a function at 0x1149, but when you break on it in gdb and run, it reports the function at 0x555555555149. The binary has not changed between the two commands. What accounts for the different addresses? Answer from Section 12.3: it is a position-independent executable, so the loader placed it at a randomized base address (here 0x555555554000), and the runtime address is that base plus the file offset.
Part V Secure Machine-Level Code
Assembly is the language of both exploitation and its defenses, and Part V teaches the defensive side with the offensive side in view, because you cannot reason about a mitigation without understanding the attack it answers. It covers the software protections every Linux binary already runs under, the newer hardware control-flow and memory-safety features on each architecture, and the discipline of writing code whose timing does not betray its secrets. This is the part with the richest primary-source security substrate, and it replaces the compliance crosswalk that other Grimoire volumes carry, because no such standard exists for a language.
Chapter 13The Software Mitigation Stack: NX, ASLR, PIE, Stack Canaries, and RELRO
Before any hardware help, a Linux binary is defended by a stack of software mitigations that you should be able to name, verify, and reason about: non-executable memory, address-space layout randomization, position-independent executables, stack canaries, and read-only relocations.
This chapter explains what each defends against, using the stack-frame and loader knowledge from Parts II through IV, and shows how to confirm each on a real binary.
13.1 The Threat: From Overflow to Hijacked Control Flow
The attack the whole stack of mitigations answers is the buffer overflow turned into control-flow hijack. A function copies attacker-controlled data into a fixed-size stack buffer without checking the length; the data runs past the buffer and overwrites the saved return address sitting higher on the stack; when the function returns, the processor jumps wherever the attacker wrote. This works because, as Section 2.1 warned, the machine cannot tell code from data, and a return address is just bytes in writable memory next to a buffer. Every defense in this chapter makes that one move harder.
13.2 NX and W^X: Data Stopped Being Executable
The first and most basic defense is to forbid executing data. Under the no-execute (NX) policy, also called W^X (write xor execute), a page of memory may be writable or executable but not both, so the classic move of writing machine code into a buffer and jumping to it simply faults. You can see the policy in the program headers: the stack is marked read-write, not executable.
$ readelf -lW app | grep GNU_STACK
GNU_STACK 0x000000 ... 0x000000 0x000000 RW 0x10Captured on the x86-64 reference VM (Debian 13.5). The RW with no E flag is the non-executable stack. NX did not end memory-corruption attacks; it redirected them to reusing existing code, which is the subject of Chapter 14.
13.3 ASLR and PIE Together
If an attacker cannot inject code, they will try to jump to code or data already present, which requires knowing its address. Address-space layout randomization (ASLR) denies that knowledge by loading the program and its libraries at unpredictable addresses each run, and it needs the position-independent executables of Chapter 12 to do so for the main program. This is the defense you saw indirectly in Section 11.2, when the digest appeared at 0x5555... under gdb: that high, odd base is ASLR placing a PIE binary somewhere an exploit cannot predict.
13.4 Stack Canaries
A stack canary catches the overflow in the act. The compiler places a secret value, loaded from thread-local storage, just below the saved return address on entry, and checks it just before returning; an overflow large enough to reach the return address must first overwrite the canary, so the check fails and the program aborts rather than returning into a smashed frame. Built with -fstack-protector-strong, a function with a buffer shows the whole mechanism:
<vuln>:
sub $0x28,%rsp
mov %fs:0x28,%rsi # load the canary from thread-local storage (%fs:0x28)
mov %rsi,0x18(%rsp) # place it just below the saved return address
... # the body, including the vulnerable strcpy into buf
mov 0x18(%rsp),%rdx
sub %fs:0x28,%rdx # has the canary changed?
jne <__stack_chk_fail> # if so, abort; never return into a smashed frame
add $0x28,%rsp
retgcc -O2 -fstack-protector-strong, captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The guard at %fs:0x28 and the call to __stack_chk_fail on a mismatch are the canary in full. AArch64 does the same with a guard loaded relative to its thread register.
13.5 RELRO
One more target is the Global Offset Table of Section 12.4: if an attacker can overwrite a GOT entry, they redirect a library call to code of their choosing. Relocation Read-Only (RELRO) closes this by resolving the GOT at startup and then marking it read-only, visible as a GNU_RELRO segment in the program headers. Full RELRO (with immediate binding) makes the entire GOT read-only; partial RELRO protects only part of it. It is one of the cheapest hardening wins and a standard default.
13.6 Verifying What a Binary Was Built With
When you inherit a binary, these are the first things to check, and readelf answers all of them: -h shows Type: DYN for a PIE, -lW shows GNU_STACK as non-executable and whether a GNU_RELRO segment is present, and the presence of __stack_chk_fail in the symbols indicates stack protection. The checksec tool wraps all of this into one report. Knowing how a binary was hardened, or was not, is the starting point for both defending it and attacking it.
Goal: build the same program with and without the mitigations and see the difference in the binary.
On the x86-64 VM, compile a small program twice: once normally, and once with -no-pie -fno-stack-protector -z execstack -z norelro. Compare them with readelf -hlW and, if installed, checksec. Confirm that the hardened build is DYN with a non-executable stack and a GNU_RELRO segment, and the unhardened one is EXEC with an executable stack and no RELRO. You are learning to read a binary’s defensive posture at a glance, exactly as you would when triaging an inherited system.
Chapter 14Hardware Control-Flow Integrity and Memory Safety: CET vs PAC, BTI, and MTE
The two architectures answer control-flow hijacking and memory-safety bugs with different hardware, and seeing them side by side is the clearest way to understand either.
This chapter covers Intel CET (the shadow stack and indirect branch tracking, with its ENDBR landing pads) against Arm’s pointer authentication, branch target identification, and memory tagging, all as documented in the vendor manuals and the kernel.
14.1 The Return-Oriented-Programming Problem
Non-executable memory ended code injection, so attackers stopped injecting code and started reusing it. Return-oriented programming (ROP) chains together short snippets of existing, legitimate code, each ending in a ret, by writing a sequence of return addresses onto the stack; each ret jumps to the next snippet, and the chain performs the attack using only code already marked executable. NX cannot stop it, because nothing new is executed, and ASLR only raises the difficulty. Defeating ROP took hardware that checks control flow itself, and the two architectures answer it differently, which is why seeing both is the clearest way to understand either.
14.2 Intel CET: the Shadow Stack and Indirect Branch Tracking
Intel Control-flow Enforcement Technology (CET) adds two hardware checks. The shadow stack keeps a second, protected copy of every return address; on a ret, the processor compares the normal return address against the shadow copy and faults if they differ, which catches the overwritten return address ROP depends on. Indirect Branch Tracking (IBT) requires every indirect call or jump to land on a special endbr64 instruction, so an attacker cannot jump into the middle of a function. Build a program with -fcf-protection and the landing pad appears at the top of each compiled function:
$ gcc -O2 -fcf-protection -o app app.c
$ objdump -d app | grep -m1 endbr64
1110: f3 0f 1e fa endbr64Captured on the x86-64 reference VM (Debian 13.5, GCC 14.2), built with -fcf-protection. The four-byte endbr64 (f3 0f 1e fa) is the IBT landing pad the hardware requires an indirect branch to target. CET is not on by default here: Debian’s gcc ships -fcf-protection=none and Debian’s own binaries carry no CET property, unlike Fedora and Ubuntu 24.04 and later, so request it explicitly. Whether the shadow stack is also enforced depends on the kernel and CPU; confirm on the target with the GNU properties (readelf -n) and /proc/cpuinfo.
Control-flow Enforcement Technology is specified in the Intel Software Developer’s Manual and documented for Linux in the kernel’s shadow-stack documentation. The shadow stack maintains a protected copy of return addresses and faults on mismatch; IBT requires indirect branch targets to be marked with ENDBR32/ENDBR64. Support is present in glibc and the mainline kernel. Some distributions enable it by default (Fedora, and Ubuntu 24.04 and later); Debian does not, so on Debian pass -fcf-protection explicitly.Intel 64 and IA-32 Architectures Software Developer’s Manual (CET); Linux kernel documentation, Control-flow Enforcement Technology Shadow Stack (docs.kernel.org/arch/x86/shstk.html). Confirm enforcement on the specific kernel and CPU; the compiler landing pads are necessary but not sufficient without kernel and hardware support.
14.3 Arm Pointer Authentication
Arm answers the same threat cryptographically rather than with a second stack. Pointer Authentication (PAC) signs the return address with a secret key and a context value (the stack pointer) on function entry, and authenticates it before returning; if anything overwrote the saved return address, the signature no longer verifies and the processor faults. Built with branch protection, the function from Section 8.2 gains a sign on entry and an authenticate on exit:
<f>:
paciasp # sign the link register (x30) using the stack pointer as context
stp x29, x30, [sp, #-16]!
mov x29, sp
bl ext
add x0, x0, #1
ldp x29, x30, [sp], #16
autiasp # authenticate x30 before ret; a tampered return address faults
retgcc -O1 -mbranch-protection=standard, captured on the AArch64 reference VM (Debian 13.5, GCC 14.2). paciasp and autiasp bracket the function; no shadow stack is needed because the protection is a signature carried in the unused high bits of the pointer itself.
14.4 Arm BTI and MTE
Branch Target Identification (BTI) is Arm’s counterpart to IBT: indirect branches must land on a bti instruction, and in the standard branch-protection mode the paciasp above doubles as a valid landing pad. The Memory Tagging Extension (MTE) attacks the bug class one level lower: it tags every 16-byte granule of memory and every pointer with a 4-bit key, and faults when a pointer’s tag does not match the memory it accesses, catching use-after-free and out-of-bounds bugs that the control-flow defenses never see. A binary advertises which of these it carries in a GNU property note:
$ readelf -n app
Properties: AArch64 feature: BTI, PACCaptured on the AArch64 reference VM (Debian 13.5). The note tells the loader the binary supports BTI and PAC so enforcement can be turned on; MTE additionally requires hardware and kernel support, which varies by device.
Pointer Authentication (Armv8.3), Branch Target Identification (Armv8.5), and the Memory Tagging Extension (Armv8.5) are specified in the Arm Architecture Reference Manual and documented for Linux in the kernel’s arm64 documentation. PAC signs and verifies pointers; BTI constrains indirect branch targets; MTE tags memory and pointers to catch spatial and temporal memory-safety violations.Arm Architecture Reference Manual (DDI 0487), the PAC, BTI, and MTE chapters; Linux kernel documentation, pointer-authentication and memory-tagging-extension under arch/arm64. Feature availability is per-CPU; confirm with the HWCAP bits and /proc/cpuinfo on the target.
14.5 The Same Threat, Two Designs
Set the two approaches side by side and the contrast is the lesson. Intel keeps a separate protected stack and checks equality; Arm signs the pointer in place and checks a cryptographic tag. Both stop the overwritten return address, neither needs the program rewritten, and both are turned on with a compiler flag and verified with readelf. Knowing both means you can reason about the defensive posture of a binary on either architecture, which is increasingly something one engineer is expected to do.
Chapter 15Constant-Time and Side-Channel-Resistant Code
A comparison that returns as soon as it finds a difference can leak a secret through how long it took, and at the machine level you can both see why and fix it. This chapter hardens the running example’s digest comparison to run in constant time, then generalizes to the vendor guidance on data-operand-independent timing and the situations where cryptographic code must be written this way.
15.1 Timing Side Channels, Concretely
The mitigations so far defend control flow. This chapter defends a subtler thing: the time a computation takes. If how long a routine runs depends on a secret, an attacker who can measure the time can learn the secret, without ever corrupting memory. The classic case is comparing a secret, a password hash or an authentication tag, with a byte-by-byte compare that returns the moment it finds a difference. Such a compare returns faster when the first byte is wrong than when the first ten match, and that timing difference leaks, one byte at a time, exactly how much of a guess was correct. The fix is to make the time independent of the secret.
15.2 The Leaky Compare and the Constant-Time Fix
The dangerous version is the obvious one: loop over the bytes and return on the first mismatch. The constant-time version never branches on the data. It walks every byte regardless, accumulates any differences into one value with or, and reports equality only at the end:
// constant-time: time depends on n, never on WHERE or WHETHER the bytes differ
int ct_eq(const unsigned char *a, const unsigned char *b, unsigned long n){
unsigned char d = 0;
for (unsigned long i = 0; i < n; i++) d |= a[i] ^ b[i];
return d == 0;
}Compiled, the loop has no data-dependent branch: the only branch is the loop counter, which depends on the length, not the contents.
<ct_eq>:
...
movzbl (%rdi,%rax,1),%ecx # load a[i]
xor (%rsi,%rax,1),%cl # ^ b[i]
add $0x1,%rax # i++
or %ecx,%r8d # accumulate the difference (no branch on it)
cmp %rax,%rdx
jne <loop> # loop on the length only
test %r8b,%r8b
sete %al # result = (accumulated difference == 0)
retgcc -O2 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). There is no jump that depends on the compared data; the routine takes the same path and the same number of iterations whether the inputs match in the first byte or the last. That is what "constant-time" means in practice.
15.3 Branch-Free and Data-Independent Techniques
The technique generalizes to two rules. First, do not branch on a secret: replace a secret-dependent if with arithmetic or a conditional move (cmov on x86, csel on AArch64) that runs the same either way. Second, do not index memory with a secret: a table lookup at a secret offset leaks through the cache, because which line gets cached depends on the secret and is measurable. Cryptographic code is written entirely under these two rules, which is why hand-written assembly is common there: the programmer needs guarantees about branches and memory access that a higher-level language does not make.
15.4 The Hardware Wrinkle: DOIT and DIT
There is a final, uncomfortable layer. Even branch-free, data-independent code can leak if the processor itself takes a data-dependent amount of time for an instruction, which recent microarchitectures do for some operations unless told otherwise. Both vendors added a mode that guarantees constant-time execution for a defined subset of instructions: Intel calls it Data Operand Independent Timing (DOIT), Arm calls it Data Independent Timing (DIT), and each is a bit the software sets. The sharp edge, current as of this writing, is that Intel processors from Ice Lake onward do not guarantee data-operand-independent timing by default, so cryptographic code that assumed constant-time arithmetic must request the mode explicitly.
Intel’s Data Operand Independent Timing guidance and its Guidelines for Mitigating Timing Side Channels Against Cryptographic Implementations, together with Arm’s Data Independent Timing (DIT) control, are the authorities on writing constant-time code. They specify which instructions are covered, how to enable the mode, and the standing requirements (no secret-dependent branches or memory addresses) that the mode does not replace.Intel, Data Operand Independent Timing ISA Guidance, and Guidelines for Mitigating Timing Side Channels Against Cryptographic Implementations (intel.com developer security guidance); Arm Architecture Reference Manual (DDI 0487), the DIT (PSTATE.DIT) control. Verify the covered-instruction list and default behavior for the specific microarchitecture.
15.5 Transient-Execution Side Channels: Spectre and the Speculation Barriers
The most famous of these side channels works one level deeper than timing, and it is the dark side of the distinction this book opened with. To go fast, a processor speculates: it guesses the outcome of a branch or a bounds check and runs ahead before the guess is confirmed, then discards the work if the guess was wrong. The discarded work never changes the architectural result, so the program is still correct, but it leaves traces in the cache, and an attacker who measures the cache can read data the speculation touched, including data the program would never have reached. Spectre and its relatives are exactly the gap between the ISA, which is upheld, and the microarchitecture, which is not silent. They are the security face of the same ISA-versus-implementation split from Section 1.3 and Section 16.1.
The reference machines describe their own exposure, and the kernel publishes it at /sys/devices/system/cpu/vulnerabilities/, which is the first place to look on any system. The two architectures answer differently, exactly as the rest of the book would predict:
# x86-64 (Debian 13.5)
$ cat /sys/devices/system/cpu/vulnerabilities/spectre_v2
Mitigation: Retpolines; STIBP: disabled; RSB filling; PBRSB-eIBRS: Not affected; BHI: Retpoline
$ cat /sys/devices/system/cpu/vulnerabilities/meltdown
Mitigation: PTI
# AArch64 (Debian 13.5)
$ cat /sys/devices/system/cpu/vulnerabilities/spectre_v2
Mitigation: CSV2, but not BHB
$ cat /sys/devices/system/cpu/vulnerabilities/meltdown
Not affectedCaptured on both reference VMs. The x86 core mitigates Spectre v2 with retpolines, a compiler-generated assembly construct, and Meltdown with kernel page-table isolation (PTI); the Arm core is not affected by Meltdown and handles v2 through a hardware feature (CSV2). One is fixed in emitted code, the other in silicon, and the difference is visible with cat.
That word "retpolines" is the reason this belongs in an assembly book: a major Spectre mitigation is emitted instructions, and you read it in disassembly. A retpoline replaces an indirect branch, the kind an attacker steers by poisoning the branch predictor, with a construct whose speculative path is trapped while its architectural path reaches the real target:
# an indirect call built with retpoline (gcc -mindirect-branch=thunk)
<call_indirect>:
mov fp(%rip),%rax # load the target pointer
jmp __x86_indirect_thunk_rax # reach it through the thunk, not a bare jmp *%rax
<__x86_indirect_thunk_rax>:
call .Lset # the architectural path: push a return address
.Lcap:
pause # the SPECULATIVE path lands here:
lfence # a dead end the processor cannot speculate past
jmp .Lcap
.Lset:
mov %rax,(%rsp) # overwrite the return address with the real target
ret # "return" to it; misprediction was already trapped abovegcc -mindirect-branch=thunk output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The indirect branch becomes a ret whose speculation is steered into the pause; lfence capture loop, defeating the branch-predictor poisoning of Spectre v2. The Linux kernel is built this way; you also see it in any user code compiled with the flag.
The other variants have their own assembly-level answers. Spectre v1, the bounds-check bypass, is stopped by halting speculation right after the check: an lfence barrier on x86, or index masking that forces a mis-speculated index back in range (array[i & mask]). Arm did not leave this to the kernel alone; it added barrier instructions to the ISA for it, csdb (a baseline consumption-of-speculative-data barrier) and sb (a speculation barrier, from Armv8.5), which a compiler or a hand-written routine inserts where speculation must be bounded.
The authoritative, living references are the Linux kernel’s hardware-vulnerability documentation (admin-guide/hw-vuln/spectre.rst and its siblings), Intel’s retpoline and speculative-execution side-channel guidance, and Arm’s CPU security bulletins. They define each variant, the per-core exposure, and the exact mitigation sequences, and they are updated as new variants appear.Linux kernel, Documentation/admin-guide/hw-vuln/ (spectre.rst and related); Intel, "Retpoline: A Branch Target Injection Mitigation" and the speculative-execution side-channel guidance; Arm CPU security bulletins (developer.arm.com). The variant and mitigation matrix changes frequently; read the current document and the live /sys/.../vulnerabilities/ rather than a printed snapshot.
A boundary, because this is a field that could fill its own volume and keeps moving. Do not try to memorize the variant zoo (v1, v2, v4, the data-sampling families, Retbleed, branch-history injection, and whatever shipped this quarter); the same reference VM already lists newer entries this section does not name. The systemic fixes, page-table isolation, microcode, and hardware redesign, live in the kernel and the silicon, which is where most readers should leave them. What an assembly programmer needs is narrower and durable: recognize these mitigations in a disassembly, know that retpolines and speculation barriers are why some code looks the way it does, and, if you write a sandbox, a just-in-time compiler, or cryptographic code, know the barriers exist and where they go. For everything else, the kernel doc and the vendor bulletins are the current truth, and the version you read here is already aging.
15.6 Where This Is Mandatory, and the Running Example
Constant-time discipline is required wherever code handles a secret that an attacker could probe by timing: password and token comparison, and the core of any cryptographic primitive, which is exactly the kind of code validated under FIPS 140-3 and the NIST Cryptographic Module Validation Program. It connects directly to the running example. The digest itself is not secret, but the moment you use it to authenticate, comparing a received digest against the expected one to decide whether to grant access, that comparison must be the constant-time ct_eq of Section 15.2, never a plain memcmp that returns early. The fingerprint you taught the machine to compute in Part II becomes safe to check only when you check it in constant time.
A reviewer replaces the constant-time digest check with if (memcmp(received, expected, 8) == 0) grant_access(); and argues it is fine because the digests are only eight bytes. Why is this still a timing leak, and roughly how many attempts might it take an attacker to recover the expected digest one byte at a time rather than by brute force? Answer from Section 15.1: memcmp returns on the first differing byte, so timing reveals how many leading bytes are correct, turning a 2^64 brute force into a byte-at-a-time search of roughly 256 times 8 attempts.
Part VI Performance and Vectorization
This is the "scale" of an assembly volume: not more machines, but more work per cycle. Part VI builds the microarchitectural cost model that explains why fast code is fast, teaches SIMD in depth on both architectures, and confronts honestly the question every would-be assembly optimizer must answer, which is when hand-written code actually beats a good compiler and when it merely loses to it more slowly.
Chapter 16The Microarchitectural Model: Latency, Throughput, Ports, and Cache
Correctness is a property of the instruction set; speed is a property of the silicon that runs it. This chapter builds the cost model the optimization work depends on: instruction latency and throughput, execution ports and how many operations issue per cycle, the cache hierarchy, and branch prediction, drawing on the vendor optimization manuals and the measured data that fills the gaps the manuals leave.
16.1 Why the Simple Cycle Model Is Not the Whole Story
The fetch-decode-execute cycle of Section 2.4 is exactly right about what a program means and badly incomplete about how fast it runs. A real processor does not finish one instruction before starting the next; it overlaps many in a pipeline, issues several per cycle through multiple execution units, and even runs them out of order, all while preserving the illusion that they happened one at a time. None of that changes the result, which is why the simple model is correct for reading code. All of it changes the timing, which is why a separate model is needed for making code fast.
16.2 Latency against Throughput
Two numbers describe every instruction, and confusing them is the most common optimization error. Latency is how many cycles pass before the result of one instruction is available to the next. Throughput is how many of that instruction can complete per cycle when they are independent. A multiply might have a latency of three cycles but a throughput of one per cycle, meaning a chain of dependent multiplies runs at one every three cycles, while a stream of independent ones runs at one per cycle, three times faster. This distinction is the entire explanation for why the running example is slow, as Section 17.4 shows: its multiplies form a dependent chain, so it is latency-bound.
16.3 Ports, Issue Width, and Instruction-Level Parallelism
The reason independent instructions go faster is that the processor has several execution units, reached through issue ports, and can start an instruction on each port every cycle. Code with many independent operations keeps the ports busy and approaches the throughput limit; code that is one long dependency chain leaves most ports idle, waiting, and runs at the latency limit. Extracting instruction-level parallelism, arranging work so independent operations are available to fill the ports, is much of what optimization is, and much of what a compiler already does for you when the algorithm allows it.
16.4 The Cache Hierarchy
The other dominant cost is memory. A value in the L1 cache is a few cycles away; in L2, a couple of dozen; in L3, dozens more; in main memory, hundreds. Because the gap is so large, how a program touches memory often matters more than how many instructions it runs, and a cache-friendly layout can beat a cleverer algorithm with a hostile one. Streaming sequentially through an array, as the sum in the next chapter does, is the friendly case; chasing pointers around the heap is the hostile one. When you optimize, you are usually optimizing memory access as much as computation.
16.5 Where the Numbers Live
The exact latency and throughput of each instruction on each microarchitecture is not something to guess or memorize; it is published. The vendor optimization manuals give the model and the coarse numbers, and the fine per-instruction tables, which the vendors do not publish exhaustively, are measured and maintained independently. Measuring your own code is the other half: the perf tool reads the hardware counters for cycles, instructions, and cache misses, though it needs access to the performance-monitoring unit, which many virtual machines do not expose (the reference VMs here among them, so this book’s performance numbers are wall-clock).
The authoritative cost model and coarse timings are in the vendor optimization guides (the Intel 64 and IA-32 Optimization Reference Manual and the AMD Software Optimization Guide for each family, and Arm’s per-core optimization guides). The de facto fine-grained per-instruction latency and throughput tables are Agner Fog’s instruction tables and the uops.info database, which are measured rather than vendor-published and are the standard reference where the manuals are silent.Agner Fog, "Instruction tables" and "The microarchitecture of Intel, AMD and VIA CPUs" (agner.org/optimize); uops.info; Intel 64 and IA-32 Architectures Optimization Reference Manual; AMD Software Optimization Guide. Treat the measured tables as empirical data for a specific microarchitecture, not as a vendor guarantee.
Chapter 17SIMD in Depth and When Hand Assembly Beats the Compiler
Single-instruction-multiple-data is where hand-written assembly still routinely wins, and this chapter teaches it as one concept realized twice (AVX on x86-64, NEON and SVE2 on AArch64). It also uses the running example as an honest teacher: the Grimoire digest’s strict serial dependency resists vectorization, which is itself the most important optimization lesson, that the algorithm, not the instruction set, sets the ceiling.
17.1 The SIMD Model and Data Layout
Single instruction, multiple data is the idea that one instruction can operate on several values packed into a wide register at once, and it is where hand-written assembly most often still wins. You met the registers already: the 128-bit XMM and wider YMM and ZMM on x86 (Chapter 6), and the 128-bit V registers on AArch64 (Section 8.5). The catch is that the data has to be laid out so that the lanes are independent and contiguous; SIMD rewards arrays of values you can process in parallel and punishes data structures you have to gather one field at a time. Getting the layout right is most of the work.
17.2 AVX in Practice
The compiler will vectorize the easy cases for you. A plain summation loop, compiled with AVX2 enabled, becomes 256-bit vector additions without a line of assembly:
// long sum(const int *a, long n) { long s = 0; for (...) s += a[i]; return s; } // gcc -O3 -mavx2
vmovdqu (%rax),%ymm0 # load 8 ints (256 bits) at once
vpmovsxdq %xmm0,%ymm2 # widen to 64-bit lanes
vpaddq %ymm1,%ymm2,%ymm1 # add four 64-bit partial sums in parallel
...gcc -O3 -mavx2 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The loop processes eight integers per iteration in ymm registers. When the compiler can see that the lanes are independent, it does this automatically; the value of writing it by hand comes when it cannot.
17.3 NEON and SVE2, and the Mapping
AArch64 does the same work with NEON, the fixed-128-bit vector unit whose four-lane float add you saw in Section 8.5, and with SVE2, a newer scalable vector extension whose register width is not fixed in the instruction so the same code runs on hardware of different widths. The operations map closely onto the AVX ones: a packed add is a packed add, a load of a vector is a load of a vector, and the lane arrangements (.4s, .2d) play the role of the x86 element-size suffixes. Chapter 19 sets the two families side by side as a lookup table.
17.4 The Running Example Hits a Wall
Now the honest lesson, and the reason the digest was chosen as the running example. SIMD speeds up independent work, and the digest is the opposite of independent: each step multiplies the running hash by the prime, so every iteration depends on the result of the one before. There is no parallelism to extract across the byte stream, and the compiler knows it. Compiled with full optimization and AVX2 enabled, the FNV loop contains exactly zero vector instructions, because the loop-carried dependency forbids them. The measured consequence, on a 64 MB buffer:
$ ./bench
digest (serial FNV): 403 MB/s
sum (AVX vector): 4725 MB/sWall-clock throughput captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The streaming sum, whose lanes are independent, runs about twelve times faster than the digest, whose dependency chain pins it to the latency of one multiply per byte. The ratio is the point, not the absolute numbers; it is the difference between work that vectorizes and work that does not.
The way to make the digest fast is therefore not a cleverer instruction but a different algorithm: hash several independent lanes of the input in parallel and combine them at the end, or choose a hash designed for parallelism. That is an algorithm decision, made above the assembly, and recognizing when you are against a dependency wall rather than a coding inefficiency is the most valuable thing this chapter teaches.
17.5 Measuring, and Deciding Whether It Is Worth It
Because the compiler already vectorizes the independent cases, hand-written SIMD earns its keep in a narrower band than people expect: kernels the compiler cannot see how to vectorize, code that needs a specific instruction the compiler will not emit, and hot paths tuned to one microarchitecture. The decision is always empirical. Measure the compiler’s output first, write the hand version only if the measurement justifies it, and measure again, because a hand-tuned kernel that is harder to maintain and only marginally faster is a poor trade. The skill is not writing SIMD; it is knowing when to.
The summation loop vectorized and ran about twelve times faster than the digest, yet both walk the same number of bytes. What property of the summation makes it vectorizable and the digest not, and what kind of change, in assembly or in the algorithm, would be needed to speed the digest up? Answer from Section 17.4: the sum’s additions are independent across elements while the digest’s multiplies form a loop-carried dependency, so speeding it up requires an algorithmic change to independent parallel lanes, not a better instruction.
Part VII Legacy, Translation, and the Edges
Machine code has a long afterlife, and Part VII is the production reality the rest of the field ignores: inheriting hand-written assembly you did not write, porting it across the transitions happening right now, and reaching for the field-reference table that maps one architecture onto the other. It closes the book where most real assembly work actually happens, which is in maintaining and moving what already exists.
Chapter 18Inheriting and Porting: 32-bit to 64-bit, x87 to SIMD, and Removed Features
The "found a routine still written in 32-bit x86 with x87 floating point" moment is the assembly equivalent of the legacy server every Grimoire volume takes seriously.
This chapter covers reading and porting old machine code: the 32-bit to 64-bit transition, the x87-to-SSE migration, and the features that have been removed out from under code (Intel MPX, AMD 3DNow!, and the largely disabled TSX), with the Apple Silicon and Arm-server transitions of Chapter 1 as the live cases.
18.1 Reading 32-bit i386 and the Differences That Bite
The most common piece of inherited assembly is 32-bit x86, and its calling convention is the first thing that will confuse you, because it is not the one Part II taught. Where x86-64 passes arguments in registers, the old 32-bit convention passes them on the stack. The same trivial function tells the whole story:
# int add3(int a, int b, int c) { return a + b + c; }
# i386 (gcc -m32): arguments come off the STACK
<add3>:
mov 0x8(%esp),%eax # b, from the stack
add 0x4(%esp),%eax # + a
add 0xc(%esp),%eax # + c
ret
# x86-64: the same arguments arrive in registers
<add3>:
add %esi,%edi # a + b (in edi, esi)
lea (%rdi,%rdx,1),%eax # + c (in edx)
retBoth captured on the x86-64 reference VM (Debian 13.5, GCC 14.2; the 32-bit build via gcc -m32 with the multilib libraries). The 32-bit form reads its arguments from %esp offsets; the 64-bit form reads them from registers. The other differences follow from the era: eight general registers instead of sixteen, the e-prefixed names (eax, esi), and no instruction-pointer-relative addressing, so position-independent 32-bit code is noticeably clumsier.
18.2 Porting i386 to x86-64
Porting up is mostly mechanical once you see the pattern. The registers widen (eax becomes rax, and you gain r8 through r15), arguments move from the stack into the System V registers of Section 5.3, and you can use the red zone and RIP-relative addressing. The traps are the places where 32-bit assumptions are baked in: code that assumed a pointer was four bytes, that read arguments at fixed stack offsets, or that used self-modifying tricks the modern mitigations of Chapter 13 now forbid. The work is less translation than modernization.
18.3 x87 to SSE
The other fossil you will meet is x87, the original floating-point unit, which computes on a stack of eighty-bit registers rather than the SSE registers of Chapter 6. It is not entirely gone: on x86-64 the long double type still uses it, which is the easiest way to see it today:
# long double ldadd(long double a, long double b) { return a + b; }
<ldadd>:
fldt 0x8(%rsp) # push a onto the x87 stack (80-bit load)
fldt 0x18(%rsp) # push b
faddp %st,%st(1) # add and pop: st(1) += st(0)
ret # result left in st(0)gcc -O2 output captured on the x86-64 reference VM (Debian 13.5, GCC 14.2). The st() stack and the f-prefixed instructions are the x87 model. Modern double and float use SSE (Section 6.2); x87 survives mainly for long double and in inherited code, and porting it forward means moving to the SSE registers and accepting 64-bit rather than 80-bit precision.
18.4 Removed and Deprecated Features
Some instructions have been removed out from under code that used them, and recognizing them saves you from chasing a feature that no longer exists. Intel Memory Protection Extensions (MPX), a hardware bounds-checking scheme, was dropped from GCC in version 9.1 and removed from the Linux kernel in 5.6, so MPX-using binaries run without the protection they think they have. AMD’s 3DNow! SIMD extension was withdrawn and its instructions removed from current assemblers and compilers. Intel’s Transactional Synchronization Extensions (TSX) have been disabled by microcode on most parts for security reasons. When you inherit code that uses any of these, the correct move is to excise or replace it, not to revive it.
18.5 The Migration That Is Urgent Now
The legacy transition that matters most today is not a fossil but a live one: the move from x86-64 to AArch64. Apple Silicon already runs only AArch64, and Apple’s retirement of the Rosetta translation layer (Section 1.4) is removing the crutch that let x86-64 code run unported; the Arm server tide is pushing the same way in the data center. Porting a routine across the two is exactly the exercise of Chapter 9, and doing it well is what the translation reference in Chapter 19 is for. The difference from the fossils above is that this migration is happening to current code, on a clock, which is why a working engineer now reads both instruction sets.
Chapter 19The x86-64 to AArch64 Translation Reference
This chapter is the field-reference asset no single-architecture book can offer, and the structural replacement for the compliance crosswalk that other Grimoire volumes carry: a systematic mapping between the two instruction sets.
Registers, calling conventions, common idioms, the SIMD families, and the security mechanisms are set side by side so that a reader fluent in one architecture can read and port the other by lookup.
19.1 Register and Calling-Convention Correspondence
This chapter is the field reference the two-architecture approach earns: a systematic mapping you can open mid-port. It is built entirely from the routines verified earlier in the book, not from a specification read in the abstract. Start with the registers and the calling convention, the two things you reach for first when reading or porting a function.
| Role | x86-64 | AArch64 |
|---|---|---|
| Integer arguments 1 to 6 (Arm: to 8) | rdi, rsi, rdx, rcx, r8, r9 | x0–x7 |
| Integer return value | rax | x0 |
| Float/vector args and return | xmm0–xmm7 / xmm0 | v0–v7 / v0 |
| Callee-saved | rbx, r12–r15, rbp | x19–x28, x29 |
| Stack pointer | rsp | sp (separate from the GPRs) |
| Frame pointer | rbp | x29 |
| Return address | on the stack (pushed by call) | x30, the link register (set by bl) |
| Condition flags | RFLAGS (set by default) | NZCV (set on request, the s forms) |
| Hard zero | (none; use xor reg,reg) | xzr / wzr |
19.2 Instruction-Idiom Translation
The common idioms map closely enough that most lines translate one to one. Table 19.2 is the digest port of Chapter 9 generalized.
| Operation | x86-64 | AArch64 |
|---|---|---|
| Move register to register | mov | mov |
| Load 64-bit constant | movabs $imm, %reg | ldr xN, =imm (literal pool) |
| Load a byte, zero-extended | movzbl (%rsi), %eax | ldrb w0, [x1] |
| Load a byte and advance pointer | movzbl (%rsi),%eax; inc %rsi | ldrb w0, [x1], #1 (post-index) |
| Add / multiply | add / imul | add / mul |
| Exclusive-or | xor | eor |
| Branch if a register is zero | test %r,%r; je L | cbz xN, L |
| Decrement and loop | dec %r; jne L | subs xN,xN,#1; b.ne L |
| Call / return | call / ret | bl / ret |
| Save/restore a register pair | push / pop (one at a time) | stp / ldp (pair, frame idiom) |
| Address arithmetic without load | lea | add (with shifted operand) |
19.3 Addressing and the Memory Model
The deepest difference is the one from Section 7.2: x86-64 can fold a memory access into almost any instruction, while AArch64 touches memory only through loads and stores. So an x86 instruction like add (%rdi,%rsi,8), %rax becomes two AArch64 instructions, a ldr with the scaled-index addressing of Section 7.4 and then an add. The x86 addressing form disp(base, index, scale) corresponds to the AArch64 load/store form [base, index, lsl #n]; the difference is that on x86 it can appear anywhere and on AArch64 only in a load or store. Keep that one rule in mind and most memory-touching code translates on sight.
19.4 SIMD Family Correspondence
| Concept | x86 (SSE/AVX) | AArch64 (NEON/SVE2) |
|---|---|---|
| Vector register | xmm (128), ymm (256), zmm (512) | v/q (128); SVE2 scalable |
| Scalar double in the vector reg | xmm0 low | d0 (low of v0) |
| Scalar double add | addsd %xmm1,%xmm0 | fadd d0, d0, d1 |
| Packed float add (4 lanes) | addps / vaddps | fadd v0.4s, v0.4s, v1.4s |
| Packed integer add | vpaddq %ymm... | add v0.2d, v0.2d, v1.2d |
| Int to double / double to int | cvtsi2sd / cvttsd2si | scvtf / fcvtzs |
19.5 Security-Mechanism Mapping
The defenses of Part V pair up by the threat they answer, even where the design differs sharply, which is the most useful way to hold them in mind across the two architectures.
| Threat answered | x86-64 | AArch64 |
|---|---|---|
| Return address overwrite | CET shadow stack | Pointer Authentication (paciasp/autiasp) |
| Jump into the middle of code | IBT (endbr64 landing pads) | BTI (bti landing pads) |
| Spatial/temporal memory bugs | (no direct equivalent) | MTE (memory tagging) |
| Code injection | NX / W^X (shared) | |
| Known addresses | ASLR + PIE (shared) | |
| Stack smashing detection | Stack canaries, RELRO (shared) | |
That is the whole crossing on a few pages: registers, idioms, the memory model, the vector families, and the defenses. Built from verified code rather than read from a manual, it is the reference a reader fluent in one architecture opens to work in the other, and it is the asset no single-architecture book can offer.
Capstone
The capstone assembles everything into one build, the way the PHP and SELinux volumes end on a single hardened system. It carries the Grimoire digest from source to a hardened, tuned, dual-architecture deliverable, with every step labeled by the chapter that taught it, and a verification pass that proves each property on a real machine.
Chapter 20Building, Hardening, and Optimizing a Real Routine End to End on Both ISAs
One program, built twice, correct, hardened, and fast: the running example as a finished thing.
This chapter walks the complete build on x86-64 and AArch64 together, turning on the mitigations of Part V, applying the optimization of Part VI, and verifying at each step that the property claimed is the property present, before a closing look forward to APX, AVX10, SVE2, and the RISC-V companion edition.
20.1 The Specification and the Plan
The capstone assembles everything into one deliverable: grimoire-sum, a small tool that takes a string, computes the Grimoire digest of it, and prints the fingerprint, built to ship. Shipping means three things at once, drawn from three parts of the book: it must be correct (Parts II and III), it must be hardened (Part V), and it must be honest about its performance (Part VI). And it must be all three on both architectures, which is the whole point of the volume. The plan is to build it on each, verify every property against the running machine, and read the one place where the naive build falls short.
20.2 The Hardened, ABI-Correct Build
The tool is the digest routine of Section 4.5 (x86-64) or Section 9.2 (AArch64), linked with a small C driver, built with the hardening flags of Part V turned on:
# x86-64 (PIE is the Debian default; add CET and the stack protector)
$ gcc -O2 -fcf-protection -fstack-protector-strong -o grimoire-sum gs.c digest.s
# AArch64 (add branch protection: PAC + BTI)
$ gcc -O2 -fstack-protector-strong -mbranch-protection=standard -o grimoire-sum gs.c digest.s
$ ./grimoire-sum
1b11756f20c6f520 The Programmer's GrimoireBuilt and run on both reference VMs (Debian 13.5, GCC 14.2, GNU Binutils 2.44). Both architectures produce the identical digest 1b11756f20c6f520, the value first computed in Section 5.6 and ported in Section 9.5: the same definition, two machines, one answer.
20.3 The Constant-Time Comparison
If the digest is ever used to authenticate, to decide whether a presented value matches an expected one, the comparison must be the constant-time ct_eq of Section 15.2, never a plain memcmp that returns on the first differing byte. This is the one place the tool touches a secret-dependent decision, and it is exactly where a timing side channel would open. The hardened build is not finished until that comparison is constant-time.
20.4 The Optimization Reality
The honest finding from Part VI stands in the capstone too: the digest cannot be vectorized, because its loop-carried multiply is a dependency chain (Section 17.4), so it runs at roughly 400 MB/s and no rearrangement of instructions will change that. Making it faster is an algorithm decision, hashing independent lanes in parallel, not an assembly one. Recognizing that the tool is at its dependency limit, and not wasting effort hand-tuning a wall, is itself the optimization result.
20.5 The Verification Table
Every property the build claims, checked against the running binary on both architectures. This is the discipline the whole series is built on: a claim is not done until the machine confirms it.
| Property | x86-64 | AArch64 | Verify with |
|---|---|---|---|
| Correct digest (1b11756f20c6f520) | pass | pass | ./grimoire-sum |
| Position-independent (PIE) | DYN | DYN | readelf -h (Type) |
| Non-executable stack | RW | RW | readelf -lW (GNU_STACK) |
| RELRO | yes | yes | readelf -lW (GNU_RELRO) |
Stack canary (-fstack-protector-strong set) | none emitted | none emitted | readelf -s: no __stack_chk_fail |
| Hardware CFI in code | endbr64 | paciasp/autiasp (in the C driver) | objdump -d |
| HW CFI advertised to the loader | no (see below) | no (see below) | readelf -n |
The stack-canary row reads “none emitted” rather than a failure, and the reason is worth seeing. -fstack-protector-strong is set, but the protector is selective: it instruments only functions with a stack buffer or an address-taken local. The hand-written digest has neither, and the thin driver hands its argument straight to the routine, so no function qualifies and no __stack_chk_fail is emitted. The flag is still correct to set as policy (any function that later grows a buffer is guarded automatically); it simply has nothing to protect in this program. That is itself the lesson the table teaches: a mitigation is measured on the finished binary, not assumed from the flag.
The two “advertised: no” rows are the capstone’s deeper lesson, the kind only a full integration reveals, and they are the same lesson on both architectures. The x86-64 build was compiled with -fcf-protection and the AArch64 build with -mbranch-protection=standard, and the C driver duly carries endbr64 on x86 and paciasp on Arm, yet readelf -n shows neither finished binary advertises its control-flow feature to the loader. The reason is identical in both cases: the hand-written digest.s emits no GNU property note, and the linker computes the binary’s properties as the intersection across all input objects, so one object without the note drops the feature for the whole program, silently. The fix is to have the assembly emit the matching .note.gnu.property marking (the x86 IBT/SHSTK feature note on Intel, the BTI/PAC feature note on Arm), as each psABI documents; until it does, mixing hand-written assembly into a hardened build quietly weakens it. Note too that CET is not even a Debian default: Debian’s gcc ships -fcf-protection=none, which is why the x86 build above requests it explicitly. No single chapter would have caught this; assembling the whole did.
A binary advertises its hardware control-flow features to the loader through a GNU property note: x86 feature: IBT, SHSTK for Intel CET, AArch64 feature: BTI, PAC for Arm. The linker keeps a feature only if every input object carries the note, so a hand-written .s file that omits it drops the protection from the entire binary, on both architectures, even though the compiled C objects requested it and the instructions are present. Always check the finished binary with readelf -n, not just the compiler flags, and add the property note to hand-written assembly that links into a hardened program. On Debian, also remember that CET is not a compiler default: pass -fcf-protection explicitly.
20.6 A Look Forward
You have carried one routine from a first naive loop to a hardened, verified, dual-architecture tool, and learned the machine underneath it well enough to read, write, debug, defend, and reason about the speed of real code on the two instruction sets that matter today. The ground keeps moving. On x86, Intel’s APX doubles the general-purpose registers and AVX10 reworks the vector story; on Arm, SVE2 generalizes the vector model the way this book only sketched; and RISC-V, the clean-slate open architecture, is the natural third edition of this volume, where the portable model you now hold meets its purest instruction set. The specifics will change, as the notes at the front promised they would. The skill that does not is the one the whole book taught: when you need to know what the machine does, go to the manual, the ABI, and the disassembly, and check.
Appendices
The field-reference half of the book. These are the pages you open mid-task: the register and calling-convention cards, the syntax cheatsheet, the tool references, the SIMD map, the mitigation and build-flag reference, the syscall tables, the glossary, and the bibliography. Each is built to be read on its own, away from the chapter that introduced it.
Appendix ARegister and Calling-Convention Cards (x86-64 System V, AArch64 AAPCS64)
Paired one-page cards: the x86-64 general-purpose and vector registers with the System V argument, return, and preserved roles; and the AArch64 registers with the AAPCS64 roles. The two are laid out in the same shape so a reader can map one to the other at a glance. Condensed from Chapter 5, Chapter 8, and Chapter 19.
Paired quick-reference cards for the two calling conventions, condensed from Chapter 5, Chapter 8, and Chapter 19, laid out in the same shape so one maps onto the other.
| Register | Role |
|---|---|
rdi rsi rdx rcx r8 r9 | integer/pointer arguments 1 to 6 |
rax | return value (and rdx for the high 64 bits) |
xmm0–xmm7 | floating-point/vector arguments; xmm0 returns |
rbx rbp r12 r13 r14 r15 | callee-saved |
r10 r11 and the argument regs | caller-saved |
rsp | stack pointer (16-byte aligned at a call) |
| Register | Role |
|---|---|
x0–x7 | integer/pointer arguments; x0 (and x1) return |
v0–v7 | floating-point/vector arguments and return |
x19–x28 | callee-saved |
x9–x15 | caller-saved temporaries |
x29 / x30 | frame pointer / link register |
sp / xzr | stack pointer (16-byte aligned) / zero register |
Appendix BAT&T vs Intel Syntax Cheatsheet
The one-page version of Table 3.1: operand order, sigils, size suffixes, and memory-reference forms, with a column of worked examples so either syntax can be read at speed during disassembly.
The mechanical differences between the two x86 syntaxes, the one-page form of Table 3.1 (Section 3.4), for reading either at speed.
| Aspect | AT&T | Intel |
|---|---|---|
| Operand order | source, destination | destination, source |
| Registers | %rax | rax |
| Immediates | $42 | 42 |
| Size | mnemonic suffix (movq) | implied or keyword (qword) |
| Memory | disp(base,index,scale) | [base+index*scale+disp] |
| Example | movq $42, %rdi | mov rdi, 42 |
Appendix Cgdb, objdump, and readelf Command Reference
The commands used throughout the book, grouped by task: disassembling, inspecting ELF structure, stepping at the instruction level, examining registers and memory, and checking which mitigations a binary was built with. Drawn from Parts IV and V.
The inspection and debugging commands used through the book, grouped by task (Parts IV and V).
| Task | Command |
|---|---|
| Disassemble (AT&T / Intel) | objdump -d / objdump -M intel -d |
| ELF header (type, entry, machine) | readelf -h |
| Segments (NX stack, RELRO) | readelf -lW |
| Relocations (GOT/PLT) | readelf -r |
| GNU properties (CET, BTI/PAC) | readelf -n |
| Break and inspect a register | break fn; run; x/s $rdi; p/d $rsi |
| Step one instruction | stepi / nexti; layout asm |
| Mitigation summary (if installed) | checksec --file=./a.out |
Appendix DSIMD Instruction-Family Map (SSE/AVX/AVX-512 and NEON/SVE2)
A correspondence table of the common SIMD operations across the x86 and Arm vector families, so a kernel written for one can be found in the other. Condensed from Chapter 17.
SIMD and floating-point correspondence across the two families, the field-reference form of Table 19.3 (Section 19.4).
| Concept | x86 | AArch64 |
|---|---|---|
| Vector register | xmm/ymm/zmm (128/256/512) | v/q (128); SVE2 scalable |
| Scalar double add | addsd %xmm1,%xmm0 | fadd d0,d0,d1 |
| Packed 4-float add | addps / vaddps | fadd v0.4s,v0.4s,v1.4s |
| Packed integer add | vpaddq %ymm.. | add v0.2d,v0.2d,v1.2d |
| int↔double | cvtsi2sd/cvttsd2si | scvtf/fcvtzs |
Appendix EMitigation and Build-Flag Reference
How to turn on, and how to verify, each protection from Part V: the compiler and linker flags for PIE, stack canaries, RELRO, CET, and BTI, and the readelf and checksec incantations that confirm them on the finished binary.
How to enable and how to verify each protection from Part V; the flags are GCC/Clang, the checks are on the finished binary.
| Protection | Build flag | Verify with |
|---|---|---|
| Position-independent executable | -fPIE -pie (default) | readelf -h shows Type: DYN |
| Stack canary | -fstack-protector-strong | __stack_chk_fail in readelf -s |
| Full RELRO | -Wl,-z,relro,-z,now | GNU_RELRO in readelf -lW |
| Non-executable stack | default (avoid -z execstack) | GNU_STACK flags RW |
| Intel CET (IBT/SHSTK) | -fcf-protection (not a Debian default; pass explicitly, and add the property note to hand-asm) | endbr64; readelf -n |
| Arm PAC/BTI | -mbranch-protection=standard | readelf -n (note: hand-asm must carry the property note) |
Appendix FLinux Syscall Quick Tables (x86-64 and AArch64)
The common Linux system calls with their per-architecture numbers and argument registers for both x86-64 and AArch64, with the warning from the Standard in Section 3.2 repeated: confirm a number for your architecture rather than transcribing it from memory.
The common Linux system calls with their per-architecture numbers (verified from the kernel headers on the reference VMs) and the calling convention for each. The numbers differ by architecture; confirm against the kernel unistd tables rather than transcribing from memory.
| Call | x86-64 | AArch64 |
|---|---|---|
read | 0 | 63 |
write | 1 | 64 |
openat | 257 | 56 |
exit | 60 | 93 |
exit_group | 231 | 94 |
| number in | rax | x8 |
| arguments | rdi rsi rdx r10 r8 r9 | x0–x5 |
| trap instruction | syscall | svc #0 |
Appendix GGlossary
The defined terms marked through the book (instruction set architecture, microarchitecture, register, word, endianness, alignment, stack frame, relocation, and the rest), each with a one-line definition and a pointer to the section that introduces it.
The terms defined through the book, each with a one-line gloss and the section that introduces it.
| Term | Meaning | Section |
|---|---|---|
| Instruction set architecture (ISA) | the contract defining a processor’s registers, instructions, and encodings | 1.3 |
| Microarchitecture | a specific silicon implementation of an ISA; sets speed, not meaning | 1.3 |
| Machine code | the bytes a processor decodes and executes directly | 1.1 |
| Register | a small, named, very fast storage slot inside the core | 2.2 |
| Word | the natural integer size; 64 bits on both architectures here | 2.2 |
| Endianness | the order of the bytes of a multi-byte value in memory (little-endian here) | 2.3 |
| Alignment | placing a value at an address that is a multiple of its size | 2.3 |
| Stack frame | the block of stack a function uses for its return address, saved registers, and locals | 5.5 |
| Load/store architecture | a design where arithmetic is register-only and memory is touched only by loads and stores | 7.2 |
| Link register | the AArch64 register (x30) holding a call’s return address | 8.2 |
| Zero register | the AArch64 register reading as 0 and discarding writes (xzr/wzr) | 7.1 |
| Position-independent executable (PIE) | a program that runs at any load address, enabling ASLR | 12.3 |
| GOT / PLT | the tables that resolve and dispatch dynamically linked calls | 12.4 |
| Latency / throughput | cycles for one result / independent results per cycle | 16.2 |
| SIMD | one instruction operating on several packed values at once | 17.1 |
| Constant-time code | code whose timing does not depend on secret data | 15.1 |
Appendix HReferences
The primary sources the book stands on, with document numbers and the revisions consulted: the Intel SDM (325462) and Optimization Reference Manual (248966), the AMD64 APM (24592–26569), the Arm Architecture Reference Manual (DDI 0487), the System V psABIs for x86-64 and AArch64, the GNU Binutils and NASM manuals, the relevant Linux kernel documentation and syscall(2), and the Intel and Arm security and timing guidance. Every Standard callout in the book cites into this list.
The primary and authoritative sources the book stands on. These are the records to check a claim against; the version numbers in the text age, these documents are where the current truth lives.
ISA specifications. Intel 64 and IA-32 Architectures Software Developer’s Manual (Intel, document 325462); AMD64 Architecture Programmer’s Manual (AMD, 24592–26569); Arm Architecture Reference Manual for A-profile (Arm, DDI 0487); The RISC-V Instruction Set Manual (RISC-V International).
Application binary interfaces. System V Application Binary Interface, AMD64 Architecture Processor Supplement (the x86-64 psABI, gitlab.com/x86-psABIs/x86-64-ABI); Arm Procedure Call Standard for the Arm 64-bit Architecture, AAPCS64, and the Arm ABI documents (github.com/ARM-software/abi-aa); the ELF generic ABI.
Assemblers and toolchain. The GNU Assembler (as) manual and GNU Binutils documentation (sourceware.org/binutils); the NASM manual (nasm.us).
Operating-system interface. The Linux man-pages, syscall(2) for the per-architecture calling conventions, and the kernel unistd tables for the numbers (man7.org, kernel.org).
Security mechanisms. Linux kernel documentation for Intel CET shadow stack, AArch64 pointer authentication, and the memory tagging extension (docs.kernel.org/arch); Intel Data Operand Independent Timing guidance and the Guidelines for Mitigating Timing Side Channels Against Cryptographic Implementations (intel.com); the Arm Architecture Reference Manual for PAC, BTI, MTE, and DIT; NIST FIPS 140-3 and the Cryptographic Module Validation Program (csrc.nist.gov).
Optimization references. The Intel 64 and IA-32 Optimization Reference Manual and the AMD Software Optimization Guide; Agner Fog’s instruction tables and microarchitecture manuals (agner.org/optimize) and the uops.info database, the de facto measured references.
Errata and Updates
This guide is corrected continuously, and you are part of how that happens. If you find an error, a claim that no longer matches its primary source, a command or listing that does not behave as printed, or anything that has simply gone stale, report it to [email protected]. Name the section, and where you can, the authority that settles it (the manual and revision, or the disassembly that proves it); that is exactly how the book is verified in the first place, and a good report can go straight into the next revision.
The current, corrected version always lives at https://gregvogt.net/grimoire/. Each edition was correct as of the revision date printed on its cover, and claims nothing beyond it: architectures gain extensions, toolchains update, and the page in front of you ages from the day it ships. When a detail matters, check it against the latest revision there, and against the primary source it cites, before you rely on it.
How to Cite This Guide
Because this is a living document, cite the revision you used and where you found it, so that a reader can retrieve the same text you saw. The revision is printed on the cover.
Vogt, Greg. Writing, Hardening & Optimizing Assembly. The Programmer’s Grimoire. Revision v1.0-RC1 · June 2026. https://gregvogt.net/grimoire/assembly/
For LaTeX and reference managers:
@misc{grimoire-assembly,
author = {Vogt, Greg},
title = {Writing, Hardening & Optimizing Assembly},
series = {The Programmer's Grimoire},
edition = {Revision v1.0-RC1},
year = {2026},
url = {https://gregvogt.net/grimoire/assembly/}
}License and Reuse
The Programmer’s Grimoire is published free of charge and licensed to you under a Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0). You are free to read, copy, share, and adapt or translate it, in any medium or format, for any non-commercial purpose, on one condition: give appropriate credit to the author, link to the license, and indicate whether you changed anything. You may not use the material for commercial purposes. The full terms are at https://creativecommons.org/licenses/by-nc/4.0/.
The intent is plain. The knowledge is meant to be free for anyone to read, copy, and translate, and the non-commercial term is what keeps it that way, so that no one else fences it off or resells it. A paid edition, where one exists, comes from the author and exists only to support the work; the knowledge itself is not the thing being sold.
Trademark and brand. The name The Programmer’s Grimoire, the series wordmark, and the look and branding of these guides are trademarks of Greg Vogt and are not part of the content license above. Reusing the licensed text, including in a translation, grants no right to the Grimoire name or brand. You may not present your version as an official Grimoire, use the name or wordmark to label, endorse, or promote a derivative or third-party work, or otherwise imply that the author stands behind it. Credit the original by name, which is the attribution the license requires, but publish your version under your own title.
Colophon
Each guide is a single HTML document with an external stylesheet and a small progressive-enhancement script, and no inline style or script at all, so it satisfies a strict Content-Security-Policy. Three formats are built from that one source: the PDF with WeasyPrint, the EPUB with EbookLib, and the Kindle AZW3 with Calibre’s ebook-convert. What you read on screen, on paper, and on an e-reader is the same text rendered three ways.
The reading text is set in Georgia, with the bundled Literata as the press fallback; display headings, numerals, and labels are set in Cinzel, code and the interface in JetBrains Mono (with a bundled fallback face for full glyph coverage), and the Grimoire wordmark in UnifrakturCook. On screen the reader can switch the prose to Atkinson Hyperlegible or OpenDyslexic, scale the type, adjust line spacing, and toggle dark mode; the print and e-reader builds stay in the typeset faces. The bundled fonts are under the SIL Open Font License.
How it was made is described in the notes at the front, and is the point as much as the prose. First drafts are generated by an AI (Claude, made by Anthropic) and then verified, line by line, against primary sources by a human before anything ships. Every factual claim is tracked in a per-volume claims ledger and re-checked against the living manuals on each revision, which is why a guide carries a revision date, and why that date is load-bearing.
