Skip to main content
Be Bitwise
x86 AssemblyLinking & C Interop

Inline Assembly in C

Sometimes you only need a couple of instructions in asm. Spinning up a separate .asm file is overkill. GCC lets you splice assembly straight into C — that's inline assembly, and it shows up everywhere from kernel internals to crypto libraries to anywhere the compiler's codegen falls short.

Basic Inline Assembly

The simplest form uses the __asm__ keyword (or just asm with GNU extensions):

c
#include <stdio.h>
int main(void) {
int result;
__asm__ (
"mov $42, %%eax\n\t" // move 42 into eax
"add $8, %%eax" // add 8 to eax
: "=a" (result) // output: eax -> result
);
printf("Result: %d\n", result); // prints 50
return 0;
}

See those double %% in front of the register names? A single % already means "operand reference" inside GCC inline asm (%0, %1, and so on), so to get an actual literal register name through, you double up.

AT&T vs Intel Syntax

Out of the box, GCC inline asm speaks AT&T syntax: source first, $ on immediates, % on registers. If your eyes prefer Intel, you can switch:

c
// AT&T syntax (default)
__asm__ ("movl $42, %%eax" : "=a" (result));
// Intel syntax (with dialect toggle)
__asm__ (".intel_syntax noprefix\n\t"
"mov eax, 42\n\t"
".att_syntax prefix"
: "=a" (result));

The toggle only covers your own text: operands GCC substitutes (%0, %1) still come out in AT&T form, and the trailing .att_syntax breaks things if the file is compiled with -masm=intel. GCC has no per-statement dialect attribute. The supported options are compiling the whole file with -masm=intel, or writing both spellings in one template as {att|intel} alternatives, for example "{movl $7, %0|mov %0, 7}", and letting GCC pick the one that matches.

Extended Assembly: Constraints and Operands

Extended inline assembly has four parts separated by colons:

c
__asm__ (
"assembly template"
: output operands // results written by the assembly
: input operands // values read by the assembly
: clobber list // registers/memory modified as side effects
);

Output constraints tell GCC where to find the result:

ConstraintMeaning
"=r"Any general-purpose register (GCC chooses)
"=a"Specifically eax / rax
"=b"Specifically ebx / rbx
"=c"Specifically ecx / rcx
"=d"Specifically edx / rdx
"=m"A memory location
"=S"Specifically esi / rsi
"=D"Specifically edi / rdi

Input constraints use the same letters without =:

c
int add_asm(int a, int b) {
__asm__ (
"addl %1, %0" // a += b
: "+r" (a) // %0: a, read and written ("+" means in/out)
: "r" (b) // %1: b in any register
: "cc" // add changes the flags
);
return a;
}

A common first attempt adds into the input register (addl %2, %1) and then copies it to a separate "=r" output. That breaks the contract: GCC assumes asm never changes a plain input operand, so it may still treat that register as holding a afterwards. It can also give the output the same register as b, because a plain "=r" output is assumed to be written only after every input has been read. The "+r" constraint says "this operand is read and written", which is what actually happens. When an output really is written before all inputs are consumed, mark it early-clobber with "=&r".

Clobber Lists

The clobber list is your honesty form. It tells GCC which registers your asm trashes beyond the declared outputs, so GCC knows not to park live values in them.

c
void cpuid_example(void) {
unsigned int eax, ebx, ecx, edx;
__asm__ (
"cpuid"
: "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) // outputs
: "a" (1) // input: eax = 1
// no clobber needed: all modified registers are declared as outputs
);
printf("CPU features: edx=0x%x, ecx=0x%x\n", edx, ecx);
}

Common clobber entries:

  • "cc" - the condition codes (flags register) are modified
  • "memory" - memory is read or written (prevents reordering around the asm)
  • "rcx", "r11" - specific registers (e.g., clobbered by syscall)

Making a Syscall from Inline Assembly

Here's a real-world example. A direct sys_write from C, no libc in the middle:

c
#include <stddef.h>
long sys_write(int fd, const char *buf, size_t count) {
long ret;
__asm__ volatile (
"syscall"
: "=a" (ret) // output: rax = return value
: "a" (1), // input: rax = 1 (sys_write)
"D" (fd), // input: rdi = fd
"S" (buf), // input: rsi = buf
"d" (count) // input: rdx = count
: "rcx", "r11", "memory" // clobbered by syscall
);
return ret;
}

The volatile keyword warns GCC that this asm has side effects, so it shouldn't be moved around or optimised out. Skip it and GCC will happily delete your syscall if it decides the return value is unused.

Memory Barriers and volatile

A "memory" clobber acts as a compiler-level memory barrier. GCC won't reorder loads or stores across the asm. You need this whenever concurrency or hardware is involved — without it, the compiler will happily shuffle accesses out of order for speed.

c
// Compiler barrier: prevents reordering of memory operations
__asm__ volatile ("" ::: "memory");
// CPU memory barrier: orders all earlier loads and stores before later ones
__asm__ volatile ("mfence" ::: "memory");

mfence orders memory accesses, and that's all. It isn't a serialising instruction in Intel's sense (it doesn't wait for every earlier instruction to finish or flush the pipeline); for that you'd reach for cpuid, or lfence, which on Intel CPUs stops later instructions from starting until earlier ones complete.

When to Use Inline Assembly

Legitimate reasons to reach for inline asm:

  • Syscalls: raw syscall access with no libc in the way
  • CPUID and hardware queries: pulling CPU feature flags, performance counters
  • Atomic operations: building lock-free data structures
  • Cryptographic primitives: AES-NI, SHA, dedicated instructions
  • Hot inner loops: when the compiler stubbornly emits worse code than you'd write by hand
Inline Assembly Is a Last Resort

Inline asm is sharp on every edge. It sidesteps type checking, register allocation, and optimisation passes. It nukes portability and makes future-you weep when reading the code. Before you reach for it, check whether a compiler built-in (__builtin_*), an intrinsic (_mm_*), or a libc function would do. If the compiler is genuinely wrong, file the bug. Only drop into inline asm when there really is no way around it.

Security Perspective: Inline Assembly Bypasses Compiler Safety

Drop into inline asm and you walk out from under several compiler safety nets:

  1. Stack canaries: The compiler injects canary checks into C functions automatically. Inline asm can mess with the stack in ways the compiler never anticipated, and a carefully built block can stomp the canary without the surrounding check ever firing.

  2. Bounds checking: Sanitizers like AddressSanitizer (ASan) instrument the loads and stores the compiler emits. Anything that happens inside an inline asm block is dark to them.

  3. Type safety: The compiler can't verify that your asm respects the types and sizes it sees in C. An "=r" on an int won't stop the instructions inside from writing 8 bytes into a 4-byte slot.

  4. Optimisation assumptions: GCC plans optimisations around the constraints you declare. Forget to list a clobbered register and GCC may have parked a live value there. Your asm silently nukes it.

c
// BUG: modifies rbx but doesn't declare it as clobbered
__asm__ ("mov $0, %%rbx" : : : /* missing "rbx" clobber */);
// GCC might have stored a critical value in rbx -> silent corruption

Inline asm is the escape hatch from compiler safety. Use it sparingly, list every clobber honestly, and test like you mean it.

What is Next

The last lesson in this module digs into position-independent code (PIC). It's required for shared libraries and the bedrock that ASLR — the memory-layout randomisation mechanism — sits on top of.