Gadgets and Gadget Hunting
A gadget is a short run of machine instructions that ends with ret. Gadgets are the bricks of Return-Oriented Programming — each one does one tiny job (load a register, run some arithmetic, write to memory), and ret shoves control to the next gadget waiting on the stack. Chain enough of them and you can compute anything, all from code that was already shipped in the process.
For the theoretical catalog of gadget types, see Gadgets and the Gadget Catalog.
What Makes a Gadget
A gadget has two qualifying properties:
- It does something useful — moves data around, computes values, fires syscalls
- It ends in
ret— so the stack drives what runs next
ret is what makes the whole thing tick. It pops the next value off the stack into rip, so the stack itself becomes the "program" that sequences gadget execution. Each ret is a goto whose target is read from the stack.
; Example gadgets (each is a complete gadget):
; "pop rdi" gadget -- loads a stack value into rdipop rdi ; 5fret ; c3
; "pop rsi; pop r15" gadget -- loads two stack valuespop rsi ; 5epop r15 ; 41 5fret ; c3
; "mov [rdi], rax" gadget -- writes rax to memory at address in rdimov qword [rdi], rax ; 48 89 07ret ; c3
; "xor rax, rax" gadget -- zeros raxxor rax, rax ; 48 31 c0ret ; c3
; "syscall" gadget -- invokes a system callsyscall ; 0f 05ret ; c3Gadget Categories
Gadgets sort into a handful of functional families:
Register load gadgets - move data from the stack into registers:
pop rdi; ret ; load rdi from stackpop rsi; ret ; load rsi from stackpop rdx; ret ; load rdx from stackpop rax; ret ; load rax from stackpop rcx; ret ; load rcx from stackMemory write gadgets - store values into memory:
mov [rdi], rax; ret ; write rax to address in rdimov [rdi], esi; ret ; write esi to address in rdistosb; ret ; write al to [rdi], increment rdiArithmetic gadgets - perform computation:
add rax, rcx; ret ; rax += rcxsub rax, rdx; ret ; rax -= rdxxor rax, rax; ret ; rax = 0inc rdi; ret ; rdi++neg rax; ret ; rax = -raxSystem call gadgets - invoke the kernel:
syscall; ret ; make syscall and returnint 0x80; ret ; legacy 32-bit syscallControl flow gadgets - conditional branching within a chain:
; Less common but powerful:cmp rax, rbx; cmove rcx, rdx; ret ; conditional movejmp rax ; indirect jump (not ret-based)call rax ; indirect callA big enough binary carries enough gadget variety to compute anything. Throw in register loads, memory writes, arithmetic, and conditional moves and ROP becomes Turing-complete — loops, conditionals, arbitrary algorithms, all addressable. Research has even produced compilers that translate high-level programs straight into ROP chains. That's the kicker: ROP turns the defender's own code into an attack platform.
Intended vs Unintended Gadgets
Intended gadgets come from real instruction boundaries. The compiler emitted pop rdi; ret as part of a function epilogue, and we co-opt it as a gadget.
Unintended gadgets are an artefact of x86's variable-length encoding. Because instructions range from 1 to 15 bytes, you can start decoding at any byte offset and the CPU will gamely treat whatever it finds as instructions. Begin halfway through one instruction and you can surface an entirely different sequence.
A concrete example. Take a single instruction that loads a constant:
; Original instruction at address 0x401234:; b8 5f c3 90 90 mov eax, 0x9090c35f
; Start decoding 1 byte later (at 0x401235), inside the immediate:; 5f pop rdi (unintended!); c3 ret; 90 90 never reached -- ret already jumped awayDecoding from the middle of that mov surfaces pop rdi; ret — two bytes (5f c3) that live inside the immediate operand, not at any instruction boundary the compiler laid down. The programmer wrote one instruction; the attacker found a gadget hiding in its constant. Any immediate, address, or offset that happens to contain 5f c3 (or 5d c3, 5e c3, and so on) spawns gadgets like this.
The well runs deep because the ret opcode (0xc3) shows up inside countless larger instructions:
; The byte c3 appears in many contexts:; mov ebx, 0xc3c3c3c3 -- c3 appears in the immediate value; add al, 0xc3 -- c3 is the immediate operand; Any address or constant containing c3 creates potential gadget endpointsTry it below. Step the start offset one byte at a time through the mov above and watch pop rdi; ret appear at +1, then switch to the other samples, where a c3 hiding in a ModRM byte or a compare's constant hands you gadgets the compiler never meant to write.
Gadget finder
Pick a byte to start decoding from. x86 instructions are 1 to 15 bytes long and can start at any byte, so a different start gives a different instruction stream.
The lesson's example: one mov whose 32-bit immediate is 0x9090c35f. Stored little-endian, its first two immediate bytes are 5f c3.
Bytes (click one to start there)
The compiler’s instructions
Decoded from +0
+0 is where one of the compiler's instructions starts.
No gadget. No ret in this stream, so control never comes back to the chain.
| Address | Bytes | Instruction |
|---|---|---|
| 0x401234 | b8 5f c3 90 90 | mov eax, 0x9090c35f |
Every gadget in these bytes
Addresses are illustrative. Decodings are LLVM’s (llvm-mc, Intel syntax). Gadget finders cap how far back from each ret they look; this list marks anything longer than 5 instructions.
Why x86 has these and Arm64 doesn’t
An x86 CPU decodes from wherever rip points. Instructions run from 1 to 15 bytes with no alignment rule, so every byte offset is a possible start, and immediates, displacements and ModRM bytes are all just bytes the decoder may read as opcodes. Any c3 in the code section is a potential ret.
Arm64 instructions are always 4 bytes and must sit on 4-byte boundaries. A branch to a misaligned address faults, so there’s no way to start halfway through an instruction. An attacker gets the gadgets the compiler actually emitted (epilogues ending in ret, indirect branches) and little else, which is why Arm64 gadget lists are much shorter for the same amount of code.
Finding Gadgets with ROPgadget
ROPgadget is the workhorse of automated gadget search:
# Installpip install ropgadget
# Find all gadgets in a binaryROPgadget --binary ./target
# Search for specific patternsROPgadget --binary ./target | grep "pop rdi"ROPgadget --binary ./target | grep "pop rsi"ROPgadget --binary ./target | grep "syscall"
# Search in shared libraries tooROPgadget --binary /lib/x86_64-linux-gnu/libc.so.6 | grep "pop rdi"Sample output:
0x0000000000401233 : pop rdi ; ret0x0000000000401231 : pop rsi ; pop r15 ; ret0x000000000040119c : ret0x0000000000401236 : pop rbp ; ret0x0000000000401010 : pop rdx ; retFinding Gadgets with ropper
ropper is the other heavy hitter, with a more interactive feel:
# Installpip install ropper
# Interactive moderopper --file ./target
# Search for specific gadgetsropper --file ./target --search "pop rdi"ropper --file ./target --search "mov [rdi]"
# Find gadgets for a specific purposeropper --file ./target --search "pop rdi; pop rsi"Manual Gadget Hunting
You can do it by hand too: scan for ret (0xc3) bytes and disassemble backwards from each one:
# Find all 0xc3 bytes in the .text sectionobjdump -d -M intel ./target | grep 'c3' | head -20
# Or use a Python script to scan backward from each c3 bytepython3 -c "import subprocess# Read the binarywith open('./target', 'rb') as f: data = f.read()
# Find all c3 (ret) bytesfor i, b in enumerate(data): if b == 0xc3: # Try disassembling 1-6 bytes before c3 for length in range(1, 7): start = i - length if start < 0: continue chunk = data[start:i+1] # Disassemble with a tool or capstone library print(f'Potential gadget at offset 0x{start:x}: {chunk.hex()}')"This only prints candidate byte runs; it doesn't tell you what they decode to. To know whether 48 31 c0 c3 is really xor rax, rax; ret (and not a run that straddles a longer instruction), feed each chunk through a disassembler — the capstone library is the usual choice — and keep only the ones that decode cleanly end to end. That's exactly the validation ROPgadget and ropper do for you.
The Gadget Supply in Real Binaries
How many gadgets are out there depends on how much code is loaded:
- Small static binary (100KB): hundreds of gadgets
- Dynamically linked binary + libc (2MB): tens of thousands
- Large application + libraries (10MB+): hundreds of thousands
libc on its own is a goldmine — register loads, memory writes, arithmetic, syscall invocations, basically every gadget shape you'd want.
ROP Chain Layout
pop rdi; ret
pop rsi; pop r15; ret
xor eax, eax; ret
syscall; ret
Gadgets You Almost Always Need
For a basic execve("/bin/sh") ROP chain on x86-64, here's the shopping list:
; Required gadgets:pop rdi; ret ; to set rdi = address of "/bin/sh"pop rsi; ret ; to set rsi = 0 (NULL argv)pop rdx; ret ; to set rdx = 0 (NULL envp) -- sometimes hard to findpop rax; ret ; to set rax = 59 (execve syscall number)syscall; ret ; to invoke the syscall
; If you cannot find "pop rdx; ret", alternatives:xor rdx, rdx; ret ; zero rdx; Or look for: pop rdx; pop r12; ret (accept the extra pop)pop rdx; ret is famously scarce in a small program binary — rdx is caller-saved, so a compiler rarely has reason to pop it in the code it emits for your .text. Link against libc, though, and the picture changes: libc is large enough to carry plenty of pop rdx gadgets (often as part of longer sequences). So the shortage bites mostly when you're confined to a stripped, statically small target.
The pop r15 Problem
Common headache: plenty of binaries hand you pop rsi; pop r15; ret and zero copies of plain pop rsi; ret. The classic culprit was GCC's __libc_csu_init epilogue:
; From __libc_csu_init (glibc < 2.34, e.g. Ubuntu 20.04 and earlier):pop rbxpop rbppop r12pop r13pop r14pop r15retglibc 2.34 (Ubuntu 22.04, current Debian) removed __libc_csu_init, so this exact gadget source is gone on recent systems — one reason modern chains lean more on libc gadgets, one_gadget, or SROP. Where it is present, different starting offsets through the sequence give you a stack of useful gadgets, but some hand you "extra" pops for registers you couldn't care less about. When you use pop rsi; pop r15; ret, just stack a junk value where r15 will land:
payload += struct.pack('<Q', pop_rsi_r15_ret) # gadget addresspayload += struct.pack('<Q', 0) # value for rsipayload += struct.pack('<Q', 0xdeadbeef) # dummy value for r15 (don't care)What is Next
Gadgets are no longer mysterious — what they are, where they come from, how to surface them. The next lesson shows you how to braid them together into a full ROP payload: a "program written on the stack" that calls execve (or anything else) using nothing but the code already loaded.