diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs
index 52eb9ea39..929a2b5fa 100644
--- a/crates/metafile/src/emf.rs
+++ b/crates/metafile/src/emf.rs
@@ -30,7 +30,7 @@ pub(crate) fn is_emf(b: Bytes) -> bool {
/// The picture frame: `rclFrame` (0.01 mm) mapped to device units through `szlDevice` and
/// `szlMillimeters`, sized in points. Without a usable frame, the device bounds stand in (1 unit = 1 point).
-pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> {
+pub(crate) fn parse(input: Bytes, depth: u8) -> Result<(Canvas, Option), Error> {
if !is_emf(input) {
return Err(Error::BadHeader);
}
@@ -45,7 +45,7 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> {
if let Some(px_mm) = device_px_per_mm(input) {
cv.set_device_mm(px_mm);
}
- let mut plus = crate::emfplus::Plus::new();
+ let mut plus = crate::emfplus::Plus::new(depth);
plus.frame = frame.as_ref().map(|f| f.rect);
let mut parsed = 0usize;
let mut pos = hsize.max(88);
diff --git a/crates/metafile/src/emfplus.rs b/crates/metafile/src/emfplus.rs
index 505149371..f507924bc 100644
--- a/crates/metafile/src/emfplus.rs
+++ b/crates/metafile/src/emfplus.rs
@@ -178,13 +178,9 @@ enum ImageData {
Meta(Picture),
}
-thread_local! {
- /// Nesting depth of metafile images being parsed, so a file of nested metafiles cannot run
- /// the stack out.
- static NESTING: std::cell::Cell = const { std::cell::Cell::new(0) };
-}
/// Metafile images inside metafile images, at most.
-pub(crate) const MAX_NESTING: usize = 3;
+#[cfg(test)]
+pub(crate) const MAX_NESTING: usize = crate::MAX_NESTED_DEPTH as usize;
#[derive(Clone)]
enum Obj {
@@ -241,12 +237,14 @@ pub(crate) struct Plus {
object_bytes: usize,
stack: Vec,
partial: Option,
+ /// Nesting depth of the outer metafile being played.
+ depth: u8,
/// The picture frame in device units (`[x, y, w, h]`), what Clear paints.
pub frame: Option<[f64; 4]>,
}
impl Plus {
- pub fn new() -> Self {
+ pub fn new(depth: u8) -> Self {
Plus {
dual: false,
gdi: false,
@@ -260,6 +258,7 @@ impl Plus {
object_bytes: 0,
stack: Vec::new(),
partial: None,
+ depth,
frame: None,
}
}
@@ -645,7 +644,7 @@ impl Plus {
let room = p.total.saturating_sub(p.data.len());
p.data.extend_from_slice(&chunk[..chunk.len().min(room)]);
if p.data.len() >= p.total {
- let obj = parse_object(p.kind, Bytes(&p.data));
+ let obj = parse_object(p.kind, Bytes(&p.data), self.depth);
self.store(p.id, obj, canvas_used);
} else {
self.partial = Some(p);
@@ -659,11 +658,11 @@ impl Plus {
{
let room = p.total.saturating_sub(p.data.len());
p.data.extend_from_slice(&r.0[..r.0.len().min(room)]);
- let obj = parse_object(kind, Bytes(&p.data));
+ let obj = parse_object(kind, Bytes(&p.data), self.depth);
self.store(id, obj, canvas_used);
return Some(());
}
- let obj = parse_object(kind, r);
+ let obj = parse_object(kind, r, self.depth);
self.store(id, obj, canvas_used);
Some(())
}
@@ -1074,13 +1073,13 @@ fn matrix(r: Bytes, off: usize) -> Option {
floats::<6>(r, off)
}
-fn parse_object(kind: u16, r: Bytes) -> Option {
+fn parse_object(kind: u16, r: Bytes, depth: u8) -> Option {
match kind {
1 => brush(r, 0).map(Obj::Brush).or_else(|| lost_texture(r).then_some(Obj::LostBrush)),
2 => pen(r),
3 => path(r).map(Obj::Path),
4 => region(r),
- 5 => Some(image(r).map_or_else(|| Obj::LostImage(bitmap_size(r)), |i| Obj::Image(Arc::new(i)))),
+ 5 => Some(image(r, depth).map_or_else(|| Obj::LostImage(bitmap_size(r)), |i| Obj::Image(Arc::new(i)))),
6 => font(r),
7 => Some(Obj::Format(Format { flags: r.u32(4)?, align: r.u32(12)?, line_align: r.u32(16)? })),
_ => None,
@@ -1097,7 +1096,7 @@ fn brush(r: Bytes, off: usize) -> Option {
let bflags = d.u32(0)?;
let wrap = d.u32(4)?;
let (xf, off) = if bflags & 0x2 != 0 { (matrix(d, 8)?, 32) } else { (IDENTITY, 8) };
- let ImageData::Bitmap(img) = image(d.tail(off)?)? else { return None };
+ let ImageData::Bitmap(img) = image(d.tail(off)?, crate::MAX_NESTED_DEPTH)? else { return None };
Some(Fill::Texture { img: Arc::new(img), wrap, xf })
}
3 => path_gradient(d),
@@ -1447,26 +1446,22 @@ fn font(r: Bytes) -> Option {
/// An image object: a bitmap of raw pixels or a compressed (PNG, JPEG, GIF…) file, or a nested
/// metafile.
-fn image(r: Bytes) -> Option {
+fn image(r: Bytes, depth: u8) -> Option {
match r.u32(4)? {
1 => bitmap(r).map(ImageData::Bitmap),
- 2 => metafile(r).map(ImageData::Meta),
+ 2 => metafile(r, depth).map(ImageData::Meta),
_ => None,
}
}
/// A metafile image: type, size, then a WMF (placeable or not) or EMF file, parsed as a picture.
-fn metafile(r: Bytes) -> Option {
+fn metafile(r: Bytes, depth: u8) -> Option {
let size = r.u32(12)? as usize;
let data = r.slice(16, size).or_else(|| r.tail(16).map(|t| t.0))?;
- let depth = NESTING.with(std::cell::Cell::get);
- if depth >= MAX_NESTING {
+ if depth >= crate::MAX_NESTED_DEPTH {
return None;
}
- NESTING.with(|n| n.set(depth + 1));
- let pic = crate::parse_nested(data).ok();
- NESTING.with(|n| n.set(depth));
- pic
+ crate::parse_nested(data, depth + 1).ok()
}
/// The size in pixels of a bitmap image object, read from its header (a compressed one's from the
@@ -1820,7 +1815,7 @@ mod cost_tests {
#[test]
fn an_object_is_not_stored_past_what_the_canvas_already_holds() {
- let mut plus = Plus::new();
+ let mut plus = Plus::new(0);
let path = || Some(Obj::Path(vec![Op::Z; 1000]));
plus.store(0, path(), crate::MAX_BYTES - 100);
assert!(plus.objects[0].is_none() && plus.object_bytes == 0);
@@ -1830,7 +1825,7 @@ mod cost_tests {
#[test]
fn an_image_or_texture_past_the_byte_budget_is_counted() {
- let (mut plus, mut cv) = (Plus::new(), Canvas::new());
+ let (mut plus, mut cv) = (Plus::new(0), Canvas::new());
let img = || Rgba { w: 4, h: 4, px: vec![0; 64] };
plus.store(0, Some(Obj::Image(Arc::new(ImageData::Bitmap(img())))), crate::MAX_BYTES);
assert!(matches!(plus.objects[0], Some(Obj::LostImage(Some((4, 4))))));
@@ -1854,7 +1849,7 @@ mod cost_tests {
#[test]
fn pieces_of_a_continued_object_count_against_the_shared_budget() {
- let (mut plus, mut cv) = (Plus::new(), Canvas::new());
+ let (mut plus, mut cv) = (Plus::new(0), Canvas::new());
// Image object (kind 5), id 0, continued: 1000 bytes announced, 100 delivered.
let mut rec = 1000u32.to_le_bytes().to_vec();
rec.extend([0u8; 100]);
@@ -1864,7 +1859,7 @@ mod cost_tests {
#[test]
fn current_and_saved_clips_count_against_the_shared_budget() {
- let (mut plus, mut cv) = (Plus::new(), Canvas::new());
+ let (mut plus, mut cv) = (Plus::new(0), Canvas::new());
let pts = vec![(0.0, 0.0); 1000];
plus.clip = Some(pts.clone());
plus.stack.push(Saved { id: 1, world: IDENTITY, page: 1.0, clip: Some(pts) });
diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs
index ea12c9ebe..a8732562a 100644
--- a/crates/metafile/src/lib.rs
+++ b/crates/metafile/src/lib.rs
@@ -66,6 +66,8 @@ pub(crate) const MAX_STACK: usize = 1024;
pub(crate) const MAX_PATH_OPS: usize = 2_000_000;
/// Bytes of path ops and pixels kept from one file (about 256 MB).
pub(crate) const MAX_BYTES: usize = 256 * 1024 * 1024;
+/// Maximum metafile nesting depth (EMF+ metafile images and WMF-wrapped EMFs).
+pub(crate) const MAX_NESTED_DEPTH: u8 = 3;
/// A parsed metafile. Items use coordinates in `0..width` and `0..height`, y down.
#[derive(Debug, Clone, PartialEq, Default)]
@@ -252,18 +254,41 @@ pub(crate) struct Frame {
/// Parses a WMF (placeable or plain) or EMF file.
pub fn parse(bytes: &[u8]) -> Result {
dib::set_decode_budget(dib::MAX_DECODE_PIXELS);
- parse_nested(bytes)
+ parse_nested(bytes, 0)
}
/// [`parse`] for a metafile inside the one being parsed: it draws on the same budgets.
-pub(crate) fn parse_nested(bytes: &[u8]) -> Result {
+pub(crate) fn parse_nested(bytes: &[u8], depth: u8) -> Result {
+ if depth > MAX_NESTED_DEPTH {
+ return Err(Error::NoRecords);
+ }
let b = Bytes(bytes);
let (cv, frame) = if emf::is_emf(b) {
- emf::parse(b)?
+ emf::parse(b, depth)?
} else if wmf::is_wmf(b) {
// A WMF converted from an EMF can carry the original in MFCOMMENT escapes; Office draws
- // the WMF's own records (its dx rounding shows), so the copy is not used.
- wmf::parse(b)?
+ // the WMF's own records (its dx rounding shows), so the copy is used only when the outer
+ // WMF produces no drawing items of its own.
+ let mut parsed = wmf::parse(b)?;
+ if parsed.cv.items.is_empty() {
+ if parsed.embedded_emf_capped {
+ parsed.cv.truncated_inside = true;
+ } else if let Some(emf_bytes) = parsed.embedded_emf.as_deref()
+ && emf::is_emf(Bytes(emf_bytes))
+ {
+ if depth >= MAX_NESTED_DEPTH {
+ parsed.cv.truncated_inside = true;
+ } else if let Ok(mut pic) = parse_nested(emf_bytes, depth + 1) {
+ pic.skipped_records = pic.skipped_records.saturating_add(parsed.cv.skipped);
+ pic.truncated |= parsed.cv.full() || parsed.cv.truncated_inside;
+ pic.dropped_images = pic.dropped_images.saturating_add(parsed.cv.dropped_images);
+ pic.ignored_clips = pic.ignored_clips.saturating_add(parsed.cv.ignored_clips);
+ pic.unplayed_raster_ops = pic.unplayed_raster_ops.saturating_add(parsed.cv.unplayed_raster_ops);
+ return Ok(pic);
+ }
+ }
+ }
+ (parsed.cv, parsed.frame)
} else if pict::is_pict(bytes) {
return pict::parse_nested(bytes);
} else {
diff --git a/crates/metafile/src/size.rs b/crates/metafile/src/size.rs
index 9d4e1f31d..f97de7fdc 100644
--- a/crates/metafile/src/size.rs
+++ b/crates/metafile/src/size.rs
@@ -94,7 +94,7 @@ fn sets_the_mapping(b: Bytes, mut pos: usize) -> bool {
if func == 0 || b.slice(pos, len).is_none() {
return false;
}
- if matches!(func, 0x0103 | 0x020E) {
+ if matches!(func, 0x0103 | 0x020E) || (func == 0x0626 && pos.checked_add(6).and_then(|o| b.u16(o)) == Some(0x000F)) {
return true;
}
let Some(next) = pos.checked_add(len) else { return false };
diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs
index 9f929108b..a0609c39d 100644
--- a/crates/metafile/src/tests.rs
+++ b/crates/metafile/src/tests.rs
@@ -357,7 +357,8 @@ fn truncated_random_and_mutated_inputs_never_panic() {
[0, 0, 20, 10],
[0, 0, 2540, 1270],
);
- for file in [&wfile, &efile] {
+ let wmfc_file = wmf(&wmfc_chunks(&efile, &[efile.len() / 2, efile.len() - efile.len() / 2]), None);
+ for file in [&wfile, &efile, &wmfc_file] {
for n in 0..=file.len() {
let prefix = &file[..n];
let _ = parse(prefix);
@@ -371,7 +372,11 @@ fn truncated_random_and_mutated_inputs_never_panic() {
let _ = parse(&buf);
}
for i in 0..1500usize {
- let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() };
+ let mut buf = match i % 3 {
+ 0 => efile.clone(),
+ 1 => wfile.clone(),
+ _ => wmfc_file.clone(),
+ };
for _ in 0..8 {
let at = rng.rnd() as usize % buf.len();
buf[at] = rng.rnd() as u8;
@@ -379,7 +384,11 @@ fn truncated_random_and_mutated_inputs_never_panic() {
let _ = parse(&buf);
}
for i in 0..500usize {
- let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() };
+ let mut buf = match i % 3 {
+ 0 => efile.clone(),
+ 1 => wfile.clone(),
+ _ => wmfc_file.clone(),
+ };
let at = rng.rnd() as usize % buf.len();
buf[at..].iter_mut().for_each(|b| *b = 0xFF);
let _ = parse(&buf);
@@ -2790,3 +2799,202 @@ fn wmf_viewport_scaling_before_first_window_is_retained() {
assert_eq!(p.skipped_records, 0);
assert_eq!(rect_extent(&p.items[0]), (0.0, 0.0, 50.0, 100.0));
}
+
+struct WmfcChunk<'a> {
+ escape_fn: u16,
+ identifier: u32,
+ comment_type: u32,
+ version: u32,
+ flags: u32,
+ record_count: u32,
+ current_size: u32,
+ remaining: u32,
+ total_size: u32,
+ data: &'a [u8],
+}
+
+impl<'a> WmfcChunk<'a> {
+ fn single(data: &'a [u8]) -> Self {
+ let n = data.len() as u32;
+ Self {
+ escape_fn: 0x000F,
+ identifier: 0x4346_4D57,
+ comment_type: 1,
+ version: 0x0001_0000,
+ flags: 0,
+ record_count: 1,
+ current_size: n,
+ remaining: 0,
+ total_size: n,
+ data,
+ }
+ }
+
+ fn encode(&self) -> Vec {
+ let byte_count = (34 + self.data.len()) as u16;
+ let mut p = Vec::with_capacity(4 + 34 + self.data.len());
+ p.extend(self.escape_fn.to_le_bytes());
+ p.extend(byte_count.to_le_bytes());
+ p.extend(self.identifier.to_le_bytes());
+ p.extend(self.comment_type.to_le_bytes());
+ p.extend(self.version.to_le_bytes());
+ p.extend(0u16.to_le_bytes()); // checksum
+ p.extend(self.flags.to_le_bytes());
+ p.extend(self.record_count.to_le_bytes());
+ p.extend(self.current_size.to_le_bytes());
+ p.extend(self.remaining.to_le_bytes());
+ p.extend(self.total_size.to_le_bytes());
+ p.extend(self.data);
+ wrec(0x0626, &p)
+ }
+}
+
+fn wmfc_chunks(emf_bytes: &[u8], chunk_sizes: &[usize]) -> Vec> {
+ let total = emf_bytes.len() as u32;
+ let count = chunk_sizes.len() as u32;
+ let mut off = 0usize;
+ let mut out = Vec::with_capacity(chunk_sizes.len());
+ for &sz in chunk_sizes {
+ let end = off + sz;
+ let rem = (emf_bytes.len() - end) as u32;
+ out.push(
+ WmfcChunk { record_count: count, current_size: sz as u32, remaining: rem, total_size: total, ..WmfcChunk::single(&emf_bytes[off..end]) }
+ .encode(),
+ );
+ off = end;
+ }
+ assert_eq!(off, emf_bytes.len());
+ out
+}
+
+fn sample_ole_emf() -> Vec {
+ let mut stretch = cat(vec![
+ e32(0),
+ e32(0),
+ e32(100),
+ e32(50),
+ e32(0),
+ e32(0),
+ e32(0),
+ e32(0),
+ e32(2),
+ e32(2),
+ e32(80),
+ e32(40),
+ e32(120),
+ e32(16),
+ e32(0),
+ e32(0x00CC_0020),
+ e32(100),
+ e32(50),
+ ]);
+ stretch.extend(info_header(2, 2, 24, 16));
+ stretch.extend(dib24_bottom_up().get(40..).unwrap_or_default());
+ // EMR_STRETCHDIBITS + stock HOLLOW_BRUSH (0x8000_0005) + Rectangle, with rclBounds = (0, 0, -1, -1).
+ emf(
+ &[erec(81, &stretch), erec(37, &h32(0x8000_0005)), erec(43, &cat(vec![e32(10), e32(10), e32(90), e32(40)]))],
+ [0, 0, -1, -1],
+ [0, 0, 2500, 1250],
+ )
+}
+
+#[test]
+fn wmf_meta_escape_enhanced_metafile_single_and_multi_chunk() {
+ let inner = sample_ole_emf();
+ let direct = parse(&inner).unwrap();
+ assert_eq!(direct.items.len(), 2);
+ assert!(matches!(direct.items[0], Item::Bitmap { width: 2, height: 2, .. }));
+ assert!(matches!(direct.items[1], Item::Path { fill: None, stroke: Some(_), .. }));
+
+ // Single-chunk WMFC inside a placeable WMF with no native drawing records.
+ let single = wmf(&wmfc_chunks(&inner, &[inner.len()]), Some([0, 0, 1000, 500]));
+ let p1 = parse(&single).unwrap();
+ assert_eq!(p1.items, direct.items);
+ assert!((p1.width - direct.width).abs() < 1e-3 && (p1.height - direct.height).abs() < 1e-3);
+ assert_eq!(crate::size(&single).unwrap(), (p1.width, p1.height));
+
+ // Multi-chunk WMFC including an odd-sized chunk padded to a 16-bit WMF word boundary.
+ let c0 = 33usize;
+ let c1 = 75usize;
+ let c2 = inner.len() - c0 - c1;
+ let multi = wmf(&wmfc_chunks(&inner, &[c0, c1, c2]), None);
+ let p2 = parse(&multi).unwrap();
+ assert_eq!(p2.items, direct.items);
+ assert_eq!(crate::size(&multi).unwrap(), (p2.width, p2.height));
+}
+
+#[test]
+fn wmf_with_native_records_ignores_embedded_emf_escape() {
+ let inner = sample_ole_emf();
+ let mut recs = wmfc_chunks(&inner, &[inner.len()]);
+ recs.push(wrec(0x041B, &cat(vec![h16(20), h16(20), h16(10), h16(10)])));
+ let p = parse(&wmf(&recs, Some([0, 0, 100, 100]))).unwrap();
+ assert_eq!(p.items.len(), 1);
+ assert!(matches!(p.items[0], Item::Path { .. }));
+ assert_eq!(p.skipped_records, 0);
+}
+
+#[test]
+fn wmf_malformed_or_oversized_wmfc_is_rejected_without_panic() {
+ let inner = sample_ole_emf();
+
+ // 1. Truncated stream (RemainingBytes > 0 with no following chunk).
+ let truncated = wmf(
+ &[WmfcChunk { record_count: 2, remaining: (inner.len() - 10) as u32, total_size: inner.len() as u32, ..WmfcChunk::single(&inner[..10]) }
+ .encode()],
+ None,
+ );
+ let p = parse(&truncated).unwrap();
+ assert!(p.items.is_empty());
+
+ // 2. Mismatched RemainingBytes on the second chunk.
+ let half = inner.len() / 2;
+ let bad_rem = wmf(
+ &[
+ WmfcChunk {
+ record_count: 2,
+ remaining: (inner.len() - half) as u32,
+ total_size: inner.len() as u32,
+ ..WmfcChunk::single(&inner[..half])
+ }
+ .encode(),
+ WmfcChunk { record_count: 2, remaining: 1, total_size: inner.len() as u32, ..WmfcChunk::single(&inner[half..]) }.encode(),
+ ],
+ None,
+ );
+ assert!(parse(&bad_rem).unwrap().items.is_empty());
+
+ // 3. Mismatched EnhancedMetafileDataSize across chunks.
+ let bad_total = wmf(
+ &[
+ WmfcChunk {
+ record_count: 2,
+ remaining: (inner.len() - half) as u32,
+ total_size: inner.len() as u32,
+ ..WmfcChunk::single(&inner[..half])
+ }
+ .encode(),
+ WmfcChunk { record_count: 2, total_size: (inner.len() + 4) as u32, ..WmfcChunk::single(&inner[half..]) }.encode(),
+ ],
+ None,
+ );
+ assert!(parse(&bad_total).unwrap().items.is_empty());
+
+ // 4. Invalid Version and non-zero Flags.
+ let bad_ver = wmf(&[WmfcChunk { version: 0x0002_0000, ..WmfcChunk::single(&inner) }.encode()], None);
+ assert!(parse(&bad_ver).unwrap().items.is_empty());
+ let bad_flags = wmf(&[WmfcChunk { flags: 1, ..WmfcChunk::single(&inner) }.encode()], None);
+ assert!(parse(&bad_flags).unwrap().items.is_empty());
+
+ // 5. Oversized EnhancedMetafileDataSize (> MAX_EMBEDDED_EMF_BYTES) with a tiny payload.
+ let over = (crate::wmf::MAX_EMBEDDED_EMF_BYTES + 1) as u32;
+ let oversized = wmf(&[WmfcChunk { remaining: over - 8, total_size: over, ..WmfcChunk::single(&[0u8; 8]) }.encode()], None);
+ let p_over = parse(&oversized).unwrap();
+ assert!(p_over.items.is_empty());
+ assert!(p_over.truncated);
+
+ // 6. Non-EMF bytes (e.g. a WMF) inside valid WMFC chunks are ignored safely.
+ let fake_wmf = wmf(&[wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)]))], None);
+ let wrapped_wmf = wmf(&wmfc_chunks(&fake_wmf, &[fake_wmf.len()]), None);
+ assert!(parse(&wrapped_wmf).unwrap().items.is_empty());
+}
diff --git a/crates/metafile/src/tests/limits.rs b/crates/metafile/src/tests/limits.rs
index 821ee52d6..6b88c4284 100644
--- a/crates/metafile/src/tests/limits.rs
+++ b/crates/metafile/src/tests/limits.rs
@@ -102,6 +102,22 @@ fn metafiles_nest_only_so_deep() {
assert_eq!(nested(emfplus::MAX_NESTING + 1), 0, "the innermost picture is not read");
}
+#[test]
+fn wmf_wrapped_emf_shares_nesting_depth_cap() {
+ let square = emf(&[erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))], [0; 4], [0; 4]);
+ let wmf_wrap = |inner: Vec| wmf(&wmfc_chunks(&inner, &[inner.len()]), None);
+ // WMF (0) -> EMF (1) -> EMF+ WMF (2) -> EMF (3): at MAX_NESTED_DEPTH, still drawn.
+ let ok = wmf_wrap(wrap(wmf_wrap(square.clone())));
+ let p_ok = parse(&ok).unwrap();
+ assert_eq!(p_ok.items.len(), 1);
+ assert!(!p_ok.truncated);
+ // One more EMF+ level exceeds MAX_NESTED_DEPTH: stops cleanly without stack overflow.
+ let too_deep = wmf_wrap(wrap(wmf_wrap(wrap(square))));
+ let p_deep = parse(&too_deep).unwrap();
+ assert_eq!(p_deep.items.len(), 0);
+ assert_eq!(p_deep.dropped_images, 1);
+}
+
#[test]
fn emfplus_images_that_are_not_read_are_counted() {
let square = || emf(&[erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))], [0; 4], [0; 4]);
diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs
index 915d1d229..4c9382da6 100644
--- a/crates/metafile/src/wmf.rs
+++ b/crates/metafile/src/wmf.rs
@@ -14,6 +14,132 @@ pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7;
const DEFAULT_INCH: f64 = 1440.0;
/// A placeable WMF plays into a target sized in points; brushes are laid out in 96-dpi pixels.
const PT_PER_PX: f64 = 72.0 / 96.0;
+const META_ESCAPE: u16 = 0x0626;
+const META_ESCAPE_ENHANCED_METAFILE: u16 = 0x000F;
+const WMFC_IDENTIFIER: u32 = 0x4346_4D57;
+const WMFC_COMMENT_TYPE: u32 = 0x0000_0001;
+const WMFC_VERSION: u32 = 0x0001_0000;
+const WMFC_HEADER_LEN: usize = 34;
+/// Largest embedded EMF reassembled from `META_ESCAPE_ENHANCED_METAFILE` chunks (16 MiB).
+pub(crate) const MAX_EMBEDDED_EMF_BYTES: usize = 16 * 1024 * 1024;
+
+pub(crate) struct ParsedWmf {
+ pub cv: Canvas,
+ pub frame: Option,
+ pub embedded_emf: Option>,
+ pub embedded_emf_capped: bool,
+}
+
+enum CollectorState {
+ Empty,
+ Collecting { buf: Vec, total: usize, expected_records: u32, seen_records: u32 },
+ Done(Vec),
+ Invalid,
+}
+
+/// Reassembles an embedded EMF from `META_ESCAPE_ENHANCED_METAFILE` (`0x0626` / `0x000F`) chunks
+/// ([MS-WMF] §2.3.6.14).
+struct EmfCollector {
+ state: CollectorState,
+ capped: bool,
+}
+
+impl EmfCollector {
+ fn new() -> Self {
+ Self { state: CollectorState::Empty, capped: false }
+ }
+
+ fn push(&mut self, r: Bytes) {
+ if r.u16(6) != Some(META_ESCAPE_ENHANCED_METAFILE) {
+ return;
+ }
+ // Only "WMFC" with CommentType == 1 carries an embedded EMF; other MFCOMMENT records are ignored.
+ if r.u32(10) != Some(WMFC_IDENTIFIER) || r.u32(14) != Some(WMFC_COMMENT_TYPE) {
+ return;
+ }
+ if !matches!(self.state, CollectorState::Empty | CollectorState::Collecting { .. }) {
+ return;
+ }
+ let Some(byte_count) = r.u16(8).map(usize::from) else {
+ self.state = CollectorState::Invalid;
+ return;
+ };
+ if byte_count < WMFC_HEADER_LEN || 10usize.checked_add(byte_count).is_none_or(|end| end > r.0.len()) {
+ self.state = CollectorState::Invalid;
+ return;
+ }
+ let (Some(version), Some(flags), Some(record_count)) = (r.u32(18), r.u32(24), r.u32(28)) else {
+ self.state = CollectorState::Invalid;
+ return;
+ };
+ let (Some(current_size), Some(remaining), Some(total_size)) =
+ (r.u32(32).map(|v| v as usize), r.u32(36).map(|v| v as usize), r.u32(40).map(|v| v as usize))
+ else {
+ self.state = CollectorState::Invalid;
+ return;
+ };
+ if version != WMFC_VERSION
+ || flags != 0
+ || record_count == 0
+ || current_size == 0
+ || total_size == 0
+ || WMFC_HEADER_LEN.checked_add(current_size).is_none_or(|n| n > byte_count)
+ {
+ self.state = CollectorState::Invalid;
+ return;
+ }
+ if total_size > MAX_EMBEDDED_EMF_BYTES {
+ self.capped = true;
+ self.state = CollectorState::Invalid;
+ return;
+ }
+ let Some(chunk) = r.slice(44, current_size) else {
+ self.state = CollectorState::Invalid;
+ return;
+ };
+ let state = std::mem::replace(&mut self.state, CollectorState::Invalid);
+ self.state = match state {
+ CollectorState::Empty => {
+ if current_size.checked_add(remaining) != Some(total_size) {
+ CollectorState::Invalid
+ } else {
+ let mut buf = Vec::new();
+ buf.extend_from_slice(chunk);
+ if remaining == 0 {
+ if record_count == 1 { CollectorState::Done(buf) } else { CollectorState::Invalid }
+ } else {
+ CollectorState::Collecting { buf, total: total_size, expected_records: record_count, seen_records: 1 }
+ }
+ }
+ }
+ CollectorState::Collecting { mut buf, total, expected_records, mut seen_records } => {
+ if total_size != total
+ || record_count != expected_records
+ || seen_records >= expected_records
+ || buf.len().checked_add(current_size).and_then(|n| n.checked_add(remaining)) != Some(total)
+ {
+ CollectorState::Invalid
+ } else {
+ buf.extend_from_slice(chunk);
+ seen_records += 1;
+ if remaining == 0 {
+ if seen_records == expected_records && buf.len() == total { CollectorState::Done(buf) } else { CollectorState::Invalid }
+ } else {
+ CollectorState::Collecting { buf, total, expected_records, seen_records }
+ }
+ }
+ }
+ other => other,
+ };
+ }
+
+ fn finish(self) -> (Option>, bool) {
+ match self.state {
+ CollectorState::Done(buf) => (Some(buf), self.capped),
+ _ => (None, self.capped),
+ }
+ }
+}
pub(crate) fn is_wmf(b: Bytes) -> bool {
if b.u32(0) == Some(PLACEABLE_KEY) {
@@ -22,9 +148,9 @@ pub(crate) fn is_wmf(b: Bytes) -> bool {
matches!(b.u16(0), Some(1 | 2)) && b.u16(2) == Some(9) && matches!(b.u16(4), Some(0x100 | 0x300))
}
-/// Reads all records. Returns the drawing state and the picture frame, or an error when no record
-/// could be read at all.
-pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> {
+/// Reads all records. Returns the drawing state, picture frame, and any complete embedded EMF
+/// reassembled from `META_ESCAPE_ENHANCED_METAFILE`, or an error when no record could be read.
+pub(crate) fn parse(input: Bytes) -> Result {
let placeable = input.u32(0) == Some(PLACEABLE_KEY);
// Placeable bounds: logical corners (left, top, right, bottom) and their size in points.
let (hdr, bounds) = if placeable {
@@ -52,6 +178,7 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> {
}
// Keep the player target independent of subsequent mapping changes.
let mut player_target = bounds.map(|(_, size)| size);
+ let mut emf_collector = EmfCollector::new();
let mut parsed = 0usize;
while !cv.full() {
let (Some(words), Some(func)) = (input.u32(pos), pos.checked_add(4).and_then(|o| input.u16(o))) else { break };
@@ -60,7 +187,11 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> {
if func == 0 {
break;
}
- record(&mut cv, func, Bytes(rec));
+ if func == META_ESCAPE {
+ emf_collector.push(Bytes(rec));
+ } else {
+ record(&mut cv, func, Bytes(rec));
+ }
if func == 0x020C && cv.window_set && player_target.is_none() && !cv.viewport_set {
let we = cv.map.window_ext();
let target = (we.0.abs(), we.1.abs());
@@ -93,7 +224,8 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> {
None if cv.window_set => Some(Frame { rect: cv.map.window_rect(), size: None }),
None => None,
};
- Ok((cv, frame))
+ let (embedded_emf, embedded_emf_capped) = emf_collector.finish();
+ Ok(ParsedWmf { cv, frame, embedded_emf, embedded_emf_capped })
}
fn record(cv: &mut Canvas, func: u16, r: Bytes) {
@@ -202,9 +334,9 @@ fn record(cv: &mut Canvas, func: u16, r: Bytes) {
}
/// Records that change nothing the picture keeps: relative-absolute and stretch modes, character
-/// spacing and justification, mapper flags, palettes, escapes and the layout. Every other record
+/// spacing and justification, mapper flags, palettes and the layout. Every other record
/// the reader does not play is counted as skipped.
-const IGNORED: &[u16] = &[0x0105, 0x0107, 0x0108, 0x020A, 0x0231, 0x0234, 0x0035, 0x0037, 0x0139, 0x0436, 0x0626, 0x0149];
+const IGNORED: &[u16] = &[0x0105, 0x0107, 0x0108, 0x020A, 0x0231, 0x0234, 0x0035, 0x0037, 0x0139, 0x0436, 0x0149];
/// A 16-bit WMF handle as a canvas object index: stock objects are `0x8000 | index`, which the
/// canvas reads with the 32-bit stock flag.