1pub mod constants;
4pub mod objects;
5pub mod records;
6
7pub use objects::header::Header;
8
9use super::Error;
10use records::Record;
11
12const RT_HEADER: u32 = 0x00000001;
14const RT_EOF: u32 = 0x0000000E;
15const RT_SET_WINDOW_EXT_EX: u32 = 0x00000009;
16const RT_SET_WINDOW_ORG_EX: u32 = 0x0000000A;
17const RT_SET_VIEWPORT_EXT_EX: u32 = 0x0000000B;
18const RT_SET_VIEWPORT_ORG_EX: u32 = 0x0000000C;
19const RT_SET_MAP_MODE: u32 = 0x00000011;
20const RT_SET_BK_MODE: u32 = 0x00000012;
21const RT_SET_POLY_FILL_MODE: u32 = 0x00000013;
22const RT_SET_BRUSH_ORG_EX: u32 = 0x0000000D;
23const RT_SET_TEXT_ALIGN: u32 = 0x00000016;
24const RT_SET_TEXT_COLOR: u32 = 0x00000018;
25const RT_SET_BK_COLOR: u32 = 0x00000019;
26const RT_SAVE_DC: u32 = 0x00000021;
27const RT_RESTORE_DC: u32 = 0x00000022;
28const RT_SET_WORLD_TRANSFORM: u32 = 0x00000023;
29const RT_MODIFY_WORLD_TRANSFORM: u32 = 0x00000024;
30const RT_SELECT_OBJECT: u32 = 0x00000025;
31const RT_CREATE_PEN: u32 = 0x00000026;
32const RT_CREATE_BRUSH_INDIRECT: u32 = 0x00000027;
33const RT_EXT_CREATE_PEN: u32 = 0x0000005F;
35const RT_CREATE_DIB_PATTERN_BRUSH: u32 = 0x0000005E;
36const RT_INTERSECT_CLIP_RECT: u32 = 0x0000001E;
38const RT_EXT_SELECT_CLIP_RGN: u32 = 0x0000004B;
39const RT_DELETE_OBJECT: u32 = 0x00000028;
40const RT_EXT_CREATE_FONT_INDIRECT_W: u32 = 0x00000052;
41const RT_MOVE_TO_EX: u32 = 0x0000001B;
43const RT_ELLIPSE: u32 = 0x0000002A;
44const RT_RECTANGLE: u32 = 0x0000002B;
45const RT_ROUND_RECT: u32 = 0x0000002C;
46const RT_ARC: u32 = 0x0000002D;
47const RT_CHORD: u32 = 0x0000002E;
48const RT_PIE: u32 = 0x0000002F;
49const RT_LINE_TO: u32 = 0x00000036;
50const RT_POLYBEZIER16: u32 = 0x00000055;
51const RT_POLYGON16: u32 = 0x00000056;
53const RT_POLYLINE16: u32 = 0x00000057;
54const RT_POLYBEZIER_TO16: u32 = 0x00000058;
56const RT_POLYLINE_TO16: u32 = 0x00000059;
57const RT_POLY_POLYGON16: u32 = 0x0000005B;
58const RT_BEGIN_PATH: u32 = 0x0000003B;
60const RT_END_PATH: u32 = 0x0000003C;
61const RT_CLOSE_FIGURE: u32 = 0x0000003D;
62const RT_FILL_PATH: u32 = 0x0000003E;
63const RT_STROKE_AND_FILL_PATH: u32 = 0x0000003F;
64const RT_STROKE_PATH: u32 = 0x00000040;
65const RT_EXT_TEXT_OUT_W: u32 = 0x00000054;
67const RT_STRETCH_DI_BITS: u32 = 0x00000051;
68const RT_COMMENT: u32 = 0x00000046;
70const RT_MAX: u32 = 0x0000007A;
72const MAX_RESYNCS: usize = 8;
74
75pub fn parse(bytes: &[u8]) -> Result<Vec<Record>, Error> {
83 let mut cursor = Cursor::new(bytes);
84 let mut out = Vec::new();
85
86 let first = cursor.peek_record_header()?;
88 if first.record_type != RT_HEADER {
89 return Err(Error::InvalidFirstRecord {
90 got: first.record_type,
91 });
92 }
93 let header_record = records::header::parse(&mut cursor)?;
94 out.push(Record::Header(header_record));
95
96 let mut emfplus_comment_seen = false;
97 let mut resyncs = 0usize;
98
99 while !cursor.is_empty() {
101 let record_start = cursor.position();
102 let step = parse_one_record(&mut cursor, &mut emfplus_comment_seen);
103 match step {
104 Ok(record) => {
105 let eof = matches!(record, Record::Eof);
106 out.push(record);
107 if eof {
108 break;
109 }
110 }
111 Err(err) => {
112 if emfplus_comment_seen && resyncs < MAX_RESYNCS {
114 if let Some(next) = find_resync(bytes, record_start + 4) {
115 resyncs += 1;
116 cursor = Cursor::new(bytes);
117 let _ = cursor.take(next)?;
118 continue;
119 }
120 }
121 if emfplus_comment_seen && out.iter().any(is_paintable) {
125 break;
126 }
127 return Err(err);
128 }
129 }
130 }
131
132 Ok(out)
133}
134
135fn is_paintable(record: &Record) -> bool {
137 matches!(
138 record,
139 Record::StretchDIBits(_)
140 | Record::ExtTextOutW(_)
141 | Record::Rectangle(_)
142 | Record::Ellipse(_)
143 | Record::RoundRect { .. }
144 | Record::Arc { .. }
145 | Record::Chord { .. }
146 | Record::Pie { .. }
147 | Record::LineTo(_)
148 | Record::Polyline16 { .. }
149 | Record::Polygon16 { .. }
150 | Record::PolyBezier16 { .. }
151 | Record::PolylineTo16 { .. }
152 | Record::PolyBezierTo16 { .. }
153 | Record::IntersectClipRect(_)
154 | Record::ExtSelectClipRgn { .. }
155 | Record::FillPath(_)
156 | Record::StrokePath(_)
157 | Record::StrokeAndFillPath(_)
158 )
159}
160
161fn parse_one_record(
164 cursor: &mut Cursor<'_>,
165 emfplus_comment_seen: &mut bool,
166) -> Result<Record, Error> {
167 let rh = cursor.peek_record_header()?;
168 let record_start = cursor.position();
169 let payload_len = (rh.size as usize)
170 .checked_sub(8)
171 .ok_or(Error::RecordTooSmall {
172 offset: record_start,
173 size: rh.size,
174 })?;
175
176 let _ = cursor.take(8)?;
178
179 let payload = cursor.take(payload_len)?;
181 if rh.record_type == RT_COMMENT && payload.len() >= 8 && &payload[4..8] == b"EMF+" {
182 *emfplus_comment_seen = true;
183 }
184 let mut sub = Cursor::new(payload);
185
186 dispatch(rh.record_type, &mut sub, payload_len)
187}
188
189fn find_resync(bytes: &[u8], from: usize) -> Option<usize> {
195 let mut p = from.checked_add(3)? & !3usize;
196 while p + 8 <= bytes.len() {
197 if let Some(h) = plausible_header_at(bytes, p) {
198 if chain_is_plausible(bytes, p, &h, 2) || stretch_dibits_self_consistent(bytes, p, &h) {
201 return Some(p);
202 }
203 }
204 p += 4;
205 }
206 None
207}
208
209fn stretch_dibits_self_consistent(bytes: &[u8], pos: usize, header: &RecordHeader) -> bool {
212 if header.record_type != RT_STRETCH_DI_BITS {
213 return false;
214 }
215 let size = header.size as usize;
216 if size < 80 + 40 {
218 return false;
219 }
220 let f = |off: usize| -> usize {
221 let b = &bytes[pos + off..pos + off + 4];
222 u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize
223 };
224 let (off_bmi, cb_bmi, off_bits, cb_bits) = (f(48), f(52), f(56), f(60));
225 off_bmi >= 80
226 && cb_bmi >= 40
227 && cb_bits > 0
228 && off_bmi.saturating_add(cb_bmi) <= size
229 && off_bits.saturating_add(cb_bits) <= size
230 && f(off_bmi) == 40
232}
233
234fn plausible_header_at(bytes: &[u8], pos: usize) -> Option<RecordHeader> {
236 let b = bytes.get(pos..pos + 8)?;
237 let record_type = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
238 let size = u32::from_le_bytes([b[4], b[5], b[6], b[7]]);
239 if !(1..=RT_MAX).contains(&record_type) {
240 return None;
241 }
242 if size < 8 || size % 4 != 0 {
243 return None;
244 }
245 if pos + size as usize > bytes.len() {
246 return None;
247 }
248 Some(RecordHeader { record_type, size })
249}
250
251fn chain_is_plausible(bytes: &[u8], pos: usize, header: &RecordHeader, depth: usize) -> bool {
254 if header.record_type == RT_EOF || depth == 0 {
255 return true;
256 }
257 let next = pos + header.size as usize;
258 if next == bytes.len() {
259 return true;
260 }
261 match plausible_header_at(bytes, next) {
262 Some(h) => chain_is_plausible(bytes, next, &h, depth - 1),
263 None => false,
264 }
265}
266
267fn dispatch(record_type: u32, c: &mut Cursor<'_>, payload_len: usize) -> Result<Record, Error> {
268 use records::{bitmap, drawing, object, path, state, text};
269
270 let rec = match record_type {
271 RT_EOF => Record::Eof,
272
273 RT_CREATE_PEN => {
275 let (handle, pen) = object::parse_create_pen(c)?;
276 Record::CreatePen { handle, pen }
277 }
278 RT_CREATE_BRUSH_INDIRECT => {
279 let (handle, brush) = object::parse_create_brush_indirect(c)?;
280 Record::CreateBrushIndirect { handle, brush }
281 }
282 RT_CREATE_DIB_PATTERN_BRUSH => {
283 let (handle, brush) = bitmap::parse_pattern_brush(c.full_buf())?;
284 Record::CreateDibPatternBrush { handle, brush }
285 }
286 RT_INTERSECT_CLIP_RECT => Record::IntersectClipRect(drawing::parse_rect(c)?),
287 RT_EXT_SELECT_CLIP_RGN => {
288 let cb_rgn_data = c.u32()?;
289 let mode = c.u32()?;
290 Record::ExtSelectClipRgn {
291 mode,
292 has_region: cb_rgn_data > 0,
293 }
294 }
295 RT_EXT_CREATE_PEN => {
296 let (handle, pen) = object::parse_ext_create_pen(c)?;
297 Record::CreatePen { handle, pen }
298 }
299 RT_EXT_CREATE_FONT_INDIRECT_W => {
300 let (handle, font) = object::parse_ext_create_font_indirect_w(c, payload_len)?;
301 Record::ExtCreateFontIndirectW { handle, font }
302 }
303 RT_SELECT_OBJECT => Record::SelectObject {
304 handle: object::parse_select_object(c)?,
305 },
306 RT_DELETE_OBJECT => Record::DeleteObject {
307 handle: object::parse_delete_object(c)?,
308 },
309
310 RT_SAVE_DC => Record::SaveDC,
312 RT_RESTORE_DC => Record::RestoreDC {
313 relative: state::parse_restore_dc(c)?,
314 },
315 RT_SET_WORLD_TRANSFORM => Record::SetWorldTransform(state::parse_set_world_transform(c)?),
316 RT_MODIFY_WORLD_TRANSFORM => {
317 let (xform, mode) = state::parse_modify_world_transform(c)?;
318 Record::ModifyWorldTransform { xform, mode }
319 }
320
321 RT_SET_MAP_MODE => Record::SetMapMode(state::parse_u32_single(c)?),
323 RT_SET_WINDOW_EXT_EX => Record::SetWindowExtEx(state::parse_set_window_ext_ex(c)?),
324 RT_SET_WINDOW_ORG_EX => Record::SetWindowOrgEx(state::parse_set_window_org_ex(c)?),
325 RT_SET_VIEWPORT_EXT_EX => Record::SetViewportExtEx(state::parse_set_viewport_ext_ex(c)?),
326 RT_SET_VIEWPORT_ORG_EX => Record::SetViewportOrgEx(state::parse_set_viewport_org_ex(c)?),
327
328 RT_SET_BK_MODE => Record::SetBkMode(state::parse_u32_single(c)?),
330 RT_SET_POLY_FILL_MODE => Record::SetPolyFillMode(state::parse_u32_single(c)?),
331 RT_SET_BRUSH_ORG_EX => Record::SetBrushOrgEx(drawing::parse_point(c)?),
332 RT_SET_TEXT_ALIGN => Record::SetTextAlign(state::parse_u32_single(c)?),
333 RT_SET_TEXT_COLOR => Record::SetTextColor(state::parse_u32_single(c)?),
334 RT_SET_BK_COLOR => Record::SetBkColor(state::parse_u32_single(c)?),
335
336 RT_MOVE_TO_EX => Record::MoveToEx(drawing::parse_point(c)?),
338 RT_LINE_TO => Record::LineTo(drawing::parse_point(c)?),
339 RT_RECTANGLE => Record::Rectangle(drawing::parse_rect(c)?),
340 RT_ELLIPSE => Record::Ellipse(drawing::parse_rect(c)?),
341 RT_ROUND_RECT => {
342 let (rect, corner_w, corner_h) = drawing::parse_round_rect(c)?;
343 Record::RoundRect {
344 rect,
345 corner_w,
346 corner_h,
347 }
348 }
349 RT_ARC => {
350 let (r, s, e) = drawing::parse_arc_like(c)?;
351 Record::Arc {
352 rect: r,
353 start: s,
354 end: e,
355 }
356 }
357 RT_CHORD => {
358 let (r, s, e) = drawing::parse_arc_like(c)?;
359 Record::Chord {
360 rect: r,
361 start: s,
362 end: e,
363 }
364 }
365 RT_PIE => {
366 let (r, s, e) = drawing::parse_arc_like(c)?;
367 Record::Pie {
368 rect: r,
369 start: s,
370 end: e,
371 }
372 }
373 RT_POLYLINE16 => {
374 let (bounds, points) = drawing::parse_points16(c)?;
375 Record::Polyline16 { bounds, points }
376 }
377 RT_POLYGON16 => {
378 let (bounds, points) = drawing::parse_points16(c)?;
379 Record::Polygon16 { bounds, points }
380 }
381 RT_POLY_POLYGON16 => {
382 let (bounds, polygons) = drawing::parse_poly_polygon16(c)?;
383 Record::PolyPolygon16 { bounds, polygons }
384 }
385 RT_POLYBEZIER16 => {
386 let (bounds, points) = drawing::parse_points16(c)?;
387 Record::PolyBezier16 { bounds, points }
388 }
389 RT_POLYBEZIER_TO16 => {
390 let (bounds, points) = drawing::parse_points16(c)?;
391 Record::PolyBezierTo16 { bounds, points }
392 }
393 RT_POLYLINE_TO16 => {
394 let (bounds, points) = drawing::parse_points16(c)?;
395 Record::PolylineTo16 { bounds, points }
396 }
397
398 RT_BEGIN_PATH => Record::BeginPath,
400 RT_END_PATH => Record::EndPath,
401 RT_CLOSE_FIGURE => Record::CloseFigure,
402 RT_FILL_PATH => Record::FillPath(path::parse_path_bounds(c)?),
403 RT_STROKE_PATH => Record::StrokePath(path::parse_path_bounds(c)?),
404 RT_STROKE_AND_FILL_PATH => Record::StrokeAndFillPath(path::parse_path_bounds(c)?),
405
406 RT_EXT_TEXT_OUT_W => {
408 let payload = c.full_buf();
409 Record::ExtTextOutW(text::parse(payload)?)
410 }
411
412 RT_STRETCH_DI_BITS => {
414 let payload = c.full_buf();
415 Record::StretchDIBits(bitmap::parse(payload)?)
416 }
417
418 _ => Record::Unknown {
419 record_type,
420 payload: c.take(payload_len)?.to_vec(),
421 },
422 };
423 Ok(rec)
424}
425
426#[derive(Debug, Clone, Copy)]
428pub struct RecordHeader {
429 pub record_type: u32,
430 pub size: u32,
431}
432
433pub struct Cursor<'a> {
435 buf: &'a [u8],
436 pos: usize,
437}
438
439impl<'a> Cursor<'a> {
440 #[inline]
441 pub fn new(buf: &'a [u8]) -> Self {
442 Self { buf, pos: 0 }
443 }
444 #[inline]
445 pub fn position(&self) -> usize {
446 self.pos
447 }
448 #[inline]
449 pub fn remaining(&self) -> usize {
450 self.buf.len() - self.pos
451 }
452 #[inline]
453 pub fn is_empty(&self) -> bool {
454 self.pos >= self.buf.len()
455 }
456
457 pub fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
458 if self.remaining() < n {
459 return Err(Error::UnexpectedEof {
460 at: self.pos,
461 need: n,
462 });
463 }
464 let s = &self.buf[self.pos..self.pos + n];
465 self.pos += n;
466 Ok(s)
467 }
468
469 pub fn peek(&self, n: usize) -> Result<&'a [u8], Error> {
470 if self.remaining() < n {
471 return Err(Error::UnexpectedEof {
472 at: self.pos,
473 need: n,
474 });
475 }
476 Ok(&self.buf[self.pos..self.pos + n])
477 }
478
479 pub fn u32(&mut self) -> Result<u32, Error> {
480 let b = self.take(4)?;
481 Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
482 }
483 pub fn i32(&mut self) -> Result<i32, Error> {
484 Ok(self.u32()? as i32)
485 }
486 pub fn u16(&mut self) -> Result<u16, Error> {
487 let b = self.take(2)?;
488 Ok(u16::from_le_bytes([b[0], b[1]]))
489 }
490
491 #[must_use]
493 pub fn full_buf(&self) -> &'a [u8] {
494 self.buf
495 }
496
497 pub fn peek_record_header(&self) -> Result<RecordHeader, Error> {
498 let b = self.peek(8)?;
499 let record_type = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
500 let size = u32::from_le_bytes([b[4], b[5], b[6], b[7]]);
501 if size < 8 {
502 return Err(Error::RecordTooSmall {
503 offset: self.pos,
504 size,
505 });
506 }
507 if size % 4 != 0 {
508 return Err(Error::MisalignedRecord {
509 offset: self.pos,
510 size,
511 });
512 }
513 Ok(RecordHeader { record_type, size })
514 }
515}