Back to Blog
Red Teaming

The Art of Heap Spraying: Modern Exploit Development Demystified

OffSec Research Team
10 June 2026 • 09:00 AM16 min
The Art of Heap Spraying: Modern Exploit Development Demystified
TL;DR — Heap spraying does not create a vulnerability; it makes an existing memory-corruption bug reliable. By filling the heap with thousands of copies of a controlled payload, the attacker raises the probability that a hijacked pointer — a freed object, a corrupted vtable, a wild write target — lands on something they control. This article explains the heap allocator's predictability, classic NOP-sled-plus-shellcode sprays, the JavaScript/string-based sprays that powered a decade of browser exploitation, the modern shift to precision grooming and JIT spraying, and why DEP, ASLR, and isolated heaps forced the technique to evolve rather than die.

Executive Summary

Memory-corruption exploitation is a two-part problem. Part one is the bug: a use-after-free, a type confusion, a buffer overflow — something that lets the attacker corrupt or redirect a pointer. Part two is control: ensuring that when execution follows the corrupted pointer, it lands somewhere useful. Heap spraying is a solution to part two.

The core difficulty is that modern heaps are dynamic. Where an object lands depends on allocation history, thread state, and allocator internals, so an attacker rarely knows the exact address of anything. Spraying sidesteps this by trading precision for probability: instead of needing to know where the payload is, the attacker arranges for the payload to be almost everywhere, so that a semi-controlled jump is overwhelmingly likely to hit it.

This is why heap spraying became synonymous with browser and document-format exploitation: those targets give an attacker a scripting environment (JavaScript, ActionScript, VBScript) capable of allocating megabytes of attacker-defined memory on demand — the perfect spray engine sitting right next to the buggy C++ object it will corrupt.

The Heap Is More Predictable Than It Looks

Naively, the heap seems chaotic. In practice, allocators are deterministic engines optimised for speed, and that determinism is exactly what an attacker exploits.

diagram — rendering…
flowchart TD
    A["Allocator design goals:<br/>speed, low fragmentation"] --> B["Size-class bins / segregated free lists"]
    B --> C["Same-size allocations cluster<br/>in predictable regions"]
    C --> D["Large, repeated allocations<br/>grow into stable address ranges"]
    D --> E["Attacker can predict<br/>~where a big spray lands"]
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Key properties an attacker leans on:

  • Size-class segregation. Allocators (Windows LFH, glibc tcache/bins, jemalloc, the browser-specific heaps) group allocations by size. Spray with one consistent chunk size and your blocks cluster together.
  • Determinism under pressure. When you allocate a few hundred megabytes of identical buffers, the OS must back them with real address space in a fairly continuous range. Historically this meant a large spray reliably occupied a known address band — the canonical 0x0c0c0c0c of mid-2000s browser exploits, chosen because it is both a plausible spray address and a valid pointer/instruction byte.
  • Reuse / recycling. Freed chunks of a given size are handed back to the next same-size request first. This is the foundation of precision grooming (below): free the victim object, immediately allocate an attacker buffer of the same size, and the attacker buffer reoccupies the victim's slot.

Classic Spray: NOP Sled + Shellcode

The original technique, pre-DEP. Allocate many blocks, each a long run of NOP instructions (0x90) followed by shellcode. Corrupt a pointer to jump somewhere into the sprayed region; whatever NOP it lands on, execution slides down the sled into the shellcode.

text
SPRAYED HEAP REGION (each block identical) [ 0x90 0x90 0x90 ... 0x90 | SHELLCODE ][ 0x90 0x90 ... | SHELLCODE ][ ... ]  ^----------- NOP sled -----------^   ^-- payload --^        landing anywhere here        slides right into the shellcode

In a scripting host the spray looked like this (conceptually, IE-era JScript):

javascript
var nop = unescape("%u9090%u9090");      // 2 NOPs per unitvar shellcode = unescape("%uXXXX%uXXXX..."); // attacker shellcode// grow each block to a target size (e.g. ~0x100000 bytes)while (nop.length < 0x100000) nop += nop;var block = nop.substring(0, 0x100000 - shellcode.length) + shellcode; var spray = new Array();for (var i = 0; i < 500; i++) spray[i] = block.substring(0); // 500 copies// now trigger the bug; a jump near 0x0c0c0c0c lands in a sled

The genius was using strings: a scripting string is just a length-prefixed buffer of attacker bytes, and concatenating/duplicating them is a trivial, high-volume allocator API. The attacker never calls malloc directly — they let the language runtime do it, hundreds of times, with bytes of their choosing.

Why DEP Broke the Classic Spray (and What Replaced It)

Data Execution Prevention (DEP / NX) marks heap pages non-executable. A jump into a sprayed NOP sled now faults — you cannot execute data. This did not kill heap spraying; it changed what you spray.

diagram — rendering…
flowchart LR
    A["DEP marks heap NX"] --> B["Can't execute sprayed shellcode directly"]
    B --> C["Spray ROP chains / fake objects instead"]
    C --> D["Pivot stack into the spray,<br/>ROP calls VirtualProtect"]
    D --> E["Flip a region to RX,<br/>then run real shellcode"]
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2

The modern post-DEP spray contains data the CPU interprets as control structures, not as code:

  • ROP chains — sprayed sequences of gadget addresses. After a stack pivot, the chain executes by returning through existing executable code (see the companion ROP article). It typically calls VirtualProtect/mprotect to make a region executable, then jumps to shellcode there.
  • Fake objects / fake vtables — when the bug is a use-after-free or type confusion on a C++ object, the spray fills memory with counterfeit objects whose vtable pointer points to attacker-chosen gadgets. When the dangling pointer's virtual method is called, control flows where the attacker wants.

So the payload became addresses and structures rather than raw instructions. The spray's job is unchanged — be everywhere so the hijacked pointer lands on a controlled structure — but the content is now ASLR-aware.

ASLR and the Information-Leak Tax

Address Space Layout Randomization randomises module and heap base addresses, so the attacker no longer knows the absolute address of gadgets or even reliably of 0x0c0c0c0c. Two adaptations:

  • Spray big enough to beat the entropy. On 32-bit systems, address-space entropy is small; a large spray still covers a predictable band with high probability. This is why 32-bit targets remained sprayable long after DEP.
  • Combine with an info leak. On 64-bit, entropy is large enough that "spray everywhere" is infeasible — there's too much address space. Modern exploits therefore pair a spray with a memory disclosure primitive (often from the same bug class) to defeat ASLR: leak a pointer, compute module/heap base, then spray precisely groomed objects at computed offsets. Spraying and info-leaks are partners, not alternatives.

Precision Heap Grooming: The Modern Default

On contemporary targets, brute-force "fill all of memory" is crude and noisy. The state of the art is heap grooming (a.k.a. heap feng shui): manipulating allocation order so that a specific freed slot is reoccupied by a specific attacker buffer.

diagram — rendering…
sequenceDiagram
    participant A as Attacker script
    participant H as Heap (size-class N)
    A->>H: Allocate many size-N filler objects
    Note over H: Defragment — create a clean run of size-N chunks
    A->>H: Allocate victim object V (size N)
    A->>H: Free a neighbour to position V predictably
    A->>H: Trigger bug → V is freed (now dangling pointer)
    A->>H: Immediately allocate attacker buffer B (size N)
    Note over H: B reoccupies V's exact slot (LIFO free-list reuse)
    A->>H: Use dangling pointer → operates on attacker-controlled B

This is deterministic, not probabilistic. By controlling the size class (matching the victim object's allocation size) and the allocation/free sequence, the attacker reclaims the freed object's memory with content they fully control — turning a use-after-free into an arbitrary read/write or a controlled vtable call with near-100% reliability. Allocator-specific knowledge matters here: the Low-Fragmentation Heap on Windows, the V8/JSC garbage-collected heaps in browsers, and glibc's tcache each have their own reuse rules to exploit.

JIT Spraying: Defeating DEP With the Defender's Own Code

A particularly elegant evolution. Just-In-Time compilers (JavaScript, Flash ActionScript) generate executable machine code at runtime — they have to, to run fast. JIT spraying abuses this: the attacker writes high-level code containing carefully chosen constants, and the JIT emits executable native code containing those constants as instruction bytes.

javascript
// Constants chosen so the emitted machine code, when entered// mid-instruction, decodes into attacker shellcode.var x = (0x3c909090 ^ 0x3c909090 ^ 0x3c909090 ^ ...);

Each 0x3c909090 becomes part of an emitted instruction, but the embedded 0x90 0x90 bytes form a NOP sled and the 0x3c byte realigns the decoder. By spraying many such JIT-compiled functions, the attacker fills executable memory with content of their choosing — neatly sidestepping DEP, because the pages are legitimately executable (the JIT made them so). Mitigations followed: constant blinding (XOR constants with a random key before emission), JIT page randomisation, and W^X enforcement on JIT regions.

Defence: How Targets Fought Back

text
DEFENSE                         WHAT IT BREAKSDEP / NX                        Direct execution of sprayed dataASLR / high-entropy 64-bit      "Spray everywhere" feasibilityIsolated / partitioned heaps    Reclaiming a victim slot with attacker data   (PartitionAlloc, IsolatedHeap, type-segregated heaps)Heap metadata hardening         Free-list / metadata corruption   (safe unlinking, pointer encoding, MTE)GC pointer compression / cages  Cross-region grooming in JS enginesJIT constant blinding + W^X     JIT sprayingCFG / CET / PAC                 Jumping to sprayed fake vtables / gadgets

The decisive structural defences:

  • Type- and size-isolated heaps. If objects of different types live in separate, non-recycling partitions (Chrome's PartitionAlloc, the old IE IsolatedHeap, V8's pointer-compressed cage), the attacker cannot reclaim a freed object of type A with a buffer of type B. This directly attacks grooming — the cornerstone of modern UAF exploitation. Memory tagging (ARM MTE) extends this by tagging allocations so a stale pointer's tag mismatches the reused chunk.
  • Control-Flow Integrity (CFG, CET shadow stacks, ARM PAC). Even if a fake vtable is sprayed and a virtual call is hijacked, CFI verifies the call target is a legitimate function entry, and ROP/return targets must match a shadow stack — breaking the "land on a sprayed gadget/vtable" payoff.
  • DEP + ASLR together. Neither alone suffices, but together they force the attacker to both find executable memory (info leak, ROP, or JIT abuse) and know where the spray landed — multiplying exploit cost.

None of these makes spraying impossible; they make it expensive, requiring a chain of primitives (leak → groom → CFI bypass) where a single spray once sufficed.

Practical Notes for the Vulnerability Researcher

  • Match the size class. The single most important grooming parameter is allocating at exactly the victim object's size so you land in the same bin/free-list. Determine the victim size from the source or by reversing the allocation.
  • Defragment first, then position. Allocate a wave of fillers to create a contiguous run, free a hole, place the victim, then trigger — predictability beats volume on modern allocators.
  • Pair with a leak. On 64-bit, plan for an information disclosure before you need an absolute address. A spray without a leak is rarely enough today.
  • Mind GC and timing. In garbage-collected runtimes, an unexpected collection can move or free your spray. Keep references alive and trigger the bug before the collector runs.
  • Measure reliability. A good spray-based exploit is judged by its success rate across reboots and machines. Test repeatedly; if it's flaky, your grooming is imprecise, not your shellcode.

Type Confusion Exploits Enabled by Heap Spray

One of the most powerful exploitation patterns in modern browser and runtime security is the combination of type confusion with heap spray / grooming. Type confusion occurs when an engine assumes an object has one type but it actually has another — a mismatch that allows the attacker to access memory fields at wrong offsets, turning a subtle semantic inconsistency into a concrete read/write primitive.

Heap spray and grooming are what make type confusion reliable: the attacker must ensure that when the engine is tricked into misinterpreting an object's type, the memory at that location contains attacker-controlled data that looks like a valid object of the expected type, or that exposes a useful pointer.

The Type Confusion → Heap Spray Pipeline

text
STEP 1: Trigger the type confusion   - Use a side-effecting operation (Proxy, setter, Array species constructor,     Symbol.toPrimitive) to swap an object's type mid-operation after the JIT     has already specialised for the original type. STEP 2: Control what the mistyped memory contains   - Heap-groom so that the freed/confused object's memory slot is occupied     by attacker-allocated data that represents a "useful" object of the     expected type — typically a fake TypedArray, a fake ArrayBuffer, or     a fake object whose "length" field is set to a huge value. STEP 3: Exploit the confusion   - The JIT's fast path now reads fields from attacker data at the "correct"     offsets — yielding an out-of-bounds length, a controlled pointer, or     a type tag the attacker chose.   - Convert the resulting OOB access into addrof + fakeobj primitives.

Fake TypedArray via Groomed Type Confusion

javascript
// Conceptual shape — simplified for clarity// Goal: get the JIT to treat an attacker-controlled ArrayBuffer backing pointer//       as if it came from a legitimate TypedArray function prepareSpray() {  const bufs = [];  // Spray many ArrayBuffer wrappers of size matching the confused object  for (let i = 0; i < 0x1000; i++) {    bufs.push(new ArrayBuffer(0x200));  }  return bufs;} // After type confusion grants an OOB write, overwrite a sprayed// ArrayBuffer's byteLength field to 0x7fffffff — now it "covers"// the whole address space. Use it as an arbitrary read/write primitive.

The spray ensures that whichever slot the confused pointer lands on, there is a predictably structured object there — turning a probabilistic type mismatch into a deterministic exploit. This is why modern JS engine exploits virtually always pair a type-confusion CVE with precise heap grooming: one provides the wrong-type access, the other ensures useful data is at that address.

Real-World Example Pattern: ArrayBuffer Length Corruption

In multiple WebKit and V8 CVEs the pattern has been:

  • Type confusion causes an integer-typed array slot to be read as a pointer (or vice versa).
  • Heap grooming places an ArrayBuffer object immediately after the victim, at the predictable offset the confusion accesses.
  • The confused write overwrites the ArrayBuffer's byteLength with a large value (e.g. 0x7fffffff).
  • Reading/writing through this "giant" ArrayBuffer now accesses the entire heap — a classic unlimited read/write primitive.
  • From there, leak pointers to defeat ASLR, craft a fake function object, and execute shellcode (after defeating JIT write-protection, PAC, or CFI depending on the platform).

Modern Allocator Mitigations Against Heap Spray

The defensive architecture has evolved significantly. Understanding these mitigations is essential both for exploit research and for security engineering.

Randomised Heap (Per-Chunk Randomisation)

Beyond ASLR's coarse base-address randomisation, modern allocators add intra-heap randomisation:

AllocatorRandomisation MechanismEffect on Spray
PartitionAlloc (Chrome)Randomises partition base + per-slot metadata encoded with a random cookieAttacker cannot predict slot addresses within a partition even after leaking the partition base
jemallocRandom chunk selection within size classes; randomised free list orderingAdjacent same-size allocations are not contiguous — breaks defragment-then-groom sequences
glibc 2.35+ tcachePer-thread tcache key XORed into the next pointer of freed chunksCorrupted free-list pointers are detected or point to random addresses
Windows Segment HeapRandomised segment selection; VS metadata encodedMakes reliable sequential spray harder on modern Windows

Guard Pages

Many allocators insert non-accessible guard pages between large allocations or between allocator metadata and user data:

text
[ ... user alloc N ... ][ GUARD PAGE (PROT_NONE) ][ allocator metadata ][ GUARD PAGE ][ user alloc N+1 ... ] → Any OOB read/write into a guard page causes an immediate SIGSEGV/access violation  instead of silently corrupting adjacent memory.→ This breaks "spray-then-overflow-into" patterns where an overflow from one allocation  was meant to corrupt the next object in the same page.

Type-Isolated Heaps (PartitionAlloc / IsoHeaps)

The most architecturally significant defence. If every allocation type lives in its own partition:

  • A freed object of type FooObject can only be reclaimed by another allocation from the FooObject partition.
  • An attacker spraying ArrayBuffer objects cannot reclaim a freed JSString — the types are segregated by partition.
  • This directly breaks UAF exploitation that depends on controlling the freed object's contents with a different type.

Chrome's PartitionAlloc and JSC's IsoHeaps are built on this principle. Combined with pointer-compressed "cages" (all heap pointers are offsets within a 4 GB region, so a leaked pointer cannot address anything outside the cage), these dramatically raise the cost of spray-based exploitation.

Memory Tagging (ARM MTE)

ARM's Memory Tagging Extension (MTE) attaches a 4-bit colour tag to each 16-byte granule of memory. Every pointer also carries a tag in its top bits. On a tag mismatch (pointer's tag ≠ granule's tag) the CPU raises a fault:

text
Allocation:  tag = 0x5 assigned to the chunk; pointer has tag 0x5 in bits [59:56]After free:  granule retagged to 0x8Stale ptr:   tag 0x5 ≠ granule tag 0x8 → fault on dereference (UAF detected)After realloc to different type: new tag 0xA ≠ old pointer's 0x5 → fault

MTE makes use-after-free and out-of-bounds heap accesses deterministically detectable (in synchronous mode) or probabilistically detectable (in asynchronous mode for production). It directly undermines both UAF-based type confusion and OOB heap spray by ensuring stale or out-of-bounds pointers fault immediately rather than silently accessing attacker-controlled data.

Conclusion and Takeaways

Heap spraying is the connective tissue of memory-corruption exploitation — the technique that converts a fragile, probabilistic bug into a reliable one. Its history is a clean illustration of the attacker-defender arms race: the original NOP-sled-and-shellcode spray was a brute-force probability play; DEP forced the payload to become ROP chains and fake objects; ASLR forced spraying to partner with information leaks; and isolated heaps plus control-flow integrity forced the crude spray to mature into surgical heap grooming.

For the researcher, the lesson is that spraying is a reliability tool, not an exploit primitive in itself. You still need the bug, and on modern targets you almost always need a leak and a CFI bypass too. But the underlying intuition — allocators are deterministic, same-size allocations cluster, freed slots are recycled predictably — remains as true as it was twenty years ago. Master the allocator you're attacking, match the victim's size class, groom the free list deliberately, and you turn "this crashes sometimes" into "this pops a shell every time." For defenders, the takeaway is equally clear: isolate heaps by type and size, harden allocator metadata, deploy DEP and ASLR together, and enforce control-flow integrity — because each layer doesn't just block one spray, it forces the attacker to chain ever more primitives to achieve what a single new Array() loop once did alone.