Skip to main content

A per file pixel budget for images inside EMF and WMF files

Updated 6 min readMarkdown
A per file pixel budget for images inside EMF and WMF files

Picture opening a small drawing file, a few hundred kilobytes, and then waiting minutes while your computer churns. Nothing on screen explains why. The file is small. What's packed inside it isn't.

An audit of VectorCraft, an open source vector illustration app written in Rust, found a way a file could plausibly do that, in issue #3600. I claimed it on the issue, and my fix was merged in storytold/vectorcraft#4215.

Small files, big pictures

VectorCraft can open EMF and WMF files, older picture formats that store a drawing as a list of commands such as "draw a line here" or "fill this shape". Each command is called a record. Some records carry a bitmap, a grid of pixels, and a bitmap can even wrap a whole compressed PNG or JPEG.

Compressed images are small in a file and big in memory. To draw one, the program has to decode it, which means unpacking it into raw pixels. VectorCraft keeps each decoded pixel as RGBA: four bytes, for red, green, blue and alpha (transparency).

The gap

Each bitmap already had a limit: at most 2²⁶ pixels, which is 8192 × 8192, about 67 million pixels. Decoded, that's 256 MB. The audit, by PierrunoYT, noted that a PNG of that size can take about 65 KB in the file. Each record was checked on its own, but nothing limited the total, so a small file with many such records could cost "minutes of CPU".

Think of a buffet with a rule about the size of your plate and no rule about how many times you go back. Every single plate is fine. It's the twentieth trip that empties the kitchen.

The audit was careful about how sure it was. It rated its confidence "plausible": the missing cap was read in the source, and the slowdown wasn't run end to end. It suggested a total budget per file, for example 2²⁸ pixels, and a test where many maximum size images stop at that budget with a warning.

The reason was simple. The decoder, dib::decode, read one bitmap and remembered nothing between calls. The EMF and WMF importers called it once per image record, so every record started from zero.

The fix

One budget per file, set to the audit's figure:

pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28;

1 << 28 is 2 to the power 28, or 268,435,456 pixels: exactly four of the largest bitmap a record may hold.

The importer reads each file with one Player, which now starts with pixels_left set to that number. decode takes a new parameter, left: &mut u64, a reference it's allowed to change, so every bitmap in the file draws from the same total. Each bitmap pays through a small helper:

fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
    let n = u64::from(w) * u64::from(h);
    *left = left.checked_sub(n).ok_or(OVER_BUDGET)?;
    Ok(())
}

The cost is width times height. checked_sub subtracts only if the answer wouldn't drop below zero, and otherwise gives back "nothing". ok_or turns that "nothing" into the over budget error, and ? returns the error straight away. Because that return happens before the new value is stored, a bitmap that doesn't fit is refused and costs nothing.

Charge first, then do the work

The important part is where charge is called. A PNG or JPEG states its width and height in its header, the first few bytes of the image. So for an embedded image, the charge runs right after the existing size check on the header, and before anything is decoded:

        if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS {
            return Err("a bitmap is too large to read".into());
        }
        charge(w, h, left)?;
        let img = image::load_from_memory(bits).map_err(|_| bad())?.to_rgba8();

The slow, memory hungry step is load_from_memory, the decode itself. Charging after it would be too late, since the time and memory would already be spent.

Raw, uncompressed bitmaps are charged too, after the check that their data is really there. Their pixels have to be in the file, but a bitmap with 1 bit per pixel still grows 32 times when it becomes four byte RGBA pixels.

For the person opening the file, images past the budget are left out with their own warning, "images past the most pixels one file may hold were left out". The rest of the picture still imports, and below the budget nothing changes.

Testing it without decoding gigabytes

The regression test needs several maximum size images, and truly decoding them would make it slow. So a helper, png_claiming, writes a 1 × 1 PNG and edits its header to claim any size. A PNG header carries a checksum (CRC), a number computed from its bytes to spot damage, so the helper recomputes that too. The size reads fine from the header, but the pixel data doesn't match it, so an actual decode fails fast.

embedded_bitmaps_share_one_pixel_budget builds an EMF by hand with five image records (StretchDIBits), each claiming 8192 × 8192. Four of them use up exactly 2²⁸. On main all five were attempted, and the only warning was the general "couldn't be read" one. With the fix, the fifth is refused from its header and the budget warning appears. A smaller test checks that a 3 × 2 raw bitmap is charged exactly 6 pixels, and that a refused one costs nothing.

Review

bflatastic merged it about seven minutes after I opened it, then left a short note that charging each bitmap from its header before it's inflated "is exactly right". Thanks, bflatastic!

CodeRabbit, a review bot, had left one fair comment shortly before the merge. A raster operation says how an image combines with what's already drawn, and the importer only draws plain copies (SRCCOPY). It skips the other kinds, but only after their bitmaps are decoded, so skipped images still use up budget and could push a later normal image out. It suggested checking the raster operation first. That isn't part of this PR.

What I'm keeping from this one

A limit on each item isn't a limit on the whole. Anything that loops over records from a file needs both.

And charge before the expensive work, so that saying no is free.

How do you handle budgets like this in your own parsers? Per file, per session, or something else?

About the author

  • I contribute to open source developer tools: Tauri, Biome, oxc, Julia, Quarkus, Grafana, Burn and a few more. I start from an issue I can reproduce and a test that fails, then fix it. Here I write up the ones worth telling: what broke, why, and how the fix got through review.

No comments yet. Be the first to comment.