In the previous post we fuzzed an AArch64 Android library on a Linux host with LibAFL QEMU mode: the target ran inside an emulator, and QEMU's translator gave us coverage. It works well, but it is still emulation. Every syscall is forwarded, you need a copy of the device's root filesystem, and anything that depends on the real phone (vendor libraries, linker namespaces, the real allocator) is only approximated.

This bug was originally found and reported by Project Zero, who shared a crash log and triggering image, but no fuzzing methodology. Here we independently rediscover it with LibAFL Frida mode, using our own seeds and knowledge of the target function, not their input file, to fuzz the closed-source library directly on the phone at native speed, with no source code, no recompilation and no root.

The specific CVE we rediscover is:

CVE-2026-21096: Samsung libimagecodec.quram.so Out-of-Bounds Write in Progressive JPEG Inverse-DCT from a Scan/Frame Component-Index Mismatch, reported by Brendon Tiszka and Mateusz Jurczyk of Google Project Zero (issue 527860114), fixed in Samsung's September 2026 security update.

The test device is an unrooted Samsung Galaxy S25 (SM-S931B), Android 16, security patch level 2026-08-05, one month before the fix. By the end of the post, our fuzzer running on that phone will have found the bug in under ten seconds, and we will have reproduced it under AddressSanitizer and traced it down to the exact instructions.

Your browser does not support embedded video. Watch the fuzzing demo.
Live on the Galaxy S25: the client objective counter changes from 0 to 1 when the fuzzer finds a crash. The actual crash line is enlarged below the terminal, and the final frame is held briefly.

We cover:

  1. What Frida mode is, and how Frida Stalker works internally
  2. How Stalker is turned into a fuzzer's instrumentation (coverage, CmpLog, ASan)
  3. How LibAFL implements this, read straight from the libafl_frida source
  4. Building a Frida-mode fuzzer for Android step by step
  5. Reversing the target API and writing the harness
  6. Fuzzing, triage with an ASan build, and a full root-cause analysis of the crash

All code from this post lives in one project directory:

textfrida-mode/
├── device_libs/          # libraries pulled from the phone
├── harness/              # harness.c, runner.c, build.sh, make_seeds.py, jpeg_info.py, symbolize.py
├── fuzzer/               # the LibAFL Frida fuzzer (Rust crate)
├── scripts/              # run_on_device.sh, decomp.sh
├── seeds/                # generated seed corpus
├── crashes/              # crash files + tombstones + ASan reports
└── vendor/LibAFL/        # LibAFL @ 338c8e7f (0.16.0)
Black Friday bundle · 61% off
Android Userland + Kernel
Two complete courses and two certifications, with 140 hours of training from AFL++ on ARM64 to Syzkaller and kernel root. Enroll now and start whenever you want.
View bundle →

Part 1: What is LibAFL Frida mode?

LibAFL is a fuzzer library: you assemble a fuzzer from components (executors, observers, feedbacks, mutators, schedulers). For targets you can recompile, coverage comes from compile-time instrumentation (SanitizerCoverage). For binary-only targets you need another way to observe execution, and LibAFL offers several backends:

Backend How coverage is obtained Runs on Typical use
QEMU mode (libafl_qemu) QEMU's TCG translator, hooks inserted into translated blocks Host (emulated guest CPU) Cross-arch targets, full-system/snapshot fuzzing
Frida mode (libafl_frida) Frida Stalker rewrites the target's code in the same process, at run time The real device, native CPU Closed-source libraries on Android/iOS/macOS/Windows/Linux
TinyInst / Intel PT Breakpoint-based / hardware tracing Host Windows/macOS / Intel CPUs

In Frida mode the fuzzer, the harness and the target library are one process. The fuzzer dlopens a small harness .so, Frida's Gum engine is linked into the fuzzer binary, and Stalker recompiles the target library's basic blocks with coverage code before they execute. Nothing is emulated: the target runs on the phone's Cortex cores, against the phone's real bionic, linker and Scudo allocator.

There is no frida-server and no ptrace. Gum is just a library inside our own process, which is why an unrooted phone is enough: we run as the shell user in /data/local/tmp, and the shell SELinux domain lets a process generate and execute code for itself.


Part 2: How Frida Stalker works

Dynamic binary instrumentation, in one paragraph

You can't add instructions to a compiled binary without breaking every offset in it. Dynamic binary instrumentation (DBI) engines such as DynamoRIO, Pin and Frida Stalker get around this: they never execute the original code. Just before a basic block runs, the engine copies it to a private code cache, rewrites it (adding whatever instrumentation it wants), and runs the copy. The original code is only ever read.

Stalker's main loop

Stalker is Frida Gum's DBI engine. Given a thread to follow, it works like this:

How Frida Stalker compiles a basic block: fetch and decode, relocate, transform each instruction, and virtualize the exit into an instrumented code-cache copy

Some details that matter for fuzzing:

  • Follow / activate. follow_me() tells Stalker to follow the current thread. deactivate() pauses following, and activate(target) resumes it as soon as execution reaches target. LibAFL uses this pair to switch instrumentation on exactly while the harness runs.
  • Branch resolution and backpatching. The first time a compiled block exits, Stalker has to look up (or compile) the destination. Once a destination is known, Stalker backpatches the exit to jump straight to the compiled copy, so hot loops run entirely inside the code cache with no context switch into Stalker. The trust_threshold sets how many times a block must be seen unchanged before it is trusted enough to be linked like this. The default is 1.
  • Exclusions. Address ranges can be excluded. When followed code calls into an excluded range (libc, for example), the call runs natively and Stalker picks up again on return. This is how a fuzzer instruments only the target library and doesn't pay for memcpy, malloc or itself.
  • AArch64 scratch registers. A direct branch on arm64 reaches ±128 MB. When the code cache is further away than that, Stalker has to branch through a register: it spills x16/x17 below the stack pointer, branches through them, and prefixes every compiled block with a one-instruction "restore prologue" that reloads them. Blocks reached with a near branch are entered after that prologue. LibAFL's coverage code relies on this trick, as we'll see.

The transformer: Stalker's extension point

The transformer is a callback Stalker invokes for each block it compiles. In C:

cstatic void transform(GumStalkerIterator *it, GumStalkerOutput *out, gpointer user) {
  const cs_insn *insn;
  gboolean first = TRUE;
  while (gum_stalker_iterator_next(it, &insn)) {
    if (first) {               /* start of a basic block */
      emit_coverage_code(out->writer.arm64, insn->address);
      first = FALSE;
    }
    if (is_compare(insn))      /* e.g. SUBS/CMP, CBZ, TBZ */
      emit_cmplog_code(out->writer.arm64, insn);
    if (is_memory_access(insn))
      emit_asan_shadow_check(out->writer.arm64, insn);
    gum_stalker_iterator_keep(it);   /* copy the original instruction */
  }
}

That callback contains the whole idea of a Stalker-based fuzzer. Whatever code you emit in it runs inline, every time that block of the target executes, at close to native speed.


Part 3: Using Stalker as fuzzer instrumentation

A coverage-guided fuzzer needs three things from its instrumentation:

  1. Edge coverage: which branches did this input take? This drives corpus growth.
  2. Comparison feedback (optional, very effective): what values does the target compare input bytes against? Magic numbers, lengths and IDs can then be copied into the input instead of guessed.
  3. A bug oracle: was this input harmful? A crash (SIGSEGV/SIGABRT) is the minimum. Memory-error detection (ASan) is better.

libafl_frida maps each one to a runtime, a Rust type implementing the FridaRuntime trait, which hooks into the transformer:

Need LibAFL runtime What it emits per block / instruction
Edge coverage CoverageRuntime ~15 instructions at the start of every block: AFL-style map[prev ^ cur]++
Comparison feedback CmpLogRuntime For SUBS/ADDS/ANDS/…, CBZ/CBNZ, TBZ/TBNZ: records both operands in the CmpLog map
Memory errors AsanRuntime Shadow-memory check before every load/store; hooks malloc/free/mem*/str*
Coverage export DrCovRuntime Records basic blocks for Lighthouse/bncov

Let's read how each piece works in LibAFL (commit 338c8e7f, version 0.16.0).

3.1 FridaInstrumentationHelper: choosing what to instrument and building the transformer

FridaInstrumentationHelper::new(&gum, &options, runtimes) does three things:

  1. Builds a module map of everything loaded in the process and keeps the modules selected with -H <harness> and -l <lib>. Their executable ranges go into a RangeMap (ranges). Only code inside ranges is ever instrumented.
  2. Initializes every runtime (init()): allocates the coverage map, sets up ASan shadow memory, and so on.
  3. Builds the Stalker transformer, a closure that calls FridaInstrumentationHelper::transform() for every block.

That is why load order matters: the target library must already be mapped when the helper is created, or there will be nothing in ranges and you'll fuzz blind with 0% coverage. Our harness links against libimagecodec.quram.so, so a single dlopen(libharness.so) pulls the target in first.

Here is the transformer, trimmed to the AArch64 path (crates/libafl_frida/src/helper.rs):

rustfn transform(basic_block: StalkerIterator, output: &StalkerOutput,
             ranges: &Rc<RefCell<RangeMap<u64, (u16, String)>>>,
             runtimes: &Rc<RefCell<RT>>, decoder: InstDecoder) {
    let mut first = true;
    for instruction in basic_block {
        let instr = instruction.instr();
        let address = instr.address();
        if ranges.borrow().contains_key(&address) {          // only the target library
            let mut runtimes = (*runtimes).borrow_mut();
            if first {
                first = false;
                if let Some(rt) = runtimes.match_first_type_mut::<CoverageRuntime>() {
                    rt.emit_coverage_mapping(address, output);   // ① edge coverage
                }
            }
            let res = if let Some(_rt) = runtimes.match_first_type_mut::<AsanRuntime>() {
                AsanRuntime::asan_is_interesting_instruction(decoder, address, instr)
            } else { None };
            if let Some((basereg, indexreg, displacement, width, shift)) = res
                && let Some(rt) = runtimes.match_first_type_mut::<AsanRuntime>() {
                rt.emit_shadow_check(address, output, basereg, indexreg,
                                     displacement, width, shift);   // ② ASan
            }
            if let Some(rt) = runtimes.match_first_type_mut::<CmpLogRuntime>()
                && let Some((op1, op2, shift, special_case)) =
                    CmpLogRuntime::cmplog_is_interesting_instruction(decoder, address, instr) {
                rt.emit_comparison_handling(address, output, &op1, &op2,
                                            &shift, &special_case);  // ③ CmpLog
            }
        }
        instruction.keep();                                     // ④ keep original
    }
}

It is the C sketch from Part 2, with each piece of emitted code owned by a runtime.

3.2 CoverageRuntime: the code injected into every block

emit_coverage_mapping() hashes the block's address into a 16-bit location ID and emits this AArch64 code (from coverage_rt.rs, generated with dynasm):

asm    b      start                  ; ← overwrites Stalker's restore prologue
    stp    x16, x17, [sp, -0x90]! ; near-branch entry lands here: spill scratch regs
start:
    ldr    x17, =&previous_pc
    ldr    x17, [x17]             ; x17 = prev
    ldr    x16, =loc              ; x16 = hash(block_addr) & 0xffff
    eor    x16, x17, x16          ; edge = prev ^ loc
    ldr    x17, =&map
    add    x16, x17, x16          ; &map[edge]
    ldrb   w17, [x16]
    add    w17, w17, #1           ; hitcount++
    add    x17, x17, x17, lsr #8  ; "NeverZero": 0xff+1 = 0x100 → 0x101 → stores 0x01
    strb   w17, [x16]
    ldr    x16, =loc >> 1
    ldr    x17, =&previous_pc
    str    x16, [x17]             ; prev = loc >> 1  (so A→B ≠ B→A)
    ldp    x16, x17, [sp], #0x90  ; restore scratch regs
    b      end
map:  .quad &map  ;  previous_loc: .quad &previous_pc ; loc: .quad h ; loc_shr: .quad h>>1
end:

The first two instructions are worth a closer look. Before emitting, the runtime does writer.reset(pc - 4), rewinding over the one-instruction restore prologue Stalker placed at the top of the block:

  • Far-branch entry (offset 0): Stalker has already spilled x16/x17 to [sp-0x90], so b start skips our own spill and reuses theirs.
  • Near-branch entry (offset 4): nothing was spilled, so we run stp x16, x17, [sp, -0x90]! ourselves.

Both paths end with ldp ..., #0x90, so the target never notices. No flags are touched (no adds/cmp), so the code is transparent to the surrounding instructions. The map itself is a plain [u8; 65536] inside the runtime, and that is the array LibAFL's HitcountsMapObserver reads after every execution.

3.3 CmpLogRuntime: getting past magic values

For every SUBS/ADDS/ANDS/SBCS/BICS/ADCS (note that cmp is subs xzr, … on AArch64), CBZ/CBNZ and TBZ/TBNZ, the runtime emits a call that records (op1, op2) into LibAFL's CmpLog map. The fuzzer runs each interesting input once more in a shadow execution with this map enabled (ShadowExecutor + ShadowTracingStage). Then I2SRandReplace (input-to-state) searches the input for one operand and replaces it with the other.

For our target this matters directly. When the JPEG SOS parser looks up a scan's component selector it executes cmp w5, w14 (selector vs. frame component ID, at 0x12b7bc). CmpLog hands the fuzzer the legal IDs (1, 2, 3) on a plate.

3.4 AsanRuntime: ASan for binaries you can't recompile

The ASan runtime reimplements AddressSanitizer at the binary level:

  • It reserves shadow memory (1 shadow byte per 8 bytes) at 1 << shadow_bit and hooks malloc/calloc/realloc/free/memalign, operator new/delete, and the mem*, str*, wcs* families with Frida's Interceptor. Allocations come from its own allocator, with redzones poisoned in the shadow.
  • In the transformer, every load and store in the target gets an inline shadow check (emit_shadow_check). A bad access is recorded in AsanErrors. After the run, FridaInProcessExecutor raises SIGABRT and AsanErrorsFeedback turns the error into an objective.

In other words, a heap overflow in a closed-source library is reported as a heap overflow, even if it never segfaults. We'll come back to what happened when we tried it on this phone.

3.5 FridaInProcessExecutor: switching Stalker on for exactly one function

The executor wraps LibAFL's normal InProcessExecutor (signal handlers, timeouts, crash serialization) and adds Stalker control (executor.rs):

rust// at construction:
let mut stalker = Stalker::new(gum);
// 1) exclude the fuzzer's own module - instrumenting LibAFL itself would be slow and
//    would make Stalker trip over our own hooks
stalker.exclude(&MemoryRange::new(fuzzer_module_base, fuzzer_module_size));
// 2) exclude every gap between the instrumented ranges: libc, libc++, linker... run natively
for range in ranges.gaps(&(0..u64::MAX)) {
    stalker.exclude(&MemoryRange::new(range.start, range.end - range.start));
}

// on every execution:
fn run_target(&mut self, ..., input: &I) -> Result<ExitKind, Error> {
    self.helper.borrow_mut().pre_exec(target_bytes)?;        // runtimes: unpoison input, reset...
    if !self.followed {
        self.followed = true;
        self.stalker.follow_me::<NoneEventSink>(transformer, None);  // once
        self.stalker.deactivate();
    }
    self.stalker.activate(NativePointer(harness_ptr));       // start compiling at the harness
    let res = self.base.run_target(fuzzer, state, mgr, input);   // calls LLVMFuzzerTestOneInput
    self.stalker.deactivate();
    if !AsanErrors::get_mut_blocking().is_empty() { libc::raise(libc::SIGABRT); }
    self.helper.borrow_mut().post_exec(target_bytes)?;       // runtimes: collect results
    res
}

Because the code cache persists between executions, a block of libimagecodec.quram.so is compiled once and reused millions of times. After a short warm-up, Frida mode runs close to native speed. On this phone we measured about 6,000 exec/s on one core and about 30,000 exec/s on eight.

Putting it all together, one execution looks like this:

One fuzz iteration inside a LibAFL client: input mutation, Frida execution, Stalker-instrumented Quram decoding, coverage collection, crash feedback, and LLMP broker synchronization

Part 4: The target, libimagecodec.quram.so

Quram is Samsung's in-house image codec library. It's what the Samsung Gallery app (com.sec.android.gallery3d) and the background image service (com.samsung.ipservice) use to decode images on the device. That makes it a classic remote attack surface: an image that lands in the media store, for instance one auto-saved by a messenger and picked up by the media scanner, gets decoded with no user interaction.

Project Zero's report describes the bug like this:

When decoding a progressive JPEG, the inverse-DCT pass WINKJ_ProgIDct walks the image's components and, for each one, writes the reconstructed samples through WINKJ_DoIdct_islow. […] the loop indexes a scan-ordered component-geometry array and a frame-ordered output-buffer array with the same loop counter; for a scan whose component order/selection differs from the frame's, these two refer to different components.

That gives two outcomes from one root cause:

  • Horizontal mismatch: a wider component's rows are written into a narrower component's buffer, a contiguous heap overflow.
  • Vertical mismatch: a component with more vertical sampling walks more output row pointers than the destination's row-pointer array holds, so it reads pointers from past the end of that array and writes through them.

Our goal: get a fuzzer to find this on its own, on the phone, starting from ordinary images.

Lab setup

Device Samsung Galaxy S25, SM-S931B, Android 16 (BP4A.251205.006.S931BXXSCCZH1), SPL 2026-08-05, not rooted
Host macOS (Apple Silicon)
Toolchain Android NDK r29 (29.0.14206865), Rust 1.97.1, cargo-ndk 4.1.2
LibAFL 0.16.0 @ 338c8e7f, frida-gum 0.17.2
RE radare2 6.1.8 + r2ghidra

Part 5: Step by step

Step 1: Pull the target off the phone

The phone has two builds of the library: the system copy named in the report title, and the APEX copy that appears in P0's Gallery backtrace. Both are world-readable, so adb pull works without root:

bash$ adb shell getprop ro.build.version.security_patch
2026-08-05
$ adb shell ls -la /system/lib64/libimagecodec.quram.so \
      /apex/com.samsung.android.media.imagecodec.system/lib64/libimagecodec.media.quram.so
-rw-r--r-- 1 root   root   3027080 ... /system/lib64/libimagecodec.quram.so
-rw-r--r-- 1 system system 3028056 ... /apex/.../libimagecodec.media.quram.so

$ mkdir device_libs && cd device_libs
$ adb pull /system/lib64/libimagecodec.quram.so .
$ adb pull /apex/com.samsung.android.media.imagecodec.system/lib64/libimagecodec.media.quram.so .

Its dependencies are all ordinary NDK/system libraries, so it loads fine in a plain native process:

bash$ llvm-readelf -d libimagecodec.quram.so | grep NEEDED
 (NEEDED) Shared library: [libc++.so]
 (NEEDED) Shared library: [libm.so]
 (NEEDED) Shared library: [liblog.so]
 (NEEDED) Shared library: [libjnigraphics.so]
 (NEEDED) Shared library: [libz.so]
 (NEEDED) Shared library: [libc.so]
 (NEEDED) Shared library: [libdl.so]

We fuzz the /system/lib64 copy. Everything below applies equally to the APEX one.

Step 2: Recover the API

There's no header. The library does export its whole API, though, including the internal WINKJ_* decoder functions:

bash$ llvm-readelf --dyn-syms -W libimagecodec.quram.so | grep -E 'QuramDecode|QuramGetImageInfo|WINKJ_Prog'
  00000000001aa9a4   732 FUNC GLOBAL DEFAULT 15 QuramDecodeBuffer
  00000000001a9900   216 FUNC GLOBAL DEFAULT 15 QuramGetImageInfoFromBuffer
  00000000001aaf64  1012 FUNC GLOBAL DEFAULT 15 QuramDecodeBufferOpt
  000000000012cfd8  1324 FUNC GLOBAL DEFAULT 15 WINKJ_ProgProcessData
  0000000000136ce8  2812 FUNC GLOBAL DEFAULT 15 WINKJ_ProgDecodeSingleiMcu
  000000000018dc14  4152 FUNC GLOBAL DEFAULT 15 WINKJ_ProgIDct
  ...

P0's Gallery backtrace tells us which entry point real decodes use: SimbaDecoderJpeg::internalDecode → QuramDecodeBuffer. In r2ghidra the cross-library calls show up as PLT stubs (func_0x002d1c10), so scripts/decomp.sh maps PLT addresses back to names before printing:

bash$ llvm-objdump -d -j .plt libimagecodec.quram.so | grep '@plt>:' \
    | sed -E 's/^0*([0-9a-f]+) <(.*)@plt>:/0x\1 \2/' > plt.map
$ ../scripts/decomp.sh libimagecodec.quram.so sym.QuramDecodeBuffer sym.QuramGetImageInfoFromBuffer
cuint64_t QuramDecodeBuffer(int64_t arg1, int64_t arg2, int64_t arg3, int64_t arg4, int64_t arg5)
{
    if (arg1 != 0 && arg2 != 0 && arg3 != 0) {
        uVar8 = arg5;  if (uVar8 < 2) uVar8 = 1;                 // sample size
        iVar6 = QURAMWINK_CreateDecInfo(1, arg1, arg3, arg4, 0); // 1 = memory stream
        if (iVar6 != 0) {
            iVar5 = QURAMWINK_Parser(iVar6, &uStack_2b0);         // -> image type, w, h
            uVar2 = uStack_2b0 / uVar8;  uVar3 = uStack_2ac / uVar8;
            if (iVar5 == 1) {                                      // JPEG
                *(iVar6 + 0x3bc) = 1;
                uVar7 = QURAMWINK_PDecodeJPEG(iVar6, arg2, uVar2, uVar3, uVar8);
                if (*(iVar6 + 0x370) != 0) {
                    if (arg4 - 7U < 2) { ...; uVar9 = 4; }        // formats 7/8: 4 bytes/pixel
                    else if (arg4 == 1) { ...; uVar9 = 3; }
                    TransformICC(..., arg2, uVar2, uVar3, uVar9, 0, 0);
                }
            }
            else if (iVar5 == 2) uVar7 = QURAMWINKI_DecodeBMP(...);
            else if (iVar5 == 3) uVar7 = decodeQPNG(...);
            ...
asmQuramGetImageInfoFromBuffer:
  add  x1, x0, w1, sxtw      ; buf + offset
  mov  x19, x4               ; int *height
  mov  x20, x3               ; int *width
  mov  w0, #1                ; memory stream
  mov  w3, #7                ; color format
  bl   QURAMWINK_CreateDecInfo
  ...
  bl   QURAMWINK_Parser      ; returns the image type
  ldp  w8, w9, [sp]
  str  w8, [x20]             ; *width
  str  w9, [x19]             ; *height

That gives us the prototypes:

cint QuramGetImageInfoFromBuffer(const uint8_t *buf, int offset, int size, int *width, int *height);
int QuramDecodeBuffer(const uint8_t *buf, void *out, int size, int color_format, int sample_size);
Tip: the library tells you why it rejected your input. Quram logs [function:line] on almost every error path. Keep adb logcat | grep -E 'QJPEG|QURAM' open while you write the harness and seeds. It saved us hours (see Step 4).

Step 3: The harness

The harness mirrors the platform decoder: parse the header, size an ARGB8888 output buffer, decode. harness/harness.c:

c#include <stdint.h>
#include <stdlib.h>

/* returns the image type (1 = JPEG, 2 = BMP, 3 = PNG, 4/6 = GIF, 5 = WBMP, 8 = TIFF) */
extern int QuramGetImageInfoFromBuffer(const uint8_t *buf, int offset, int size,
                                       int *width, int *height);
/* returns non-zero on success; writes width*height*bpp bytes into out */
extern int QuramDecodeBuffer(const uint8_t *buf, void *out, int size,
                             int color_format, int sample_size);

#define QURAM_IMAGE_JPEG      1
#define QURAM_COLOR_ARGB8888  7     /* 7 and 8 are the 4-byte-per-pixel formats */
#define MAX_INPUT_SIZE        (1 << 20)
#define MAX_PIXELS            (8192u * 8192u)

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    int width = 0, height = 0;

    if (size < 4 || size > MAX_INPUT_SIZE)
        return 0;

    /* Header parse only: tells us the type and how big the output must be. */
    if (QuramGetImageInfoFromBuffer(data, 0, (int)size, &width, &height) != QURAM_IMAGE_JPEG)
        return 0;
    if (width <= 0 || height <= 0 || (uint64_t)width * (uint64_t)height > MAX_PIXELS)
        return 0;

    /* Same sizing the platform decoder uses: one ARGB8888 frame at sample size 1. */
    void *out = malloc((size_t)width * (size_t)height * 4);
    if (!out)
        return 0;

    QuramDecodeBuffer(data, out, (int)size, QURAM_COLOR_ARGB8888, 1);

    free(out);
    return 0;
}

Three design decisions:

  • Only JPEG. QuramDecodeBuffer also routes BMP/PNG/GIF/WBMP/TIFF. Restricting to type 1 keeps the campaign on the JPEG decoder, where the bug is.
  • Link against the vendor .so. We pass -limagecodec.quram at link time, so the library becomes a DT_NEEDED dependency of libharness.so. When the fuzzer dlopens the harness, the target is mapped before FridaInstrumentationHelper builds its module map (see Part 3.1).
  • A pixel cap. Without it the fuzzer will happily set the width and height to 65535 and spend its time in malloc.

harness/runner.c is a tiny main() that reads files and calls LLVMFuzzerTestOneInput, used for reproduction. harness/build.sh builds three artifacts:

bashNDK=$HOME/Library/Android/sdk/ndk/29.0.14206865
CC=$NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android31-clang
LINK="-L../device_libs -limagecodec.quram -Wl,-rpath,\$ORIGIN"

$CC -O1 -g -fPIC -shared harness.c -o ../out/libharness.so $LINK            # for the fuzzer
$CC -O1 -g harness.c runner.c -o ../out/runner $LINK                       # plain reproducer
$CC -O1 -g -fsanitize=address -fno-omit-frame-pointer \
    harness.c runner.c -o ../out/runner_asan $LINK                         # ASan reproducer
cp $(find $NDK -name libclang_rt.asan-aarch64-android.so | head -1) ../out/

A first check on the phone, as the shell user:

bash$ adb shell mkdir -p /data/local/tmp/quram
$ adb push out/* /data/local/tmp/quram/
$ adb shell 'cd /data/local/tmp/quram && LD_LIBRARY_PATH=. ./runner seeds/pil_prog_420_32x32.jpg'
[*] running seeds/pil_prog_420_32x32.jpg (666 bytes)
[+] seeds/pil_prog_420_32x32.jpg: no crash
From userland crashes to ring 0
Get both Android exploitation tracks on Black Friday
Continue with Android Userland Fuzzing & Exploitation and Android Kernel Fuzzing & Exploitation. The Black Friday bundle includes both courses, CAED and CASR exams, and lifetime course access.
View bundle →

Step 4: Seeds, and what Quram is picky about

Seed quality decides whether a campaign finds anything in minutes or never. Here are some things we learned the hard way, using the logcat trick.

Quram needs AC Huffman tables even for DC-only scans. Our first hand-built progressive JPEG was rejected:

textI QJPEG   : [WINKJ_DecodeFrame:6151]
I QURAM_STAT: [QuramDecodeBuffer:958]

Decompiling WINKJ_SetupScan shows why. For every scan component it builds derived tables for both the DC and the AC table (WINKJ_PrepareDerivedTbl(ctx, 1, dc_tbl…) and (ctx, 0, ac_tbl…)), and returns 0xc9 if either is missing. The same thing kills jpegtran -scans output, which defines only DC tables before DC scans. A whole family of tool-generated seeds is dead on arrival.

The SOS parser partially checks component order. For each scan selector, WINKJ_ParseNextMarker searches the frame for the matching component ID (cmp w5, w14 at 0x12b7bc) and rejects it if a "used" slot is set. The slot is checked by frame index but set by scan index (str x8, [x23, x10], x10 = k*8). In practice the k-th scan component must have frame index ≥ k. So [1,2,3], [1,3], [2,3] and [3,2] pass, while [2,1] or [1,1,3] are rejected with [WINKJ_ParseNextMarker:23177, compId : 1, …]. For a full scan (Ns == Nf) the only order that passes is frame order, so the bug can only be reached through a scan that selects a subset of the components, which is exactly what both P0 PoCs do.

Quram can't decode some perfectly legal scan scripts. For a later single-component scan, WINKJ_SetupScan reads ctx->scan_comp[ctx->last_frame_index] (ctx + 0x160 + ctx[0x2f0]*8), indexing a scan-ordered array with a frame index. That's the same index-space confusion as the CVE, just less dangerous. A legal file whose DC scans are [1,2] then [3] fails in WINKJ_InitDecBeforeScan:17696.

With that knowledge, harness/make_seeds.py produces two families of valid images:

  1. Encoder output: Pillow progressive JPEGs in 4:4:4, 4:2:2, 4:2:0 and grayscale.
  2. Hand-assembled progressive JPEGs covering every legal way to group three components into DC scans ([1,2,3], [1,2]+[3], [1]+[2,3], [1,3]+[2], [1]+[2]+[3]) × 4 chroma subsamplings. Each is a flat grey image with one shared DC table (only "diff = 0") and one shared AC table (only EOB) defined up front, and exactly as many entropy bits as each scan needs. Each also gets a _trunc twin that stops after the first scan, which is what a partially downloaded progressive JPEG looks like, and decoders are built to accept that.
pythondef progressive_jpeg(w, h, sampling, dc_groups, truncate=False):
    hmax = max(s[0] for s in sampling); vmax = max(s[1] for s in sampling)
    mcux, mcuy = math.ceil(w / (8 * hmax)), math.ceil(h / (8 * vmax))
    ...
    jpg += seg(0xC4, b"\x00" + bytes([1] + [0] * 15) + b"\x00")   # DC0: '0' -> diff 0
    jpg += seg(0xC4, b"\x10" + bytes([1] + [0] * 15) + b"\x00")   # AC0: '0' -> EOB
    for group in dc_groups:                                       # DC first scans
        bits = blocks(group[0]) if len(group) == 1 else \
               mcux * mcuy * sum(sampling[c][0] * sampling[c][1] for c in group)
        jpg += sos(group, 0, 0) + entropy(bits)
        if truncate:
            return jpg + b"\xff\xd9"
    for c in range(len(sampling)):                                # AC scans, EOB per block
        jpg += sos([c], 1, 63) + entropy(blocks(c))
    return jpg + b"\xff\xd9"
bash$ python3 harness/make_seeds.py seeds      # 45 files, 154–793 bytes

Every seed was checked on the phone: none of them crashes, and all the truncated ones decode successfully. The bug needs a component-sampling mismatch that no seed has; the fuzzer has to invent it.

Step 5: The fuzzer

The fuzzer is LibAFL's fuzzers/binary_only/frida_libpng example adapted for Android and JPEG. fuzzer/Cargo.toml:

toml[package]
name = "quram_frida_fuzzer"
version = "0.1.0"
edition = "2021"

[profile.release]
lto = true
codegen-units = 1
opt-level = 3
debug = true
panic = "abort"

[dependencies]
libafl = { path = "../vendor/LibAFL/crates/libafl", features = [
  "std", "llmp_compression", "llmp_bind_public", "frida_cli", "errors_backtrace",
] }
libafl_bolts = { path = "../vendor/LibAFL/crates/libafl_bolts" }
libafl_frida = { path = "../vendor/LibAFL/crates/libafl_frida", features = ["cmplog"] }
libafl_targets = { path = "../vendor/LibAFL/crates/libafl_targets", features = ["sancov_cmplog"] }
frida-gum = { version = "0.17.1", features = ["auto-download", "event-sink", "invocation-listener"] }
libloading = "0.8.5"
log = { version = "0.4.22", features = ["release_max_level_info"] }
env_logger = "0.11.5"
mimalloc = { version = "0.1.43", features = ["local_dynamic_tls"] }

[build-dependencies]
cc = "1"
  • frida_cli gives us LibAFL's standard Frida command line (-H, -l, -A, -C, --cmplog-cores, …) through libafl_bolts::cli::FuzzerOptions.
  • frida-gum/auto-download fetches the prebuilt Gum devkit for android-arm64 at build time. No Frida build is needed.
  • panic = "abort": a Rust panic inside a client must look like a crash to the restarting manager, not like a clean exit().
  • mimalloc as the global allocator keeps the fuzzer's own allocations away from libc malloc, which the Frida ASan runtime would otherwise intercept.

build.rs handles two Android-specific link problems with the Gum devkit:

rust// The frida-gum devkit links against -lresolv, which bionic does not ship
// (resolver lives in libc). An empty archive satisfies the linker.
let stub = out_dir.join("libresolv.a");
Command::new("llvm-ar").args(["crs"]).arg(&stub).status()?;
println!("cargo:rustc-link-search=native={}", out_dir.display());

// The devkit also references __clear_cache, a compiler-rt builtin the NDK does not
// export to Rust links. Provide it with explicit AArch64 cache maintenance
// (dc cvau / ic ivau), since __builtin___clear_cache would recurse.
cc::Build::new().file(&clear_cache_c).compile("clear_cache_stub");

__clear_cache matters more than it looks. It is how Stalker makes freshly written code visible to the instruction cache on ARM, so the stub has to really clean the D-cache and invalidate the I-cache.

Now src/main.rs, piece by piece.

Loading the harness (and, through it, the target):

rustlet lib = unsafe { libloading::Library::new(options.harness.clone().unwrap()).unwrap() };
let target_func: libloading::Symbol<unsafe extern "C" fn(*const u8, usize) -> i32> =
    unsafe { lib.get(options.harness_function.as_bytes()).unwrap() };

let mut frida_harness = |input: &BytesInput| {
    let target = input.target_bytes();
    let buf = target.as_slice();
    unsafe { target_func(buf.as_ptr(), buf.len()) };
    ExitKind::Ok
};

This must run before the helper is created. That's the load-order rule from Part 3.1.

The Frida runtimes and the helper:

rustlet gum = Gum::obtain();
let coverage = CoverageRuntime::new();
let asan = AsanRuntime::new(options);
let cmplog = CmpLogRuntime::new();

let frida_helper = Rc::new(RefCell::new(FridaInstrumentationHelper::new(
    &gum,
    options, // -l <lib> restricts instrumentation to the target library
    tuple_list!(
        IfElseRuntime::new(move || Ok(is_asan(&opts_a, &client_a)),   tuple_list!(asan),   tuple_list!()),
        IfElseRuntime::new(move || Ok(is_cmplog(&opts_c, &client_c)), tuple_list!(cmplog), tuple_list!()),
        coverage
    ),
)));

IfElseRuntime lets each client decide at start-up whether it carries a runtime. With -C --cmplog-cores 1-2, only clients 1 and 2 pay for CmpLog, and every client gets coverage.

Observers, feedbacks and objectives:

rust// The edge map *is* the CoverageRuntime's array that the injected code increments
let edges_observer = HitcountsMapObserver::new(unsafe {
    StdMapObserver::from_mut_ptr("edges", frida_helper.borrow_mut().map_mut_ptr().unwrap(), MAP_SIZE)
}).track_indices();
let time_observer = TimeObserver::new("time");
let asan_observer = AsanErrorsObserver::from_static_asan_errors();
let frida_helper_observer = FridaHelperObserver::new(Rc::clone(&frida_helper));

let mut feedback = feedback_or!(MaxMapFeedback::new(&edges_observer),   // new edges / hitcounts
                                TimeFeedback::new(&time_observer));
let mut objective = feedback_or_fast!(CrashFeedback::new(),               // SIGSEGV, SIGABRT...
                                      AsanErrorsFeedback::new(&asan_observer),
                                      TimeoutFeedback::new());

State, dictionary, mutator, scheduler. The JPEG dictionary is small: markers, plus the sampling-factor bytes (0x11, 0x12, 0x21, 0x22, 0x41) a SOF parser compares against:

rustfn jpeg_tokens() -> Tokens {
    Tokens::from([
        vec![0xFF, 0xD8], vec![0xFF, 0xD9],              // SOI, EOI
        vec![0xFF, 0xC0], vec![0xFF, 0xC2],              // SOF0, SOF2 (progressive)
        vec![0xFF, 0xC4], vec![0xFF, 0xDB], vec![0xFF, 0xDA], vec![0xFF, 0xDD],
        vec![0xFF, 0xE0], vec![0xFF, 0xE1],
        vec![0x11], vec![0x12], vec![0x21], vec![0x22], vec![0x41],
        b"JFIF\0".to_vec(), b"Exif\0\0".to_vec(),
    ])
}
...
let mutator = HavocScheduledMutator::new(havoc_mutations().merge(tokens_mutations()));
let scheduler = IndexesLenTimeMinimizerScheduler::new(&edges_observer, QueueScheduler::new());
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);

The executor:

rustlet executor = FridaInProcessExecutor::new(
    &gum,
    InProcessExecutor::with_timeout(&mut frida_harness, observers, &mut fuzzer,
                                    &mut state, &mut mgr, options.timeout)?,
    Rc::clone(&frida_helper),
);
let cmplog_observer = CmpLogObserver::new("cmplog", true);
let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer));

InProcessExecutor installs the signal handlers: on SIGSEGV it writes the current input to crashes/, and the restarting event manager respawns the client from its last serialized state. FridaInProcessExecutor adds Stalker control. ShadowExecutor adds the second, CmpLog-enabled run used by the I2S stage.

Stages and launch:

rustlet mut stages = tuple_list!(
    IfElseStage::new(|_, _, _, _| Ok(is_cmplog(options, &client_description)),
                     tuple_list!(ShadowTracingStage::new(), i2s), tuple_list!()),
    StdMutationalStage::new(mutator)
);
fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)?;
...
Launcher::builder()
    .configuration(EventConfig::AlwaysUnique)
    .shmem_provider(StdShMemProvider::new()?)   // ashmem-backed on Android
    .monitor(MultiMonitor::new(|s| println!("{s}")))
    .run_client(&mut run_client)
    .cores(&options.cores)
    .broker_port(options.broker_port)
    .stdout_file(Some(&options.stdout))
    .build()
    .launch()

The Launcher forks one broker and one client per core. They talk over LLMP (shared memory, plus TCP on port 1337 for the broker), and that all works for the shell user.

Building for Android:

bash$ export ANDROID_NDK_HOME=$HOME/Library/Android/sdk/ndk/29.0.14206865
$ export PATH=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin:$PATH
$ cd fuzzer
$ RUSTFLAGS="--cap-lints=warn" cargo ndk -t arm64-v8a build --release
    Finished `release` profile [optimized + debuginfo] target(s) in 1m 03s
Why --cap-lints=warn? LibAFL's workspace denies warnings. Path dependencies get the same lint levels as your own crate, so a newer rustc (or a newer wide crate) turns deprecation warnings inside libafl_bolts into hard errors. Capping lints is cleaner than patching LibAFL.

The binary dynamically links libc++_shared.so from the NDK, so push it alongside.

Step 6: Run it on the (unrooted) phone

bash$ adb push fuzzer/target/aarch64-linux-android/release/quram_frida_fuzzer \
           out/libharness.so out/libimagecodec.quram.so \
           $ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/sysroot/usr/lib/aarch64-linux-android/libc++_shared.so \
           /data/local/tmp/quram/
$ adb push seeds /data/local/tmp/quram/seeds
$ adb shell
pa1q:/ $ cd /data/local/tmp/quram
pa1q:/data/local/tmp/quram $ LD_LIBRARY_PATH=. ./quram_frida_fuzzer \
      -H ./libharness.so \
      -l libimagecodec.quram.so \
      -i seeds -o crashes \
      -c 0-7 -C --cmplog-cores 1-2 \
      -t 2000 -s clients.log
Flag Meaning
-H ./libharness.so harness to dlopen; -F defaults to LLVMFuzzerTestOneInput
-l libimagecodec.quram.so instrument only this module (plus the harness)
-c 0-7 8 clients, one per core
-C --cmplog-cores 1-2 CmpLog runtime + I2S stage on clients 1 and 2
-t 2000 timeout in ms
-s clients.log client stdout (the broker prints the stats)

(scripts/run_on_device.sh does the push and launch in one go, detached with nohup setsid so you can unplug.)

A single-core run first, to confirm that Stalker works in the shell domain:

text[INFO  libafl_frida::executor] Fuzzer range: 60dfcc8000-60e45b6000
[INFO  libafl_frida::executor] disable_excludes: false
[INFO  libafl::state] 45 total_corpus_size, 1 cores
[INFO  libafl::state] Loading file seeds/gen_440_dc123_32x32_trunc.jpg ...
[INFO  libafl_frida::executor] Activating Stalker for 0x7fd4b69570
...
[UserStats #1] (GLOBAL) run time: 44s, clients: 1, corpus: 787, objectives: 0,
               executions: 268570, exec/sec: 6.074k, edges: 7.661%

Over 6,000 executions per second on one core, against a closed-source vendor library, on a stock phone.


Part 6: Results

Campaign A: the full seed corpus (45 seeds, 8 cores)

text[Objective #8]  (GLOBAL) run time: 0s, clients: 8, corpus: 2326, objectives: 1, executions: 52961, ...
[UserStats #7]  (GLOBAL) run time: 9s, clients: 8, corpus: 5459, objectives: 2, executions: 288079, exec/sec: 30.78k, edges: 8.666%
Your browser does not support embedded video. Watch the crash being found.
The moment client #2 records its first objective. The enlarged terminal strip keeps the objectives: 1 crash line visible as the other clients continue fuzzing.

The first crash arrived within the first second, after 11,660 executions on the client that found it. Diffing the crash against its closest seed shows the decisive mutation:

textclosest seed: gen_440_dc13_2_32x32.jpg
  offset 0x58 (SOF2, component 3 sampling byte):  11 -> 12      # V: 1 -> 2
  (plus incidental havoc noise in DQT and entropy data)

One byte. The seed already had a legal subset scan ([1,3] then [2]). The fuzzer made component 3 vertically twice as large as component 2, and that was enough.

Campaign B: "hard mode" (29 seeds, no subset scans)

That's a bit easy, so we removed every seed whose first scan selects a subset of components (dc12_3, dc13_2 and their truncated twins). In the remaining 29 seeds the first scan is always either all three components or only component 1, and both take the safe path through WINKJ_ProgIDct. The fuzzer now has to reach the scan-ordered path and create the sampling mismatch on its own:

text[Objective #5]  (GLOBAL) run time: 8s, clients: 8, corpus: 4296, objectives: 1, executions: 242927, exec/sec: 29.03k, edges: 6.464%
...
[Client Heartbeat #2] (GLOBAL) run time: 3m-27s, clients: 8, corpus: 16487, objectives: 13, executions: 1856940, exec/sec: 8.965k, edges: 17.862%

First crash after 8 seconds (242,927 executions across all clients), 13 objectives in 3.5 minutes. The rate drops from ~30k to ~9k exec/s as the phone heats up and the corpus grows. A phone is not a server, so keep that in mind for long campaigns.

The first hard-mode crash looks like this (harness/jpeg_info.py):

text== crashes/crash_hardmode.jpg
0x0056 SOF2 (progressive)  16x32  precision=8  components=3
         frame[0] id=1 H=2 V=1 Tq=0
         frame[1] id=2 H=1 V=2 Tq=0          ← mutated 0x11 -> 0x12
         frame[2] id=3 H=1 V=1 Tq=0
0x0069 DHT  len=20
0x009a SOS  Ns=2 comps=[2, 3]  Ss=0 Se=0 Ah=0 Al=0     ← now the FIRST scan
...
0x012a SOF2 (progressive)  0x0  precision=8  components=255   ← spliced junk, ignored

The hex shows how the fuzzer got there. It started from a 4:2:2 seed whose DC scans were [1] then [2,3]. In that layout the first scan is single-component, so WINKJ_ProgIDct takes the safe frame-order path. The fuzzer then overwrote the FF DA marker of the leading [1] scan with FF FF:

text0x8e:  ff ff 00 08 01 01 00 00 00 00      ← was: ff da 00 08 01 01 00 00 00 00  (SOS [1])
0x9a:  ff da 00 0a 02 02 00 03 00 00 00 00  SOS [2,3]

FF FF is legal fill between markers, so the decoder skips it and the [2,3] scan becomes the first scan. That flips the IDCT pass onto the scan-ordered path. Together with component 2 now being vertically sampled ×2, scan index 0 drives component 2's geometry (V=2) into component 1's buffer (V=1). Nobody told the fuzzer what a "first scan" is; coverage feedback found that path.

All 12 hard-mode objectives we triaged land on the same instruction (more on that below), so this is one bug, not twelve.


Part 7: Triage

On-device evidence in Samsung Gallery

We also checked the crash through Samsung Gallery's real decoding path. Opening the crashing image closes Gallery immediately, and logcat then shows the SIGSEGV and null-pointer write.

Your browser does not support embedded video. Watch the on-device crash evidence.
On-device evidence: Gallery closes as the crashing image opens, followed by the highlighted SIGSEGV entry in logcat. The logcat section plays at 1.6×.

Reproduce without the fuzzer

bash$ cp crashes/35d5fb9e1729cff0 crashes/crash_vertical.jpg
$ adb push crashes/crash_vertical.jpg /data/local/tmp/quram/
$ adb shell 'cd /data/local/tmp/quram && LD_LIBRARY_PATH=. ./runner crash_vertical.jpg'
[*] running crash_vertical.jpg (198 bytes)
Segmentation fault

The tombstone (from adb logcat), symbolized against the library's export table with harness/symbolize.py, which maps each offset to the nearest preceding exported function:

textsignal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0000000000000000 (write)
Cause: null pointer dereference
    x0  b400007b9935cac0  x1  b400007b9935cb00  x2  b400007ca9355888  x3  0000000000000000
    x9  b400007b9935c8c0  x10 0000000000000000  x11 b400007b9935c8c0  x12 b400007b9935c900
    x13 b400007b9935c940  x14 b400007b9935c980  x20 0000000000000001  x21 b400007ca9355848
backtrace:
  #00 pc 24bb00  libimagecodec.quram.so   <sub_24b800 [WINKJ_DoIdct_islow NEON kernel]+0x300>
  #01 pc 18dfa0  libimagecodec.quram.so   <WINKJ_ProgIDct+0x38c>
  #02 pc 1377ac  libimagecodec.quram.so   <WINKJ_ProgDecodeSingleiMcu+0xac4>
  #03 pc 12d0c4  libimagecodec.quram.so   <WINKJ_ProgProcessData+0xec>
  #04 pc 1332b0  libimagecodec.quram.so   <WINKJ_DecodeImage+0xd50>
  #05 pc 12e4f8  libimagecodec.quram.so   <QURAMWINK_DecodeJPEG+0x4a0>
  #06 pc 1306d0  libimagecodec.quram.so   <QURAMWINK_PDecodeJPEG+0x244>
  #07 pc 1aab70  libimagecodec.quram.so   <QuramDecodeBuffer+0x1cc>
  #08 pc 004b14  runner

Frames #01–#07 match P0's Gallery crash frame for frame: WINKJ_ProgIDct → WINKJ_ProgDecodeSingleiMcu → WINKJ_ProgProcessData → WINKJ_DecodeImage → QURAMWINK_DecodeJPEG → QURAMWINK_PDecodeJPEG → QuramDecodeBuffer. Frame #00 is an unexported NEON IDCT kernel at 0x24b800, which P0 calls WINKJ_DoIdct_islow.

Rebuild with ASan and replay

The ASan reproducer was already built by harness/build.sh (-fsanitize=address -fno-omit-frame-pointer). On Android an ASan executable just needs the runtime next to it:

bash$ adb shell 'cd /data/local/tmp/quram && \
    LD_LIBRARY_PATH=. ASAN_OPTIONS=fast_unwind_on_fatal=1 ./runner_asan crash_vertical.jpg'
AddressSanitizer report showing a write to 0xbebebebebebebebe in libimagecodec.quram.so at offset 0x24bb00, followed by the Quram decoder stack
The ASan replay: a write to 0xbebebebebebebebe in the NEON IDCT kernel, with the Quram decoder frames below it. Select the image to inspect the full-resolution report.

Look at the fault address: 0xbebebebebebebebe. ASan's allocator fills every fresh malloc chunk with the byte 0xbe (malloc_fill_byte). The decoder didn't just write out of bounds; it wrote through a pointer it had loaded from uninitialized heap memory, word for word P0's "Manifestation B". Without ASan the same slot happened to hold 0 (Scudo hands out zeroed memory), so the plain run showed a NULL write.

A second AddressSanitizer crash replay showing the same poisoned 0xbebebebebebebebe destination and write access with a shorter recovered stack
Another crashing input produces the same poisoned destination and write access. This replay also shows how the recovered stack can be shorter when the unwinder cannot get through every frame.

Two notes on ASan with closed-source code:

  • ASan only checks accesses in instrumented code. Our harness is instrumented; libimagecodec.quram.so is not, so ASan can't say "heap-buffer-overflow" for a store inside it. What it gives us here is its allocator (poisoned fill patterns, different heap layout), its signal handler and its report. The 0xbe pattern is what proves the uninitialized-pointer story.
  • WINKJ_ProgIDct is missing from the ASan stack: the frame-pointer unwinder skips over it because the leaf NEON kernel never sets up a frame. The tombstone has the full chain. fast_unwind_on_fatal=1 matters on Android; the default slow unwinder couldn't get through the signal frame at all.

Part 8: Root cause

The vulnerable loop, at instruction level

Here is the component loop of WINKJ_ProgIDct (full-resolution islow arm). x0 = decoder context, x12 = loop counter i running over the frame's component count (ctx+0x11d0):

asm18de64  ldr   w9,  [x0, #0x118c]       ; ctx->first_scan_is_single_component
18de68  add   x14, x0, x12, lsl #3     ; &ctx->scan_comp[i] - 0x160
18de6c  cmp   w9,  #1
18de70  b.ne  18de94
18de74  mov   w10, #0x58               ; ── path 1: geometry in FRAME order ──
18de78  ldr   x9,  [x0, #0x158]
18de80  madd  x28, x12, x10, x9        ;   x28 = &ctx->frame_comp[i]
        ...
18de94  ldr   x28, [x14, #0x160]       ; ── path 2: geometry in SCAN order ──
                                       ;   x28 = ctx->scan_comp[i]
18dea0  ldrb  w9,  [x28, #0x3]         ; row_groups = geometry->v_samp
        ...
18ded0  ldr   w9,  [x24, #0x20]!       ; sanity check: geometry->h_blocks * (mcus-1)
18ded4  ldur  w10, [x24, #-0x8]        ;   <= geometry->width_in_blocks ?
18dedc  cmp   w9,  w10                 ;   (checks the geometry against ITSELF,
18dee0  b.hi  18eb04                   ;    never against the destination buffer)
        ...
18defc  ldr   x21, [x8, x12, lsl #3]   ; x21 = out_rows[i]   ← destination in FRAME order
        ...
18df18  add   x21, x21, #0x40          ; next row group: advance 8 row pointers
        ...
18df90  ldr   x0,  [x28, #0x48]        ; dequant table of the *geometry* component
18df94  mov   x1,  x23                 ; coefficient block
18df98  mov   x2,  x21                 ; 8 output row pointers  (destination's array)
18df9c  mov   w3,  w22                 ; output column
18dfa0  bl    sub_24b800               ; IDCT → 8 stores: *(x2[r] + col) = row r

Decompiled, it's almost exactly P0's pseudocode:

cfor (i = 0; i < ctx->num_frame_components; i++) {
    comp = ctx->first_scan_is_single_component ? &ctx->frame_comp[i]    // frame order
                                               :  ctx->scan_comp[i];     // SCAN order
    JSAMPROW *rows = out_rows[i];                                         // FRAME order
    for (r = 0; r < comp->v_samp; r++) {                  // vertical extent from comp
        for (col = 0; col <= comp->mcus_per_row; col++)    // horizontal extent from comp
            for (b = 0; b < comp->h_blocks; b++)
                idct_islow(comp->dqt, coef, rows, outcol += 8);
        rows += 8;                                         // 8 more row pointers
    }
}

comp and rows come from two different index spaces that share the counter i. They name the same component only when the scan lists the frame's components contiguously and in frame order.

Mapping it onto our crash

The fuzzer's crash_vertical.jpg:

textSOF2 32x32, 3 components:
   frame[0] id=1 H=1 V=2
   frame[1] id=2 H=1 V=1        ← its row-pointer array is sized for V=1
   frame[2] id=3 H=1 V=2        ← fuzzer: 0x11 -> 0x12
SOS  Ns=2 comps=[1, 3]  Ss=0 Se=0     (first scan, not single-component → scan order)
i geometry scan_comp[i] destination out_rows[i] result
0 comp 1 (V=2) comp 1's rows fine
1 comp 3 (V=2) comp 2's rows (V=1) 2 row groups into a 1-group array
2 stale/unbound comp 3's rows (never reached)

At i = 1, row group r = 1 (the extra group that only exists because comp 3 has V=2) advances x21 past the end of comp 2's row-pointer array (18df18). The kernel then loads 8 "row pointers" from whatever follows on the heap, and the crash registers show exactly that:

  • x20 = 1: we are in row group r = 1, the surplus one.
  • x21 = …5848, x2 = …5888 = x21 + 0x40: the kernel has consumed 8 pointers from the out-of-bounds cursor (ldp x11, x12, [x2], #0x10 …).
  • The "row pointers": x0 = …cac0, x1 = …cb00, x9 = …c8c0, x10 = 0, x11 = …c8c0, x12 = …c900 … are leftover heap contents, not row pointers. Row 3 is NULL, and the faulting instruction is st1 {v29.d}[1], [x10] at 0x24bb00.

So what gets written is attacker-influenced IDCT output (pixel data computed from the file's coefficients and quantization tables), and where it gets written is whatever 8-byte values sit after the row-pointer array in the heap. Under the system allocator that's NULL or stale pointers; under ASan it's 0xbebebebebebebebe.

The horizontal variant: a heap overflow that becomes a controlled free()

The same bug with a horizontal mismatch gives P0's "Manifestation A". We derived it from the fuzzer's crash by hand (variant analysis): give comp 3 H=2 V=1 (twice comp 2's width), keep the [1,3] scan, and widen the frame so comp 2's buffer becomes a large, page-backed allocation:

bash$ python3 harness/jpeg_info.py crashes/crash_horizontal.jpg | sed -n '3,6p'
0x0049 SOF2 (progressive)  65520x32  precision=8  components=3
         frame[0] id=1 H=1 V=1 Tq=0
         frame[1] id=2 H=1 V=1 Tq=0
         frame[2] id=3 H=2 V=1 Tq=0

On the stock allocator it faults exactly like P0's Gallery crash: a write with SEGV_ACCERR on a page-aligned address, i.e. the IDCT ran off the end of a Scudo secondary allocation into its guard page:

textsignal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0xb400007bad163000 (write)
  #00 pc 24bb10  libimagecodec.quram.so   <sub_24b800 [WINKJ_DoIdct_islow NEON kernel]+0x310>
  #01 pc 18dfa0  libimagecodec.quram.so   <WINKJ_ProgIDct+0x38c>
  #02 pc 1377ac  libimagecodec.quram.so   <WINKJ_ProgDecodeSingleiMcu+0xac4>
  #03 pc 12d0c4  libimagecodec.quram.so   <WINKJ_ProgProcessData+0xec>

Under the ASan build there is no guard page right behind the buffer, so the overflow doesn't fault. It keeps writing, and the program dies later, somewhere else.

In this replay, ASan reports a read from 0x8080808080808070 while its free() implementation reads a chunk header. The call chain reaches that cleanup through WINKJ_DeleteDecoderInfo → WINKJ_DecodeImage → QURAMWINK_DecodeJPEG:

asm128c70  ldur  x0, [x9, #-0x8]       ; raw malloc() pointer stored before an aligned block
128c74  bl    QURAMWINK_OsFree      ; → free(x0)

Quram's aligned allocator stores the original malloc pointer just before each 16-byte-aligned block (you can see the *(aligned - 8) = raw pattern in WINKJ_SetupScan). Our overflow overwrote that slot with pixel data: 0x80 is sample value 128, the flat grey of our image. The decoder's cleanup then calls free(0x8080808080808080), and ASan faults reading the fake chunk's header at -0x10.

That turns the bug from "decoder crashes" into "bytes the attacker controls reach free() as a pointer". That's the kind of primitive exploits are built on, and it's why P0 rates this "memory corruption with potential for remote code execution". (We stop at the primitive here.)

Why the fuzzer found it so fast

  • One byte unlocks it. With a subset scan in place, a single sampling-factor byte creates the mismatch, and havoc flips single bytes constantly. The dictionary's 0x12/0x21/0x22 tokens make the right values even more likely.
  • Coverage leads there. Different sampling factors and scan layouts exercise different MCU-geometry code in WINKJ_ProgIDct, WINKJ_SetupScan and the entropy decoders, so the intermediate inputs are "interesting" and stay in the corpus.
  • CmpLog knows the component IDs. The SOS selector lookup is a cmp, so the I2S stage can rewrite selectors to valid IDs instead of guessing.
  • The vertical variant faults on its own. Writing through garbage row pointers crashes even on a 32×32 image, so a plain CrashFeedback is enough. The horizontal variant on a small image silently corrupts the heap, and that's where binary-only ASan would have helped (next section).

Part 9: Frida ASan on Android, what we hit

We wanted to run some clients with -A --asan-cores … so silent heap overflows would be caught too. On this phone, LibAFL 0.16's Frida ASan didn't start, and the reasons are useful to know:

  1. 39-bit address space. Android arm64 kernels commonly give user space 39 bits (our highest mapping was 0x7fcfa65000). The ASan allocator only tries shadow bits ≥ 44, i.e. a shadow at 16 TB, which can never be mapped here: assertion failed: shadow_bit != 0 (allocator.rs). Starting the search at bit 36 on Android (shadow at 64 GB, 3 << 36 < 1 << 39) fixes it: shadow_bit 36 is suitable.
  2. has_tls() reads the wrong register. On aarch64, libafl_bolts::has_tls() reads TPIDRRO_EL0, which holds the thread pointer only on Apple platforms. On Linux/Android it's 0, so the first hooked free() dereferenced 0 + 0x102*8 = 0x810 (symbolized: libafl_bolts::has_tls → AsanRuntime::register_hooks::replacement_free). Restricting that branch to target_vendor = "apple" fixes it.
  3. A deadlock in unpoison_all_existing_memory(). Once the libc allocator hooks are live, Frida's own range enumeration blocks on a futex. It's the same enumeration call that works fine before the hooks are installed. Fixing that means untangling Gum's internal allocations from the ASan hooks, which is beyond this post.

Fixes 1 and 2 are in fuzzer/patches/frida-asan-android-partial.patch if you want to go further. For this campaign we didn't need ASan in the fuzzer: crash detection plus an ASan reproducer was enough.


Gotchas collected along the way

  • Load the target before creating the helper. Otherwise there's nothing to instrument and coverage stays at 0. Link the harness against the target, or dlopen it in LLVMFuzzerInitialize and call that first.
  • Don't pkill -f quram_frida_fuzzer through adb shell '...'. The pattern matches the adb shell's own command line and kills it. Use kill $(pidof quram_frida_fuzzer).
  • git archive + cargo: restored files keep their old commit mtimes, so cargo thinks nothing changed. touch them after restoring.
  • fast_unwind_on_fatal=1 for ASan on Android, or you may get a stack that stops in the signal frame.
  • Watch the temperature. Throughput dropped from 30k to 9k exec/s in a few minutes. Fewer cores at a steady rate can beat eight throttled ones.
  • Use the library's own logging. logcat | grep QJPEG turned every rejected seed into a [function:line] we could jump to in the disassembler.

Conclusion

We took a closed-source Samsung system library, pulled it off an unrooted Galaxy S25, and fuzzed it on the phone with LibAFL Frida mode at up to 30,000 executions per second. Frida Stalker recompiled the library's code on the fly with AFL-style edge coverage and comparison logging. LibAFL turned that into a multi-core, coverage-guided fuzzer with a few hundred lines of Rust.

Starting from ordinary progressive JPEGs, the fuzzer rediscovered CVE-2026-21096 within seconds, in both an easy and a "hard mode" seed setup. Rebuilding the harness with AddressSanitizer exposed the poisoned 0xbebebebebebebebe row pointer that proves the uninitialized-pointer write. Reading the WINKJ_ProgIDct loop at instruction level showed the one-line root cause: geometry taken from the scan-ordered array, destination taken from the frame-ordered array. The horizontal variant showed what an attacker can do with it: pixel data ends up as an argument to free().

Compared with QEMU mode from the previous post, Frida mode trades emulation for reality: the real CPU, the real linker namespace, the real allocator and the real library build, all on a stock device. The price is that you're inside the target process, so load order, exclusions, signal handling and platform quirks (like the 39-bit address space) are your problem. That's also why it finds bugs the way they happen in the field.

Credits: CVE-2026-21096 was found and reported by Brendon Tiszka and Mateusz Jurczyk of Google Project Zero (issue 527860114) and fixed by Samsung in the September 2026 security update. If your device's security patch level is earlier than that, update it.

Continue from crash to exploit
Learn Android Userland Fuzzing & Exploitation
If you enjoyed this LibAFL Frida-mode deep dive, expand your toolkit with AFL++, libFuzzer, QEMU, AFL Frida Mode and structure-aware fuzzing. The course also covers Android userland exploitation, including ASLR and NX bypasses, ROP, jeMalloc, Scudo and real-world 0-click proof-of-concepts.
Start learning Android exploitation →