Back to Blog
Adversarial Machine Learning

ROP Chains 101: Practical Return-Oriented Programming for Vulnerability Researchers

OffSec Research Team
10 June 2026 • 09:00 AM16 min
ROP Chains 101: Practical Return-Oriented Programming for Vulnerability Researchers
TL;DR — Return-Oriented Programming (ROP) is how you compute without injecting code. When Data Execution Prevention (DEP/NX) forbids running your shellcode, ROP reuses the executable code already in the process — short instruction sequences ("gadgets") ending in ret — chaining them via a stack you control to perform arbitrary computation. This article builds ROP from first principles: why DEP created it, what a gadget is, how the stack drives the chain, finding gadgets, the canonical "call VirtualProtect/mprotect then run shellcode" pattern, the stack-pivot problem, and how ASLR, CFG, and CET shadow stacks fight back.

Executive Summary

Once upon a time, exploitation was simple: overflow a buffer, overwrite the return address to point at shellcode you placed on the stack, and the CPU executed it. Then DEP arrived and marked the stack and heap non-executable. Your shellcode is still there in memory — but the moment the CPU tries to execute it, the page is NX and the process crashes. Injecting code no longer works.

ROP is the answer to a precise question: if I can't inject and run my own code, how do I run arbitrary logic using only code that's already mapped executable? The answer is that the program — and every library it links (libc, ntdll, kernel32) — already contains millions of bytes of executable instructions. Scattered throughout are short sequences that end in a ret. If you control the stack, you control where each ret goes. By laying out a sequence of addresses on the stack, you make the CPU "return" from one useful snippet to the next, stitching them into a program of your design. You aren't injecting code; you're injecting control flow.

This is why ROP is foundational: nearly every modern memory-corruption exploit on a DEP-enabled target passes through a ROP stage, even if only briefly, to flip a memory region executable so real shellcode can finally run.

The Insight: ret Is a Jump You Control

The ret instruction does two things: it pops the value at the top of the stack into the instruction pointer and continues execution there. In normal programs the stack top holds a legitimate return address. But in an exploit where you control the stack contents, ret becomes "jump to whatever address I placed here, then advance the stack pointer."

diagram — rendering…
flowchart TD
    A["CPU executes a gadget<br/>(a few useful instructions)"] --> B["Gadget ends in RET"]
    B --> C["RET pops next address<br/>off the attacker-controlled stack"]
    C --> D["IP jumps to the next gadget"]
    D --> A
    style C fill:#2a0c14,stroke:#ef233c,color:#fee2e2

So a controlled stack is effectively a program, where each entry is "the address of the next instruction-snippet to run." The stack pointer is the program counter of your meta-program; ret is its "step" instruction.

What Is a Gadget?

A gadget is a short sequence of machine instructions, present in executable memory, that ends in a ret (or a controllable indirect branch). Each gadget does a tiny amount of useful work, then returns control to your chain.

text
EXAMPLE GADGETS (x86-64) pop rdi ; ret              -> load attacker value into RDIpop rsi ; ret              -> load attacker value into RSIpop rax ; ret              -> load attacker value into RAXmov [rdi], rax ; ret       -> arbitrary write: *RDI = RAXadd rsp, 0x20 ; ret        -> adjust stack (alignment / skip)xchg rax, rsp ; ret        -> stack pivotsyscall ; ret              -> invoke a syscall with set-up registers

Crucially, gadgets need not be instructions the original programmer intended. On x86, instructions are variable-length and unaligned, so by jumping into the middle of an instruction you can decode entirely different instructions than the compiler emitted. The byte 0xC3 (ret) appears constantly inside larger instructions and constants, so the supply of gadgets in any sizeable binary is enormous. ROP composition is the art of selecting gadgets whose side effects, taken together, perform your computation.

Anatomy of a Chain

Suppose you want to call system("/bin/sh") on x86-64, where the first argument goes in RDI. You need to: put the address of the "/bin/sh" string into RDI, then jump to system. Two gadgets and some data:

text
STACK LAYOUT (low -> high address, consumed by RETs in order) [ overflow padding ...               ][ addr_of( pop rdi ; ret )           ]  <- first RET lands here[ addr_of "/bin/sh" string           ]  <- popped into RDI[ addr_of( system )                  ]  <- next RET jumps to system[ addr_of( exit ) or junk            ]  <- system's "return address"

Execution walk-through:

  • The vulnerability overwrites the saved return address with the address of pop rdi ; ret. The function returns → CPU starts executing that gadget.
  • pop rdi pops the next stack value (addr "/bin/sh") into RDI. ret pops the next value — the address of system — into IP.
  • CPU jumps to system, which reads its first argument from RDI (our string). Shell spawns.

That is a complete, if minimal, ROP chain. Real chains are longer because they must set multiple registers, handle stack alignment (the x86-64 ABI wants 16-byte alignment before a call), and often marshal a full function-call ABI.

The Canonical Goal: Make Memory Executable Again

Spawning a shell directly via system is the easy case (it needs a libc with a convenient function). On Windows and in hardened Linux exploits, the standard ROP objective is to defeat DEP by flipping a memory region to executable, then jump to real shellcode there. The chain marshals a call to a memory-protection API:

PlatformFunctionWhat the chain sets up
WindowsVirtualProtect(addr, size, PAGE_EXECUTE_READWRITE, &old)4 args (stdcall/x64 fastcall), then jump to addr
WindowsVirtualAllocAllocate RWX, copy shellcode, jump
Linux`mprotect(addr, len, PROT_READ\WRITE\EXEC)`rdi/rsi/rdx via pop gadgets, then syscall
Linuxexecve("/bin/sh",0,0) via syscallrax=59, rdi=ptr, rsi=rdx=0, syscall
diagram — rendering…
sequenceDiagram
    participant V as Vulnerability (stack control)
    participant R as ROP chain
    participant K as Kernel / API
    V->>R: RET into first gadget
    R->>R: pop registers to set args (addr, size, RWX)
    R->>K: call VirtualProtect / mprotect
    K-->>R: region now executable
    R->>R: RET into the now-executable shellcode
    Note over R: DEP defeated — native shellcode runs

The beauty is that the ROP chain itself is data on a non-executable stack — DEP allows it, because no data is being executed; only the legitimate, already-executable gadgets run. ROP uses DEP-compliant data to undo DEP.

The Stack Pivot Problem

ROP assumes you control the stack — but many bugs (a corrupted heap object, a controlled register pointing at attacker data) give you control over a register or a heap buffer, not the live stack. The solution is a stack pivot: a gadget that points RSP at memory you control, after which your chain executes normally.

text
COMMON PIVOT GADGETSxchg rax, rsp ; ret        (if you control RAX → RSP)mov rsp, rbp ; pop rbp; retlea rsp, [rax+0x...] ; retadd rsp, <large> ; ret     (pivot within a big controlled buffer)

A classic pattern: a use-after-free gives a controlled fake object whose first "virtual call" you redirect to a pivot gadget that sets RSP to the heap buffer (often heap-sprayed) holding the ROP chain. After the pivot, the chain runs against the sprayed stack. Pivoting is the bridge between non-stack bugs and stack-driven ROP.

Finding Gadgets

You don't hunt gadgets by hand. Tooling disassembles the executable regions and indexes every byte offset that decodes into a useful sequence ending in ret:

text
TOOLSROPgadget         --binary ./target --rop --badbytes "00|0a"ropper            search "pop rdi; ret" ; semantic search ; gadget chainspwntools (ROP)    rop = ROP(elf); rop.system(next(elf.search(b"/bin/sh")))rp++ / xrop       fast gadget enumeration

Practical selection criteria:

  • Avoid bad bytes. If the bug is a string overflow, NUL or newline bytes terminate your input. Gadget addresses must avoid those bytes — a constant constraint that narrows the usable gadget set.
  • Prefer clean side effects. A pop rdi ; ret is ideal; a pop rdi ; pop rbx ; add rsp,8 ; ret works but forces you to add filler entries to the stack to keep alignment. Track every register a gadget clobbers.
  • Find them in non-randomised modules first. If any loaded module lacks ASLR (compiled without /DYNAMICBASE or PIE), its gadgets sit at fixed addresses — a gift that removes the need for an info leak.
  • `pwntools` automates ABI marshalling. For CTFs and many real targets, ROP(elf) + high-level calls assemble the padding, alignment, and argument layout for you.

ASLR: Why ROP Needs a Leak

ROP picks gadgets by address. ASLR randomises module base addresses every run, so the gadget at libc_base + 0x4f2c5 is at a different absolute address each time. Therefore modern ROP almost always requires an information leak first: read a single pointer (a saved libc return address, a GOT entry, a leaked heap/stack pointer), subtract its known offset to recover the module base, then add gadget offsets to that base.

text
LEAK -> BASE -> CHAINleaked = read(GOT["puts"])         # an address inside libclibc_base = leaked - puts_offset   # known from the target's libcpop_rdi = libc_base + 0x00023b6a   # gadget at known offsetsystem  = libc_base + system_offbinsh   = libc_base + binsh_off

This is the universal modern shape: leak to defeat ASLR, then ROP to defeat DEP. The two mitigations are bypassed by two cooperating primitives. Without the leak, ROP on a fully-randomised 64-bit target is a non-starter (entropy is too high to guess).

Defence: Breaking the Chain

diagram — rendering…
flowchart TD
    A["ROP relies on:<br/>(1) known gadget addrs<br/>(2) returning into mid-function gadgets<br/>(3) a controllable stack"] --> B["ASLR/PIE → unknown addresses"]
    A --> C["CET shadow stack → RET must match real call"]
    A --> D["CFG/CFI → indirect calls must hit valid targets"]
    A --> E["Stack canaries → detect the overflow first"]
    B & C & D & E --> F["Chain construction or execution fails"]
    style F fill:#0c2a22,stroke:#21d48e,color:#d1fae5
MitigationHow it attacks ROP
ASLR / PIEGadget addresses unknown; forces an info-leak primitive
Stack canariesDetect the stack overflow before ret is reached
Intel CET — Shadow StackHardware keeps a protected copy of return addresses; a ret whose target doesn't match the shadow stack faults. This is the direct counter — ROP's whole trick is making ret go where the attacker wants, and the shadow stack forbids exactly that.
Intel CET — IBT / ARM BTIIndirect jumps/calls must land on an endbr/landing-pad instruction, killing JOP and many pivots
CFG / Clang CFIIndirect call targets validated against a set of legitimate functions, breaking fake-vtable entries into chains
ARM PACReturn addresses are cryptographically signed; forging one is infeasible without the key

The most consequential of these is the shadow stack (CET): because it independently records the legitimate return target of every call, a ret redirected to a gadget mismatches the shadow copy and traps. As CET deployment spreads, classic return-oriented chains die — pushing attackers toward JOP (jump-oriented, using indirect-jump-terminated gadgets), call-oriented techniques, and data-only attacks that never corrupt control flow at all. The arms race continues, but ret-based ROP's days on hardened platforms are numbered.

A Minimal Worked Example (Linux x86-64, no ASLR)

python
from pwn import *elf = ELF("./vuln")rop = ROP(elf)binsh = next(elf.search(b"/bin/sh"))   # or in libcrop.system(binsh)                       # auto-builds: pop rdi; binsh; systempayload = flat({ 72: rop.chain() })     # 72-byte offset to saved RIPio = process("./vuln")io.sendline(payload)io.interactive()                        # shell, with NX enabled, zero injected code

This runs on a DEP/NX-enabled binary precisely because nothing in the payload is executed as data: the bytes are gadget addresses and arguments, and only the binary's own pop rdi ; ret and system ever run.

Jump-Oriented Programming (JOP): ROP Without ret

As Intel CET's shadow stack sees broader deployment, classic return-oriented chains face a hardware enforcement mechanism that independently tracks legitimate return addresses and faults any ret that deviates. The logical response is to build control-flow chains that avoid ret entirely. Jump-Oriented Programming (JOP) is the primary alternative: it uses indirect-jump-terminated gadgets (jmp [reg], jmp [mem]) and a separate "dispatcher" gadget to drive the chain forward, never touching ret.

The JOP Mental Model

In ROP, the stack is both the chain storage and the implicit "step" register — rsp advances with every ret. JOP replaces this with an explicit dispatcher gadget that consults a separate data structure (the "dispatch table") to advance execution:

text
CLASSIC ROP CHAIN                    JOP EQUIVALENT------------------                   ---------------stack:                               dispatch table (any writable memory):[ addr_gadget1 ]   <- RSP            [ addr_gadget1 ]   <- "dispatch pointer"[ arg1         ]                     [ addr_gadget2 ][ addr_gadget2 ]                     [ addr_gadget3 ][ addr_gadget3 ]...                                  dispatcher gadget:  driven by: RET                        jmp [rdx]      (rdx points into table)  (pops RSP each time)                  + each JOP gadget advances rdx

Every JOP gadget ends in jmp [reg] — it does some work, updates the dispatch pointer (e.g. add rdx, 8), and jumps through it to the next gadget. The dispatcher itself is just a gadget that dereferences the current dispatch pointer:

text
EXAMPLE JOP GADGET SEQUENCE (x86-64) [pop rdi]                       ; load an argument  jmp [rdx]                     ; return control to dispatcher [add rdx, 8; jmp [rdx]]         ; dispatcher: advance + jump next gadget [pop rsi]  jmp [rdx] ... until a gadget calls the target function

Because no ret is involved, CET's shadow-stack mechanism is bypassed — it only validates return addresses popped by ret, not indirect jumps.

JOP Gadget Finding

bash
# ROPgadget can enumerate JOP-compatible gadgetsROPgadget --binary ./target --jop # look for: jmp [reg], jmp [mem+offset], call [reg]# and dispatcher-like patterns: add rdx,8; jmp [rdx]ropper --search "jmp [r?]"

JOP gadgets are somewhat less abundant than ROP gadgets because jmp [reg] byte sequences appear less frequently than 0xC3 (ret), but sizeable binaries still contain enough to build functional chains.

COP: Call-Oriented Programming

Call-Oriented Programming (COP) is a closely related variant using indirect call [reg] gadgets rather than jmp. COP gadgets are terminated by call [reg]; ret sequences, meaning they briefly touch the stack but the ret goes back to a controlled return slot rather than a shadow-stack-validated return address. COP can be combined with "fake" stack frames that keep the shadow stack coherent (by ensuring each call is paired with a matching valid ret), blurring the boundary between JOP and ROP.

CET IBT: The JOP Counter

Intel CET's Indirect Branch Tracking (IBT) is the hardware answer to JOP. IBT requires that every valid indirect-jump/call target begin with an endbr64 / endbr32 instruction (a landing-pad marker). A jump to any address without that prefix raises a fault. This limits JOP gadgets to code locations that were intended as indirect-call targets — dramatically shrinking the available gadget surface.

MitigationTargetsEffectiveness against JOP
CET Shadow Stackret instructionsNo effect on JOP/COP
CET IBTIndirect jmp/callLimits gadgets to endbr64-prefixed targets
ARM BTIIndirect branchesLanding-pad requirement (equivalent to IBT)
CFI/CFGIndirect callsValidates call targets against a set of valid functions

The combined CET deployment (shadow stack + IBT) closes both ROP and JOP simultaneously — but CET adoption is still incomplete, and many real-world targets remain without IBT even as shadow-stack deployment grows.

Practical Gadget Selection Reference

Goalx86-64 gadgetNotes
Set 1st argument (rdi)pop rdi ; retMost common, present in most ELFs
Set 2nd argument (rsi)pop rsi ; retOften combined with pop r15 ; ret
Set 3rd argument (rdx)pop rdx ; ret or pop rdx ; pop rbx ; retLess common; sometimes use syscall-centric gadgets
Set 4th argument (rcx/r10 for syscalls)pop rcx ; retr10 needed for Linux syscalls, not rcx
Arbitrary writemov [rdi], rax ; retNeeds rdi=target addr, rax=value
Arbitrary readmov rax, [rdi] ; retChain with pop rdi
Stack pivot to raxxchg rax, rsp ; retClassic pivot
Stack pivot to rbpleave ; ret (= mov rsp, rbp; pop rbp; ret)Very common — present in most functions' epilogue
System callsyscall ; retrax=syscall number, rdi/rsi/rdx/r10/r8/r9=args
Stack alignmentadd rsp, 8 ; retRequired for 16-byte ABI alignment before glibc functions
NOP (skip slot)ret aloneAny ret acts as a no-op that advances the chain

Understanding these staples — and why each is needed — is the mechanical foundation of building chains by hand or auditing automated chain output.

Conclusion and Takeaways

Return-Oriented Programming is the canonical answer to DEP, and understanding it is non-negotiable for any vulnerability researcher working on memory-corruption targets. The mental model is the whole battle: a controlled stack is a program, gadget addresses are its instructions, and ret is the step that advances it. With that lens, the rest follows — gadgets are short, ret-terminated snippets harvested from already-executable code (often by decoding unaligned bytes), chains marshal register state to call functions, the canonical goal is to flip a region executable via VirtualProtect/mprotect so real shellcode can run, and stack pivots bridge non-stack bugs into the technique.

The defensive picture is equally coherent. ROP needs known addresses, which ASLR denies — so modern exploitation pairs ROP with an information leak as a matter of course. And ROP needs ret to obey the attacker, which Intel CET's shadow stack and ARM PAC structurally forbid, pushing the frontier toward jump-oriented and data-only attacks. For the practitioner the workflow is clear: leak to beat ASLR, enumerate gadgets that avoid bad bytes, build the chain to defeat DEP, and pivot the stack if your bug doesn't already control it. Master those four moves and you can drive arbitrary computation out of a binary that, on paper, forbids you from running a single byte of your own code.