fix(fla): document-wide budgets, linear Contents scans and our own test shape (M4)

A small hostile file could have one stream read and decoded for thousands of symbols, place one frame or text record many times through references, or make the Contents scans decode megabytes per candidate. Streams are now read against an allowance of twice the file's size; every byte a stream's decoders read, rolled back or not, is charged to a work budget of 64 times its length; keyframes (with their scripts and hints) and text characters count against the object allowance; bitmaps share the XFL importer's pixel budget; symbols and scenes are capped; the library scans step over strings by their head. The report now says when the stage wasn't found, a list was cut at its cap, or media is listed twice.

The unit tests' rectangle reproduced a shape of the third-party corpus (its geometry, fill, matrix and name); it is replaced by values of our own.
This commit is contained in:
Tanish Manku committed 2026-11-24 15:33:48 -07:00
1 parent 893d5ffa73
commit 66bd506bc8
9 files changed
+399 -95

No files matched your search

+34 -20
View File
@@ -70,8 +70,12 @@ pub const MAX_OBJECTS: usize = 1 << 20;
const MAX_DEPTH: usize = 64;
/// Longest string read, in UTF-16 units.
const MAX_STRING: usize = 1 << 20;
/// Bytes scanned while skipping undecoded objects, per stream.
const SCAN_BUDGET: usize = 256 << 20;
/// A stream's work budget: every byte read (again after a rolled-back trial, too) and every
/// byte scanned while skipping undecoded objects is charged, so decoding a stream costs at
/// most this many times its length (and a little, for the smallest streams). A stream Flash
/// wrote is read about once; the room is for the trial parses of what isn't decoded yet.
const WORK_PER_BYTE: usize = 64;
const WORK_FLOOR: usize = 1 << 16;
/// Trial parses while skipping, per stream.
const MAX_TRIALS: usize = 1 << 16;
/// Most envelope points, persistent-data entries, guides or ease anchors in one list.
@@ -256,23 +260,18 @@ impl Graph {
pub fn node(&self, i: usize) -> Option<&Node> {
self.nodes.get(i)
}
/// How many of the page's children didn't decode as anything (recovery skipped them): the
/// layers [`Graph::layers`] can't list.
/// How many of the page's children aren't layers (recovery skipped them, or they are
/// objects of another kind): what [`Graph::layers`] can't list.
pub fn skipped_layers(&self) -> usize {
let Some(Node::Page { layers }) = self.nodes.get(self.root) else { return 0 };
layers.iter().filter(|&&l| matches!(self.nodes.get(l), Some(Node::Skipped(_)))).count()
layers.iter().filter(|&&l| !matches!(self.nodes.get(l), Some(Node::Layer(_)))).count()
}
/// The layers, bottom first, each once.
pub fn layers(&self) -> Vec<usize> {
let Some(Node::Page { layers }) = self.nodes.get(self.root) else { return Vec::new() };
let mut out: Vec<usize> = Vec::with_capacity(layers.len());
for &l in layers {
if matches!(self.nodes.get(l), Some(Node::Layer(_))) && !out.contains(&l) {
out.push(l);
}
}
out
let mut seen = std::collections::HashSet::new();
layers.iter().copied().filter(|&l| matches!(self.nodes.get(l), Some(Node::Layer(_))) && seen.insert(l)).collect()
}
}
@@ -328,10 +327,15 @@ struct Base {
/// Decodes an item stream's object graph (its first byte, then the page object).
pub fn parse(data: &[u8]) -> Result<Graph, Bad> {
parse_within(data, data.len().saturating_mul(WORK_PER_BYTE).saturating_add(WORK_FLOOR))
}
/// [`parse`] with a work budget of `budget` bytes (tests try small ones).
pub(crate) fn parse_within(data: &[u8], budget: usize) -> Result<Graph, Bad> {
if data.first() != Some(&0x01) {
return Err(Bad);
}
let mut p = Parser { d: data, at: 1, map: vec![Entry::Null], classes: Vec::new(), nodes: Vec::new(), depth: 0, budget: SCAN_BUDGET, trials: 0, resyncs: 0 };
let mut p = Parser { d: data, at: 1, map: vec![Entry::Null], classes: Vec::new(), nodes: Vec::new(), depth: 0, budget, trials: 0, resyncs: 0 };
let root = p.obj(None)?.ok_or(Bad)?;
if !matches!(p.nodes.get(root), Some(Node::Page { .. })) {
return Err(Bad);
@@ -340,7 +344,13 @@ pub fn parse(data: &[u8]) -> Result<Graph, Bad> {
}
impl<'a> Parser<'a> {
/// Charges `n` bytes of reading, and the read itself, against the stream's work budget.
fn charge(&mut self, n: usize) -> R<()> {
self.budget = self.budget.checked_sub(n.saturating_add(1)).ok_or(Bad)?;
Ok(())
}
fn take(&mut self, n: usize) -> R<&'a [u8]> {
self.charge(n)?;
let end = self.at.checked_add(n).ok_or(Bad)?;
let s = self.d.get(self.at..end).ok_or(Bad)?;
self.at = end;
@@ -614,10 +624,9 @@ impl<'a> Parser<'a> {
self.number_declarations(&mut numbered_to, i);
let numbered = self.snap();
self.at = i;
// What a trial reads is charged as it reads, whether it parses or is rolled
// back (a hostile stream can't make the skipping quadratic).
let ok = matches!(self.obj(parent), Ok(Some(_)));
// What a trial reads counts against the budget too (a hostile stream can't
// make the skipping quadratic).
self.budget = self.budget.saturating_sub(self.at.saturating_sub(i));
self.restore(numbered);
if ok {
self.at = i;
@@ -746,7 +755,10 @@ impl<'a> Parser<'a> {
/// A shape body, or why it didn't decode.
fn shape_body_or_why(&mut self) -> Result<ShapeRecord, shape::ShapeError> {
let at05 = self.at.checked_add(24).ok_or(shape::ShapeError::Truncated)?;
let record = shape::decode(self.d, at05)?;
// A shape that doesn't decode is charged what it read, too.
let (record, read) = shape::decode_counted(self.d, at05);
self.charge(read).map_err(|_| shape::ShapeError::TooLarge)?;
let record = record?;
self.at = record.end;
let n = self.u32().map_err(|_| shape::ShapeError::Truncated)? as usize;
if n > shape::MAX_EDGES {
@@ -802,7 +814,6 @@ impl<'a> Parser<'a> {
let snap = self.snap();
self.at = i;
let ok = self.frame_tail().is_ok() && self.continues_at(self.at, Some(KIND_LAYER));
self.budget = self.budget.saturating_sub(self.at.saturating_sub(i));
self.restore(snap);
if ok {
self.at = i;
@@ -898,10 +909,13 @@ impl<'a> Parser<'a> {
/// A text record (its head here), decoded by [`crate::text`]; one in a layout not seen,
/// or that doesn't end where its parent continues, is skipped.
fn text(&mut self, parent: Option<u8>) -> R<Node> {
if let Ok(t) = crate::text::decode(self.d, self.at)
// A text that doesn't decode, or doesn't end where its parent continues, is charged
// what it read, too.
let (decoded, read) = crate::text::decode_counted(self.d, self.at);
self.charge(read)?;
if let Ok(t) = decoded
&& self.continues_at(t.end, parent)
{
self.budget = self.budget.saturating_sub(t.end.saturating_sub(self.at));
self.at = t.end;
return Ok(Node::Text(Box::new(t)));
}
+5
View File
@@ -155,6 +155,11 @@ impl<'a> Compound<'a> {
self.read_entry(entry)
}
/// The size of the stream at a full path, without reading it.
pub fn stream_size(&self, path: &str) -> Option<u64> {
self.streams.get(path).and_then(|&i| self.entries.get(i)).map(|e| e.size)
}
/// Reads the stream one of [`Compound::entries`] is: its own bytes, even when another
/// entry of a damaged file has the same path.
pub fn read_entry(&self, entry: &Entry) -> Result<Vec<u8>, Error> {
+116 -17
View File
@@ -58,6 +58,30 @@ const MAX_CONVERTED: usize = 1_000_000;
/// keyframes is rebuilt on each, and its edges are the work: they are charged before the
/// rebuild, so a compact stream can't make it repeat without end.
const MAX_EDGES_BUILT: usize = 32_000_000;
/// Most library symbols converted (the XFL importer's cap), and most scenes.
const MAX_SYMBOLS: usize = 20_000;
const MAX_SCENES: usize = 4_096;
/// Most pixels the document's bitmaps may decode to together (the XFL importer's budget).
const MAX_BITMAP_PIXELS: u64 = 256 * 1024 * 1024;
/// Why a stream wasn't read.
enum Unread {
Missing,
/// The document's reading allowance is spent.
OverBudget,
}
/// Reads a stream against the document's reading allowance, `left` bytes. The allowance is
/// twice the file's size: each stream of a file Flash wrote is its own bytes, so together
/// they are smaller than the file, while a hostile `Contents` may name one large stream as
/// thousands of symbols, scenes or media items to have it read and decoded again for each.
fn read_stream(file: &Compound, path: &str, left: &mut u64) -> Result<Vec<u8>, Unread> {
let size = file.stream_size(path).ok_or(Unread::Missing)?;
let Some(rest) = left.checked_sub(size) else { return Err(Unread::OverBudget) };
let bytes = file.stream(path).map_err(|_| Unread::Missing)?;
*left = rest;
Ok(bytes)
}
/// A scene as the document lists it: its page stream's name and the scene's label.
struct Page {
@@ -108,14 +132,28 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> {
/// `max_edges` shape edges, in place of [`MAX_CONVERTED`] and [`MAX_EDGES_BUILT`] (tests try
/// small allowances).
pub(crate) fn import_within(data: &[u8], max_converted: usize, max_edges: usize) -> Result<(Document, Report), ImportError> {
import_limited(data, max_converted, max_edges, MAX_BITMAP_PIXELS)
}
/// [`import_within`], its bitmaps decoding to at most `max_pixels` together in place of
/// [`MAX_BITMAP_PIXELS`].
pub(crate) fn import_limited(data: &[u8], max_converted: usize, max_edges: usize, max_pixels: u64) -> Result<(Document, Report), ImportError> {
let file = Compound::new(data)?;
let contents = file.stream("Contents")?;
if contents.first() != Some(&CONTENTS_VERSION) {
return Err(ImportError::UnsupportedVersion);
}
let mut report = Report::default();
let pages = pages(&contents)?;
let items = library_items(&contents);
let mut pages = pages(&contents)?;
if pages.len() > MAX_SCENES {
pages.truncate(MAX_SCENES);
report.skip("scenes past 4,096 (left out)");
}
let mut items = library_items(&contents);
if items.len() > MAX_SYMBOLS {
items.truncate(MAX_SYMBOLS);
report.skip("library symbols past 20,000 (left out)");
}
if !items.is_empty() {
report.keep("library names");
}
@@ -123,9 +161,15 @@ pub(crate) fn import_within(data: &[u8], max_converted: usize, max_edges: usize)
let mut doc = Document::default();
doc.scenes.clear();
doc.library.clear();
doc.stage = stage(&contents).unwrap_or_default();
doc.stage = stage(&contents).unwrap_or_else(|| {
report.skip("the stage's size, colour and frame rate (not found: the defaults are used)");
Stage::default()
});
// The library's folders first (empty ones come across too, as in the XFL importer).
let folder_list = library::folders(&contents);
if folder_list.len() >= library::MAX_ITEMS {
report.skip("library folders past the 16,384 an import reads (left out)");
}
let folders = library::folder_paths(&folder_list);
for f in &folder_list {
if let Some(path) = folders.get(&f.id) {
@@ -140,7 +184,8 @@ pub(crate) fn import_within(data: &[u8], max_converted: usize, max_edges: usize)
// As the XFL importer: ActionScript 3.0 unless the file says otherwise.
_ => Language::ActionScript3,
};
let (bitmaps, sounds) = media(&file, &contents, &folders, &mut doc, &mut report);
let mut streams_left = (data.len() as u64).saturating_mul(2);
let (bitmaps, sounds) = media(&file, &contents, &folders, &mut doc, &mut report, &mut streams_left, max_pixels);
// Symbols first, so instances can refer to any of them.
let mut symbols: HashMap<u32, SymbolId> = HashMap::new();
let mut ids = Vec::with_capacity(items.len());
@@ -154,13 +199,17 @@ pub(crate) fn import_within(data: &[u8], max_converted: usize, max_edges: usize)
let mut left = max_converted;
let mut edges_left = max_edges;
for (item, &id) in items.iter().zip(&ids) {
let timeline = match file.stream(&item.stream) {
let timeline = match read_stream(&file, &item.stream, &mut streams_left) {
Ok(bytes) => {
let mut ctx = Ctx { doc: &mut doc, report: &mut report, symbols: &symbols, bitmaps: &bitmaps, sounds: &sounds, fonts, faces: &mut faces, language, left: &mut left, edges_left: &mut edges_left };
library_timeline(&bytes, &item.label, &mut ctx)
}
Err(_) => {
report.skip_named("library symbols whose stream is missing", item.label.clone());
Err(why) => {
let what = match why {
Unread::Missing => "library symbols whose stream is missing",
Unread::OverBudget => "library symbols past the import's reading budget (left empty)",
};
report.skip_named(what, item.label.clone());
Timeline { layers: vec![Arc::new(Layer::new(LayerId(doc.alloc_id()), "Layer 1"))] }
}
};
@@ -175,7 +224,7 @@ pub(crate) fn import_within(data: &[u8], max_converted: usize, max_edges: usize)
}
for page in &pages {
let mut timeline = Timeline::default();
match file.stream(&page.stream) {
match read_stream(&file, &page.stream, &mut streams_left) {
Ok(bytes) => match archive::parse(&bytes) {
Ok(graph) => {
let mut ctx = Ctx { doc: &mut doc, report: &mut report, symbols: &symbols, bitmaps: &bitmaps, sounds: &sounds, fonts, faces: &mut faces, language, left: &mut left, edges_left: &mut edges_left };
@@ -189,7 +238,8 @@ pub(crate) fn import_within(data: &[u8], max_converted: usize, max_edges: usize)
}
}
},
Err(_) => report.skip_named("scenes whose page stream is missing", page.label.clone()),
Err(Unread::Missing) => report.skip_named("scenes whose page stream is missing", page.label.clone()),
Err(Unread::OverBudget) => report.skip_named("scenes past the import's reading budget (left empty)", page.label.clone()),
}
if timeline.layers.is_empty() {
timeline.layers.push(Arc::new(Layer::new(LayerId(doc.alloc_id()), "Layer 1")));
@@ -219,25 +269,47 @@ fn place_in_folder(doc: &mut Document, folders: &HashMap<ItemId, String>, parent
/// a bitmap in Animate's own lossless layout, or a PNG or JPEG; a sound as raw 16-bit PCM of
/// its item's format and sample count (it comes across as a WAV), or a WAV, Ogg Vorbis or MP3
/// file. What doesn't decode is reported by name, with why.
fn media(file: &Compound, contents: &[u8], folders: &HashMap<ItemId, String>, doc: &mut Document, report: &mut Report) -> (HashMap<u16, BitmapId>, HashMap<u16, SoundId>) {
fn media(file: &Compound, contents: &[u8], folders: &HashMap<ItemId, String>, doc: &mut Document, report: &mut Report, streams_left: &mut u64, max_pixels: u64) -> (HashMap<u16, BitmapId>, HashMap<u16, SoundId>) {
let streams: HashSet<String> = file.entries().iter().filter(|e| e.kind == crate::cfb::Kind::Stream).map(|e| e.path.clone()).collect();
let (mut bitmaps, mut sounds) = (HashMap::new(), HashMap::new());
let (items, missing) = library::media_items(contents, |s| streams.contains(s));
if items.len() + missing.len() >= library::MAX_ITEMS {
report.skip("media past the 16,384 items an import reads (left out)");
}
for name in missing {
report.skip_named("media whose stream is missing", name);
}
let mut pixels_left = max_pixels;
for item in items {
if bitmaps.contains_key(&item.id) || sounds.contains_key(&item.id) {
report.skip_named("media listed twice under one id (the first kept)", item.name.clone());
continue;
}
let shown = item.name.clone();
let Ok(bytes) = file.stream(&item.stream) else {
report.skip_named("media whose stream couldn't be read", shown);
continue;
let bytes = match read_stream(file, &item.stream, streams_left) {
Ok(bytes) => bytes,
Err(Unread::Missing) => {
report.skip_named("media whose stream couldn't be read", shown);
continue;
}
Err(Unread::OverBudget) => {
report.skip_named("media past the import's reading budget (left out)", shown);
continue;
}
};
let kind = item.kind.unwrap_or(if anicraft_flamedia::is_bitmap(&bytes) { MediaKind::Bitmap } else { MediaKind::Sound });
match kind {
MediaKind::Bitmap => {
// Refused by its header, before its pixels are decoded, once the document's
// bitmaps are past their pixel budget (a file image is charged once decoded).
let over = match anicraft_flamedia::bitmap_header(&bytes) {
Ok(h) if anicraft_flamedia::is_bitmap(&bytes) => u64::from(h.width) * u64::from(h.height) > pixels_left,
_ => pixels_left == 0,
};
if over {
report.skip_named("bitmaps past the import's pixel budget (left out)", shown);
continue;
}
let decoded = if anicraft_flamedia::is_bitmap(&bytes) {
anicraft_flamedia::decode_bitmap(&bytes).map_err(|e| e.to_string()).and_then(|px| {
Bitmap::from_rgba(BitmapId(0), item.name.clone(), px.width, px.height, px.rgba).ok_or_else(|| anicraft_flamedia::DatError::BadSize.to_string())
@@ -247,6 +319,7 @@ fn media(file: &Compound, contents: &[u8], folders: &HashMap<ItemId, String>, do
};
match decoded {
Ok(mut b) => {
pixels_left = pixels_left.saturating_sub(u64::from(b.width) * u64::from(b.height));
b.id = BitmapId(doc.alloc_id());
b.smoothing = true;
bitmaps.insert(item.id, b.id);
@@ -303,7 +376,7 @@ fn library_timeline(bytes: &[u8], label: &str, ctx: &mut Ctx) -> Timeline {
}
}
let (doc, report) = (&mut *ctx.doc, &mut *ctx.report);
let shapes = shapes(bytes, report);
let shapes = shapes(bytes, report, ctx.edges_left);
let layer = Layer::new(LayerId(doc.alloc_id()), "artwork");
if shapes.is_empty() {
report.skip_named("library symbols whose timeline didn't decode", label.to_string());
@@ -371,6 +444,11 @@ fn build_timeline(graph: &Graph, ctx: &mut Ctx) -> Timeline {
if duration == 0 {
continue;
}
// Charged with its script and hints: references may place one frame record on a
// layer many times over, and each placement is a keyframe with its own copies.
if !spend_n(ctx, 1 + frame.script.len() / 64 + frame.hints.len()) {
break;
}
if !frame.hints.is_empty() {
hints.insert(at, frame.hints.clone());
}
@@ -486,6 +564,9 @@ fn frame_sound(frame: &archive::FrameRec, ctx: &mut Ctx) -> Option<FrameSound> {
.collect();
// The format has no effect byte: an envelope plays as its points (as the XFL importer
// reads an envelope without a preset name).
if frame.envelope.len() > anicraft_doc::sound::MAX_ENVELOPE_POINTS {
ctx.report.skip("sound envelope points past the most a sound holds (left out)");
}
if !points.is_empty() {
fs.effect = SoundEffect::Custom(anicraft_doc::sound::clean_points(&points));
}
@@ -578,6 +659,11 @@ fn element(graph: &Graph, n: usize, ctx: &mut Ctx, out: &mut Vec<Arc<Element>>,
}
}
Some(Node::Text(t)) => {
// Charged by its characters as well: laying a text out costs by its length, and
// references may place one long record many times over.
if !spend_n(ctx, t.runs.iter().map(|r| r.text.len()).sum()) {
return;
}
let id = ElementId(ctx.doc.alloc_id());
if let Some(e) = t.to_element(id, ctx.fonts, ctx.faces, ctx.report) {
out.push(Arc::new(e));
@@ -656,7 +742,13 @@ fn shape_skip(why: shape::ShapeError) -> &'static str {
/// Spends one of the document's [`MAX_CONVERTED`] objects; false, and reported, once they are
/// spent.
fn spend(ctx: &mut Ctx) -> bool {
let Some(left) = ctx.left.checked_sub(1) else {
spend_n(ctx, 1)
}
/// Spends `n` of the document's [`MAX_CONVERTED`] objects at once (a keyframe with its script,
/// a text with its characters); false, and reported, when fewer are left.
fn spend_n(ctx: &mut Ctx, n: usize) -> bool {
let Some(left) = ctx.left.checked_sub(n) else {
ctx.report.skip("objects past a million in one document (left out)");
return false;
};
@@ -808,7 +900,7 @@ pub fn stage(contents: &[u8]) -> Option<Stage> {
/// record (the object that names the class) as shape elements, one per fill style, then one
/// per stroke style, carried by the record's matrix. A record that doesn't decode is left
/// out whole and counted.
fn shapes(bytes: &[u8], report: &mut Report) -> Vec<Element> {
fn shapes(bytes: &[u8], report: &mut Report, edges_left: &mut usize) -> Vec<Element> {
let Some(name) = find(bytes, b"CPicShape") else { return Vec::new() };
let after = name + b"CPicShape".len();
let decoded = match shape::body_after_tag(bytes, after) {
@@ -842,6 +934,13 @@ fn shapes(bytes: &[u8], report: &mut Report) -> Vec<Element> {
for what in &record.approximations {
report.skip(what);
}
// Charged against the document's geometry budget, as the shapes on keyframes are: many
// library items may name this one stream.
let Some(left) = edges_left.checked_sub(record.edges.len()) else {
report.skip("shapes past the import's geometry budget (left out)");
return Vec::new();
};
*edges_left = left;
let transform = record.matrix;
record.shapes().into_iter().enumerate().map(|(i, s)| Element {
id: ElementId(i as u64 + 1),
@@ -903,7 +1002,7 @@ fn pages(contents: &[u8]) -> Result<Vec<Page>, ImportError> {
}
/// The library: stream-name strings (`01 80 17` prefix) each followed by a label string
/// (`ff fe ff`), e.g. `Symbol 125` → `UFO rays`, as (stream, label) pairs.
/// (`ff fe ff`), e.g. `Symbol 9` → `Sky mask`, as (stream, label) pairs.
pub fn library(contents: &[u8], report: &mut Report) -> Vec<(String, String)> {
let items = library_items(contents);
if !items.is_empty() {
+4
View File
@@ -76,10 +76,14 @@ pub fn dump_only(data: &[u8], only: Option<&str>) -> Result<Vec<StreamDump>, cfb
// One tag budget for the whole file: several directory entries may share one chain, so a
// budget per stream would let a small file hold millions of tags.
let mut tags_left = records::MAX_TAGS;
// And one reading allowance, of twice the file's size, for the same reason: each stream
// of a file Flash wrote is its own bytes, so together they are smaller than the file.
let mut bytes_left = (data.len() as u64).saturating_mul(2);
for entry in file.entries() {
if entry.kind != cfb::Kind::Stream || only.is_some_and(|p| p != entry.path) {
continue;
}
bytes_left = bytes_left.checked_sub(entry.size).ok_or_else(|| cfb::Error::OverLimit("its streams add up to more than twice the file's size".to_string()))?;
let bytes = file.read_entry(entry)?;
let scan = records::scan_tags_max(&bytes, tags_left);
tags_left = tags_left.saturating_sub(scan.tags.len());
+28 -8
View File
@@ -29,7 +29,10 @@ pub type ItemId = (u32, u32);
/// The root's id.
pub const ROOT: ItemId = (0, 0);
/// Most folders and media items read.
const MAX_ITEMS: usize = 1 << 14;
pub const MAX_ITEMS: usize = 1 << 14;
/// The longest name a library record's string may be, in bytes as stored: a longer string is
/// no name, and is refused from its head alone, before anything is decoded.
const MAX_NAME_BYTES: usize = 8192;
/// Longest stream name (UTF-16 units).
const MAX_STREAM_NAME: usize = 64;
@@ -89,11 +92,22 @@ impl<'a> Reader<'a> {
fn expect(&mut self, v: u32) -> Option<()> {
(self.u32()? == v).then_some(())
}
/// A name: a string of at most [`MAX_NAME_BYTES`], refused before it is decoded when longer.
fn string(&mut self) -> Option<String> {
let end = crate::text::cstring_end(self.d, self.at).ok()?;
if end.saturating_sub(self.at) > MAX_NAME_BYTES {
return None;
}
let (s, end) = crate::text::cstring(self.d, self.at).ok()?;
self.at = end;
Some(s)
}
/// Steps over a string by its head alone: a candidate that turns out not to be a record
/// costs the scan nothing for the strings it claimed to hold.
fn skip_string(&mut self) -> Option<()> {
self.at = crate::text::cstring_end(self.d, self.at).ok()?;
Some(())
}
/// The identity block: u32 6, u32 1, parent id, u32 1, own id.
fn identity(&mut self) -> Option<(ItemId, ItemId)> {
self.expect(6)?;
@@ -124,10 +138,13 @@ pub fn folders(contents: &[u8]) -> Vec<Folder> {
if contents.get(i..i + 7) == Some(&[0x04, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0xFF][..]) {
let mut r = Reader { d: contents, at: i + 4 };
let folder = (|| {
let name = r.string()?;
// The name is decoded only once the record behind it checks out.
let name_at = r.at;
r.skip_string()?;
let (parent, id) = r.identity()?;
r.expect(0)?;
r.expect(7)?;
let name = Reader { d: contents, at: name_at }.string()?;
let name = name.trim().to_string();
(!name.is_empty() && id != ROOT && !name.contains('/')).then_some(Folder { name, parent, id })
})();
@@ -176,7 +193,7 @@ pub fn folder_paths(folders: &[Folder]) -> HashMap<ItemId, String> {
/// byte at `after` (the type byte's offset + 1), with a string, `u32 1` and the identity block.
pub fn symbol_parent(contents: &[u8], after: usize) -> Option<ItemId> {
let mut r = Reader { d: contents, at: after };
r.string()?;
r.skip_string()?;
r.expect(1)?;
r.identity().map(|(parent, _)| parent)
}
@@ -229,11 +246,14 @@ pub fn media_items(contents: &[u8], has_stream: impl Fn(&str) -> bool) -> (Vec<M
fn media_at(contents: &[u8], at: usize, declared: Option<MediaKind>) -> Option<(MediaItem, usize)> {
let mut r = Reader { d: contents, at };
let stream = r.stream_name()?;
let name = r.string()?;
// The name is decoded only once the record behind it checks out.
let name_at = r.at;
r.skip_string()?;
let id = r.u16()?;
r.string()?; // the source file's path
r.skip_string()?; // the source file's path
r.u32()?; // its import time
let (parent, _) = r.identity()?;
let name = Reader { d: contents, at: name_at }.string()?;
let mut item = MediaItem { kind: declared, stream, name: name.chars().take(256).collect(), id, parent, sound: None };
let identity_end = r.at;
// The common settings, then the class's own.
@@ -242,19 +262,19 @@ fn media_at(contents: &[u8], at: usize, declared: Option<MediaKind>) -> Option<(
r.expect(7)?;
r.u8()?;
for _ in 0..3 {
r.string()?;
r.skip_string()?;
}
r.u8()?;
r.expect(2)?;
for _ in 0..2 {
r.string()?;
r.skip_string()?;
}
r.take(8)?;
r.expect(1)?;
r.expect(0)?;
r.expect(u32::MAX)?;
r.u8()?;
r.string()?;
r.skip_string()?;
r.u8()?;
r.expect(1)?;
match r.u8()? {
+15 -3
View File
@@ -255,7 +255,19 @@ fn stroke(r: &mut Reader, approximations: &mut Vec<&'static str>) -> Result<Stro
/// Decodes the shape body whose matrix ends at `at` (the offset of its `05` byte).
pub fn decode(data: &[u8], at: usize) -> Result<ShapeRecord, ShapeError> {
let mut r = Reader { data, at: at.checked_sub(MATRIX).ok_or(ShapeError::NotShape)? };
decode_counted(data, at).0
}
/// [`decode`], and how many bytes it read, whether it decoded or not: what the object walker
/// charges a trial against its stream's work budget.
pub(crate) fn decode_counted(data: &[u8], at: usize) -> (Result<ShapeRecord, ShapeError>, usize) {
let Some(start) = at.checked_sub(MATRIX) else { return (Err(ShapeError::NotShape), 0) };
let mut r = Reader { data, at: start };
let record = decode_in(&mut r);
(record, r.at.saturating_sub(start))
}
fn decode_in(r: &mut Reader) -> Result<ShapeRecord, ShapeError> {
let matrix = r.matrix()?;
if r.u8()? != 0x05 {
return Err(ShapeError::NotShape);
@@ -271,7 +283,7 @@ pub fn decode(data: &[u8], at: usize) -> Result<ShapeRecord, ShapeError> {
}
let mut fills = Vec::with_capacity(fill_count.min(64));
for _ in 0..fill_count {
fills.push(fill(&mut r, &mut approximations)?);
fills.push(fill(r, &mut approximations)?);
}
let stroke_count = r.u16()? as usize;
if stroke_count > MAX_STYLES {
@@ -279,7 +291,7 @@ pub fn decode(data: &[u8], at: usize) -> Result<ShapeRecord, ShapeError> {
}
let mut strokes = Vec::with_capacity(stroke_count.min(64));
for _ in 0..stroke_count {
strokes.push(stroke(&mut r, &mut approximations)?);
strokes.push(stroke(r, &mut approximations)?);
}
let mut edges = Vec::with_capacity(count.min(4096));
let (mut pen, mut styles) = ((0i64, 0i64), (0u16, 0u16, 0u16));
+49 -23
View File
@@ -301,6 +301,7 @@ fn stream_names_with_spaces_and_digits_round_trip() {
pub(crate) fn synthetic_contents() -> Vec<u8> {
let utf16 = |s: &str| -> Vec<u8> { s.encode_utf16().flat_map(|c| c.to_le_bytes()).collect() };
let mut c = vec![0x3F, 0x01, 0x00, 0x00, 0x00];
c.extend(properties([0, 11_000, 0, 8_000], 24 << 16)); // a 550 x 400 stage at 24 fps
c.extend_from_slice(&[0xFF, 0xFF, 0x01, 0x00]); // the record stream's marker
c.extend_from_slice(&13u16.to_le_bytes()); // the record's name length
c.extend_from_slice(b"CDocumentPage");
@@ -313,13 +314,28 @@ pub(crate) fn synthetic_contents() -> Vec<u8> {
c.extend_from_slice(&[0x01, 0x80, 0x17, 0x08]);
c.extend_from_slice(&utf16("Symbol 9"));
c.extend_from_slice(&[0xFF, 0xFE, 0xFF, 0x08]);
c.extend_from_slice(&utf16("UFO mask"));
c.extend_from_slice(&utf16("Sky mask"));
c.extend_from_slice(&9u32.to_le_bytes()); // its item id
c.push(0x00); // a graphic
c.extend_from_slice(&[0u8; 8]);
c
}
/// The document properties around `legacyLineSpacing`: the stage rectangle (left, right,
/// top, bottom in twips) 74 bytes before the property's name, the background 21 and the
/// frame rate (16.16) 13 bytes before it.
pub(crate) fn properties(rect: [i32; 4], fps: i32) -> Vec<u8> {
let mut c = vec![0u8; 74];
for (k, v) in rect.iter().enumerate() {
c[4 * k..4 * k + 4].copy_from_slice(&v.to_le_bytes());
}
c[53..57].copy_from_slice(&[0x33, 0x66, 0x99, 0xFF]);
c[61..65].copy_from_slice(&fps.to_le_bytes());
c.extend([0xFF, 0xFE, 0xFF, 17]);
c.extend("legacyLineSpacing".encode_utf16().flat_map(u16::to_le_bytes));
c
}
/// A minimal page stream: two layers (stored bottom-first), each with one empty keyframe.
fn synthetic_page() -> Vec<u8> {
let mut w = Ar::new();
@@ -446,20 +462,19 @@ fn shape_head(matrix: [i32; 6], edge_count: u32) -> Vec<u8> {
/// The layer-record tail that follows a shape in a library stream.
const TAIL: [u8; 9] = [0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x03];
/// A `CPicShape` record holding the corpus's smallest shape's geometry (Symbol 123, "UFO
/// mask"): a 10.9 × 11.2 px rectangle, white fill at 31 % opacity, its matrix scaled by
/// 65535/65536 and translated to (26.9, −1.55). The bytes are written from the decoded
/// grammar (ADR 0120), not copied from any file.
/// A `CPicShape` record of our own making: a 12 × 8 px rectangle, a blue fill at half
/// opacity, its matrix scaled by a half and translated to (15, −7). The bytes are written from
/// the decoded grammar (ADR 0120); neither they nor the values come from any file.
fn synthetic_shape_record() -> Vec<u8> {
let mut d = shape_head([0xFFFF, 0, 0, 0xFFFF, 538, -31], 4);
let mut d = shape_head([0x8000, 0, 0, 0x8000, 300, -140], 4);
d.extend_from_slice(&1u16.to_le_bytes()); // one fill:
d.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0x50, 0x00, 0x00]); // white at 80/255, solid
d.extend_from_slice(&[0x20, 0x80, 0xC0, 0x80, 0x00, 0x00]); // blue at 128/255, solid
d.extend_from_slice(&0u16.to_le_bytes()); // no strokes
// The right-hand fill 1, a move to (−429, −81) twips, then four straight edges.
edge(&mut d, Some(Styles::Narrow(0, 0, 1)), Some(Pt::Half(-858, -162)), None, Some(Pt::Half(0, 448)));
edge(&mut d, None, None, None, Some(Pt::Half(-436, 0)));
edge(&mut d, None, None, None, Some(Pt::Half(0, -448)));
edge(&mut d, None, None, None, Some(Pt::Half(436, 0)));
// The right-hand fill 1, a move to (200, 100) twips, then four straight edges.
edge(&mut d, Some(Styles::Narrow(0, 0, 1)), Some(Pt::Half(400, 200)), None, Some(Pt::Half(0, 320)));
edge(&mut d, None, None, None, Some(Pt::Half(-480, 0)));
edge(&mut d, None, None, None, Some(Pt::Half(0, -320)));
edge(&mut d, None, None, None, Some(Pt::Half(480, 0)));
d.push(0x00); // the edge list's end
d.extend_from_slice(&TAIL);
d
@@ -493,7 +508,7 @@ fn library_shapes(record: Vec<u8>) -> (Vec<std::sync::Arc<anicraft_doc::Element>
use super::doc;
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", synthetic_page()), ("Symbol 9", one_frame_stream(&record_body(&record)))];
let (document, report) = doc::import(&write(&payloads)).expect("opens");
let elements = document.library.iter().find(|s| s.name == "UFO mask")
let elements = document.library.iter().find(|s| s.name == "Sky mask")
.map(|symbol| symbol.timeline.layers[0].keyframes[0].elements.clone())
.unwrap_or_default();
(elements, report)
@@ -534,20 +549,20 @@ fn a_straight_edged_shape_decodes_with_its_geometry_and_fill() {
let (elements, report) = library_shapes(synthetic_shape_record());
assert_eq!(elements.len(), 1, "the rectangle decodes as one shape");
let shape = shape_of(&elements[0]);
// The fill: white at 80/255.
// The fill: at 128/255.
let Some(anicraft_doc::Paint::Solid(fill)) = shape.fill else { panic!("a solid fill") };
assert!((fill.a - 80.0 / 255.0).abs() < 0.001, "fill alpha {fill:?}");
// The matrix: 65535/65536 scale, translation (26.9, −1.55) px.
assert!((fill.a - 128.0 / 255.0).abs() < 0.001, "fill alpha {fill:?}");
// The matrix: a half scale, translation (15, −7) px.
let m = elements[0].transform.m;
assert!(close(m[0], 65535.0 / 65536.0) && close(m[3], 65535.0 / 65536.0) && m[1] == 0.0 && m[2] == 0.0, "{m:?}");
assert!(close(m[4], 26.9) && close(m[5], -1.55), "{m:?}");
// The path: the rectangle's corners, (−429, −81) … (−647, 143) twips, as one closed loop.
assert!(close(m[0], 0.5) && close(m[3], 0.5) && m[1] == 0.0 && m[2] == 0.0, "{m:?}");
assert!(close(m[4], 15.0) && close(m[5], -7.0), "{m:?}");
// The path: the rectangle's corners, (200, 100) … (−40, 260) twips, as one closed loop.
let points: Vec<_> = shape.path.cmds.iter().filter_map(|c| match *c {
anicraft_geom::PathCmd::MoveTo(p) | anicraft_geom::PathCmd::LineTo(p) => Some((p.x, p.y)),
anicraft_geom::PathCmd::Close => None,
_ => panic!("straight edges only"),
}).collect();
let want = [(-21.45, -4.05), (-21.45, 7.15), (-32.35, 7.15), (-32.35, -4.05), (-21.45, -4.05)];
let want = [(10.0, 5.0), (10.0, 13.0), (-2.0, 13.0), (-2.0, 5.0), (10.0, 5.0)];
assert_eq!(points.len(), want.len(), "{points:?}");
for (got, want) in points.iter().zip(want) {
assert!(close(got.0, want.0) && close(got.1, want.1), "{points:?}");
@@ -1112,7 +1127,7 @@ fn a_synthetic_timeline_decodes_its_layers_keyframes_tweens_and_instances() {
// The instance: its symbol, matrix, loop, first frame, colour, blend and moved point.
let e = &first.elements[0];
let ElementKind::Symbol { symbol, loop_mode, first_frame, blend, pivot, .. } = &e.kind else { panic!("an instance: {:?}", e.kind) };
assert_eq!(doc.symbol(*symbol).map(|s| s.name.as_str()), Some("UFO mask"));
assert_eq!(doc.symbol(*symbol).map(|s| s.name.as_str()), Some("Sky mask"));
let want = [1.25, 0.5, -0.5, -0.5, 100.5, -20.25];
for (got, want) in e.transform.m.iter().zip(want) {
assert!((got - want).abs() < 1e-4, "{:?}", e.transform.m);
@@ -1129,7 +1144,7 @@ fn a_synthetic_timeline_decodes_its_layers_keyframes_tweens_and_instances() {
assert_eq!(raw.len(), 1);
assert!(matches!(&raw[0].kind, ElementKind::Shape(s) if s.merge));
// The library symbol has its own timeline now, not just its first shape.
let sym = doc.library.iter().find(|s| s.name == "UFO mask").expect("the symbol");
let sym = doc.library.iter().find(|s| s.name == "Sky mask").expect("the symbol");
let spans: Vec<(u32, u32)> = sym.timeline.layers[0].keyframes.iter().map(|k| (k.start, k.duration)).collect();
assert_eq!(spans, [(0, 2), (2, 3)]);
// The report: what was left out, by kind.
@@ -1455,7 +1470,7 @@ fn texts_bitmaps_buttons_sounds_scripts_and_hints_come_in_on_their_keyframes() {
assert_eq!((s.name.as_str(), s.rate, s.channels, s.frames), ("beep", 44_100, 1, 4));
assert_eq!(doc.entry_path(LibraryEntry::Item(LibraryItem::Sound(s.id))), "Art/Sounds/beep");
let sym = &doc.library[0];
assert_eq!(doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(sym.id))), "Art/UFO mask");
assert_eq!(doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(sym.id))), "Art/Sky mask");
// The objects: the dynamic text, the bitmap's rectangle, the named button.
let k = &tl.layers[0].keyframes[0];
assert_eq!(k.elements.len(), 3, "{:?}", k.elements.iter().map(|e| &e.kind).collect::<Vec<_>>());
@@ -1588,3 +1603,14 @@ fn a_scene_label_at_the_very_end_of_contents_is_found() {
let (doc, _) = super::doc::import(&write(&[("Contents", c), ("P 1 1", synthetic_page())])).expect("the scene is found");
assert_eq!(doc.scenes.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["A"]);
}
#[test]
fn bitmaps_past_the_pixel_budget_are_left_out_by_their_header_and_named() {
let bitmap = bitmap_payload(2, 1, &[255, 255, 0, 0, 128, 128, 128, 128]);
let bytes = write(&[("Contents", media_contents()), ("P 1 1", media_page()), ("Symbol 9", one_frame_stream(&rectangle_body())), ("Media 1", bitmap)]);
let (doc, _) = super::doc::import_limited(&bytes, usize::MAX, usize::MAX, 2).expect("opens");
assert_eq!(doc.bitmaps.len(), 1, "two pixels fit a budget of two");
let (doc, report) = super::doc::import_limited(&bytes, usize::MAX, usize::MAX, 1).expect("opens");
assert!(doc.bitmaps.is_empty());
assert_eq!(report.names.get("bitmaps past the import's pixel budget (left out)").map(Vec::len), Some(1), "{:?}", report.names);
}
+120 -21
View File
@@ -4,7 +4,7 @@
//! `Contents` scans. Every byte here is written from the grammar in `crate::archive` and
//! `crate::doc`, never taken from a corpus file.
use crate::tests::{one_frame_stream, rectangle_body, scene, synthetic_contents, write, Ar, FrameSpec, InstSpec};
use crate::tests::{one_frame_stream, properties, rectangle_body, scene, synthetic_contents, write, Ar, FrameSpec, InstSpec};
use crate::text_tests::{record, units, Head, Style};
use anicraft_doc::{Element, ElementKind};
use std::sync::Arc;
@@ -287,19 +287,20 @@ fn three_fills(w: &mut Ar) {
#[test]
fn every_shape_a_record_emits_is_charged_against_the_object_allowance() {
// Four uses of a three-fill drawing, in groups two levels deep: 11 objects visited and 12
// shapes emitted, 24 with the library's rectangle.
// shapes emitted, 24 with the library's rectangle, and the two keyframes they sit on.
let file = || {
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", page_with(|w| {
shared(w, 2, three_fills);
})), ("Symbol 9", one_frame_stream(&rectangle_body()))];
write(&payloads)
};
let (doc, report) = crate::doc::import_within(&file(), 24, usize::MAX).expect("opens");
let (doc, report) = crate::doc::import_within(&file(), 26, usize::MAX).expect("opens");
assert_eq!(shapes_in(&scene(&doc).layers[0].keyframes[0].elements), 12);
assert!(report.skipped.is_empty(), "{:?}", report.skipped);
// With room for 13, the visits alone (12 with the library's) would have fit and all 12
// shapes come in; the shapes count too, so they stop at the allowance and say so.
let (doc, report) = crate::doc::import_within(&file(), 13, usize::MAX).expect("opens");
// With room for 15, the visits alone (12 with the library's, and the two keyframes) would
// have fit and all 12 shapes come in; the shapes count too, so they stop at the allowance
// and say so.
let (doc, report) = crate::doc::import_within(&file(), 15, usize::MAX).expect("opens");
let shapes = shapes_in(&scene(&doc).layers[0].keyframes[0].elements);
assert_eq!(shapes, 6);
assert!(skipped(&report, "objects past a million in one document (left out)") > 0, "{:?}", report.skipped);
@@ -382,21 +383,6 @@ fn a_scene_label_outside_ascii_advances_by_its_stored_units() {
assert_eq!(scene_names(contents_with_scenes(&["Scene 1", "Scene 2"])), ["Scene 1", "Scene 2"]);
}
/// The document properties around `legacyLineSpacing`: the stage rectangle (left, right,
/// top, bottom in twips) 74 bytes before the property's name, the background 21 and the
/// frame rate (16.16) 13 bytes before it.
fn properties(rect: [i32; 4], fps: i32) -> Vec<u8> {
let mut c = vec![0u8; 74];
for (k, v) in rect.iter().enumerate() {
c[4 * k..4 * k + 4].copy_from_slice(&v.to_le_bytes());
}
c[53..57].copy_from_slice(&[0x33, 0x66, 0x99, 0xFF]);
c[61..65].copy_from_slice(&fps.to_le_bytes());
c.extend([0xFF, 0xFE, 0xFF, 17]);
c.extend(utf16("legacyLineSpacing"));
c
}
#[test]
fn a_stage_rectangle_of_extreme_edges_is_no_stage_and_never_overflows() {
let s = crate::doc::stage(&properties([0, 11_000, 0, 8_000], 24 << 16)).expect("a stage");
@@ -448,3 +434,116 @@ fn keyframes_past_the_last_frame_are_left_out_not_stacked_on_it() {
assert!(starts.len() < 4, "{starts:?}");
assert!(skipped(&report, "keyframes past frame 100,000 (left out)") > 0, "{:?}", report.skipped);
}
// The document-wide allowances: what a small hostile file can't multiply.
/// The synthetic `Contents` listing the "Symbol 9" stream as `n` more library symbols.
fn contents_naming_one_stream(n: u32) -> Vec<u8> {
let mut c = synthetic_contents();
for k in 0..n {
c.extend([0x01, 0x80, 0x17, 0x08]);
c.extend(utf16("Symbol 9"));
c.extend([0xFF, 0xFE, 0xFF, 0x04]);
c.extend(utf16("copy"));
c.extend((100 + k).to_le_bytes());
c.push(0x00);
c.extend([0u8; 8]);
}
c
}
#[test]
fn one_stream_named_by_many_symbols_is_read_within_the_files_allowance() {
// A symbol stream of a few kilobytes that `Contents` lists thousands of times: reading and
// decoding it for each would cost far more than the file holds.
let stream = {
let mut w = Ar::new();
w.page(|w| {
for _ in 0..40 {
w.layer("artwork", 0, None, |w| w.frame(&rectangle_body(), &frame_spec(1), |_| {}));
}
});
w.out
};
let file = write(&[("Contents", contents_naming_one_stream(4000)), ("P 1 1", page_with(|_| {})), ("Symbol 9", stream.clone())]);
assert!(4000 * stream.len() > 2 * file.len(), "the fixture asks for more than its allowance");
let (doc, report) = crate::doc::import(&file).expect("opens");
let left_empty = skipped(&report, "library symbols past the import's reading budget (left empty)");
assert!(left_empty > 0, "{:?}", report.skipped);
let decoded = doc.library.iter().filter(|s| s.timeline.layers.len() == 40).count();
assert!(decoded > 0 && decoded * stream.len() <= 2 * file.len(), "{decoded} symbols decoded");
assert_eq!(decoded + left_empty, doc.library.len(), "every symbol is there, decoded or named as left empty");
}
#[test]
fn keyframes_and_text_characters_are_charged_against_the_object_allowance() {
// Five empty keyframes: each is an object of the allowance, so three fit.
let frames = {
let mut w = Ar::new();
w.page(|w| {
w.layer("art", 0, None, |w| {
for _ in 0..5 {
w.frame(&[], &frame_spec(1), |_| {});
}
});
});
w.out
};
// The library symbol's own keyframe takes one of the allowance first.
let (doc, report) = crate::doc::import_within(&write(&[("Contents", synthetic_contents()), ("P 1 1", frames), ("Symbol 9", one_frame_stream(&[]))]), 4, usize::MAX).expect("opens");
assert_eq!(scene(&doc).layers[0].keyframes.len(), 3);
assert!(skipped(&report, "objects past a million in one document (left out)") > 0, "{:?}", report.skipped);
// A text is charged its characters too: one of forty doesn't fit an allowance of twenty.
let text = |chars: &str| {
let chars = chars.to_string();
page_with(move |w| {
w.tag("CPicText");
let head = Head { matrix: [65536, 0, 0, 65536, 0, 0], bounds: [0, 2000, 0, 400], ..Head::default() };
w.out.extend(record(&head, &[(units(&chars), Style::default())]));
})
};
let texts = |page: Vec<u8>| {
let (doc, report) = crate::doc::import_within(&write(&[("Contents", synthetic_contents()), ("P 1 1", page), ("Symbol 9", one_frame_stream(&[]))]), 20, usize::MAX).expect("opens");
(scene(&doc).layers[0].keyframes[0].elements.len(), skipped(&report, "objects past a million in one document (left out)"))
};
assert_eq!(texts(text("short")), (1, 0));
let (kept, left_out) = texts(text(&"long ".repeat(8)));
assert!(kept == 0 && left_out > 0);
}
#[test]
fn a_stream_is_charged_every_byte_it_reads_whichever_decoder_reads_it() {
// An item stream, one that is mostly a shape record, and one that is mostly a text: each
// decodes within a few times its length, and none within half of it, so the walker, the
// shape decoder and the text decoder all charge the stream's work budget.
let layers = {
let mut w = Ar::new();
w.page(|w| {
for _ in 0..20 {
w.layer("a layer with a name", 0, None, |w| w.frame(&[], &frame_spec(1), |_| {}));
}
});
w.out
};
let shape = one_frame_stream(&crate::tests::three_squares_body());
let text = page_with(|w| {
w.tag("CPicText");
let head = Head { matrix: [65536, 0, 0, 65536, 0, 0], bounds: [0, 2000, 0, 400], ..Head::default() };
w.out.extend(record(&head, &[(units(&"words ".repeat(100)), Style::default())]));
});
for stream in [layers, shape, text] {
assert!(crate::archive::parse_within(&stream, 4 * stream.len()).is_ok());
assert!(crate::archive::parse_within(&stream, stream.len() / 2).is_err());
}
}
#[test]
fn a_document_without_stage_properties_says_the_defaults_are_used() {
let mut contents = synthetic_contents();
let name = utf16("legacyLineSpacing");
let at = contents.windows(name.len()).position(|w| w == name.as_slice()).expect("the property");
contents[at] ^= 0x20; // no longer that property's name
let (doc, report) = crate::doc::import(&write(&[("Contents", contents), ("P 1 1", page_with(|_| {})), ("Symbol 9", one_frame_stream(&[]))])).expect("opens");
assert_eq!(doc.stage, anicraft_doc::Stage::default());
assert_eq!(skipped(&report, "the stage's size, colour and frame rate (not found: the defaults are used)"), 1, "{:?}", report.skipped);
}
+28 -3
View File
@@ -224,6 +224,11 @@ impl<'a> Reader<'a> {
/// the corpus's strings read `FF FE FF <u8>` and, from 255 units, `FF FE FF FF <u16>`.
/// Unmarked strings are 8-bit (read as Latin-1).
fn cstring(&mut self) -> Result<String, TextError> {
let (wide, len) = self.cstring_head()?;
Ok(if wide { String::from_utf16_lossy(&self.units(len)?) } else { self.take(len)?.iter().map(|&b| b as char).collect() })
}
/// A `CArchive` string's head: whether it is UTF-16, and its length in characters.
fn cstring_head(&mut self) -> Result<(bool, usize), TextError> {
let mut wide = false;
let len = loop {
let b = self.u8()?;
@@ -246,7 +251,7 @@ impl<'a> Reader<'a> {
if len > MAX_STRING {
return Err(TextError::TooLarge);
}
Ok(if wide { String::from_utf16_lossy(&self.units(len)?) } else { self.take(len)?.iter().map(|&b| b as char).collect() })
Ok((wide, len))
}
}
@@ -259,6 +264,15 @@ pub fn cstring(data: &[u8], at: usize) -> Result<(String, usize), TextError> {
Ok((s, r.at))
}
/// Where the `CArchive` string at `at` ends, read from its head alone: nothing is decoded, so
/// a scan can step over a string, or refuse a long one, without paying for its characters.
pub fn cstring_end(data: &[u8], at: usize) -> Result<usize, TextError> {
let mut r = Reader { data, at };
let (wide, len) = r.cstring_head()?;
r.take(if wide { len.checked_mul(2).ok_or(TextError::TooLarge)? } else { len })?;
Ok(r.at)
}
fn note(approximations: &mut Vec<&'static str>, what: &'static str) {
if !approximations.contains(&what) {
approximations.push(what);
@@ -338,7 +352,18 @@ fn block<'a>(r: &mut Reader<'a>, approximations: &mut Vec<&'static str>) -> Resu
/// Decodes the text record whose head (the `04` byte behind its class tag) is at `at`.
pub fn decode(data: &[u8], at: usize) -> Result<TextRecord, TextError> {
decode_counted(data, at).0
}
/// [`decode`], and how many bytes it read, whether it decoded or not: what the object walker
/// charges a trial against its stream's work budget.
pub(crate) fn decode_counted(data: &[u8], at: usize) -> (Result<TextRecord, TextError>, usize) {
let mut r = Reader { data, at };
let record = decode_in(&mut r, at);
(record, r.at.saturating_sub(at))
}
fn decode_in(r: &mut Reader, at: usize) -> Result<TextRecord, TextError> {
let head: [u8; HEAD] = r.bytes()?;
if head[0] != 0x04 || head[2..4] != [0, 0] || head[12..14] != [0, 0] || head[14] != 0x0D {
return Err(TextError::NotText);
@@ -367,7 +392,7 @@ pub fn decode(data: &[u8], at: usize) -> Result<TextRecord, TextError> {
// The stored runs, the 512-unit pieces of one run merged back as they come.
let mut merged: Vec<(Vec<u16>, RunStyle, &[u8])> = Vec::new();
if field_flags & NO_CHARACTERS != 0 {
let (style, raw) = block(&mut r, &mut approximations)?;
let (style, raw) = block(r, &mut approximations)?;
if r.u16()? != 0 {
return Err(TextError::Unclosed);
}
@@ -384,7 +409,7 @@ pub fn decode(data: &[u8], at: usize) -> Result<TextRecord, TextError> {
if stored > MAX_STORED_RUNS || total > MAX_UNITS {
return Err(TextError::TooLarge);
}
let (style, raw) = block(&mut r, &mut approximations)?;
let (style, raw) = block(r, &mut approximations)?;
let units = r.units(n)?;
match merged.last_mut() {
Some(last) if !last.0.is_empty() && last.0.len() % CHUNK == 0 && last.2 == raw => last.0.extend(units),