Systems Security & Exploitation

a gadget

If a ROP chain is a sentence the attacker writes by gluing words together, a gadget is one of those words — a short, already-existing run of machine instructions that ends in a ret (or, for jump-oriented programming, an indirect jump). The attacker does not write these; they FIND them, scattered throughout the program and its libraries, like finding usable phrases in a newspaper.

Concretely, a gadget is an address pointing at a few instructions followed by a return, where those instructions perform one small useful effect. Common shapes include 'pop rdi; ret' (load the next stack value into rdi), 'pop rax; ret', 'mov [rdi], rsi; ret' (a memory write), 'add rsp, 0x18; ret' (adjust the stack), or 'syscall; ret'. The attacker scans the binary with a gadget finder and collects a toolbox of these. A subtle and powerful trick on x86, where instructions have variable length, is the UNINTENDED gadget: by jumping into the MIDDLE of a longer instruction, the same bytes decode into a completely different, useful instruction the programmer never wrote — so a binary contains far more gadgets than it has intended instructions.

It matters because the supply and quality of gadgets determine whether an exploit is feasible: an attacker needs gadgets that, chained, can set up arguments and reach a system call. The honest framing: a single gadget does almost nothing — its power comes only from being one link in a chain, and the ret at its end is what passes control to the next gadget. This is also why defenses that constrain ret targets (Control-Flow Integrity, shadow stacks) and why removing 'ret' byte patterns (a research idea called gadget elimination) attack the gadget supply directly.

0x401abc: 5f pop rdi ; intended 0x401abd: c3 ret // unintended: jumping to 0x401abe inside a 'mov eax, 0x0fc3...' may decode as 0x401ac1: ff e0 jmp rax ; a gadget the author never wrote

Variable-length x86 encoding lets the same bytes decode differently when entered mid-instruction — an unintended gadget.

Most useful gadgets end in 'ret'; the value of a gadget is entirely in chaining, which is why CFI and shadow stacks (constraining where a ret may go) blunt the whole technique rather than any one gadget.

Also called
ROP gadgetinstruction snippetROP 小工具指令片段