Skip to main content

rhwp/emf/parser/
mod.rs

1//! EMF 파서 루트 — 스트림 reader + 레코드 디스패처.
2
3pub mod constants;
4pub mod objects;
5pub mod records;
6
7pub use objects::header::Header;
8
9use super::Error;
10use records::Record;
11
12// RecordType 값 상수 — 디스패처 분기용. RecordType enum과 일치.
13const 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;
33/// [#6577] 이 파일군의 비-스톡 펜은 전부 여기서 온다(`EMR_CREATEPEN` 은 0건).
34const RT_EXT_CREATE_PEN: u32 = 0x0000005F;
35const RT_CREATE_DIB_PATTERN_BRUSH: u32 = 0x0000005E;
36/// [#6577] 156627451 내장 EMF 는 클립을 112건 쓴다 — 종전에는 클립이 아예 없었다.
37const 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;
41// 드로잉 (단계 12)
42const 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;
51// MS-EMF 2.1.1: EMR_POLYGON16=0x56, EMR_POLYLINE16=0x57.
52const RT_POLYGON16: u32 = 0x00000056;
53const RT_POLYLINE16: u32 = 0x00000057;
54/// [#6577] 패스 기반 EMF 의 주 구성 레코드 — 종전에는 `Unknown` 으로 버려졌다.
55const RT_POLYBEZIER_TO16: u32 = 0x00000058;
56const RT_POLYLINE_TO16: u32 = 0x00000059;
57const RT_POLY_POLYGON16: u32 = 0x0000005B;
58// 패스 (단계 12)
59const 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;
65// 텍스트/비트맵 (단계 13)
66const RT_EXT_TEXT_OUT_W: u32 = 0x00000054;
67const RT_STRETCH_DI_BITS: u32 = 0x00000051;
68// 코멘트 — EMF+ 이중 스트림 판별용 (단계 밖, #5637)
69const RT_COMMENT: u32 = 0x00000046;
70// MS-EMF 정의 레코드 타입 최댓값 (EMR_CREATECOLORSPACEW = 0x7A).
71const RT_MAX: u32 = 0x0000007A;
72// [#5637] 재동기 시도 상한 — 적대적 입력에서의 반복 폭주 방지.
73const MAX_RESYNCS: usize = 8;
74
75/// EMF 바이트를 레코드 시퀀스로 파싱.
76///
77/// [#5637] EMF+ 이중 스트림(GDI+ 레코드를 `EMR_COMMENT`에 내장) 중 일부 생산자는
78/// 코멘트 레코드의 Size 필드가 실데이터보다 작게 적혀 있어, 코멘트 뒤에서 레코드
79/// 프레이밍이 임의 바이트 위에 얹힌다. 그런 스트림도 뒤쪽에는 온전한 GDI 폴백
80/// 레코드(EMR_STRETCHDIBITS 등)가 이어지므로, **EMF+ 코멘트를 본 스트림에 한해**
81/// 구조 파단 지점부터 다음 그럴듯한 레코드 연쇄를 훑어 재동기한다.
82pub fn parse(bytes: &[u8]) -> Result<Vec<Record>, Error> {
83    let mut cursor = Cursor::new(bytes);
84    let mut out = Vec::new();
85
86    // 첫 레코드: EMR_HEADER (필수).
87    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    // 나머지 레코드 디스패처.
100    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                // EMF+ 이중 스트림이면 재동기 시도.
113                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                // 재동기가 불가능해도 그릴 내용이 있는 EMF+ 프리픽스는 살린다 —
122                // 손상 지점 전까지의 온전한 레코드 렌더가 빈 placeholder 보다 낫다.
123                // EMF+ 시그니처 없는 일반 EMF는 종전처럼 형식 오류를 반환한다.
124                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
135/// 손상 스트림 프리픽스 구제 판단용 — Player 가 실제로 그리는 레코드인지.
136fn 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
161/// 커서 위치에서 레코드 1개를 읽어 디스패치한다. EMF+ 시그니처 코멘트를 만나면
162/// `emfplus_comment_seen`을 세운다.
163fn 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    // type + size 스킵.
177    let _ = cursor.take(8)?;
178
179    // 페이로드 전용 sub-cursor. 레코드 경계를 넘지 않도록 분리.
180    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
189/// [#5637] `from`부터 4바이트 스텝으로 "그럴듯한 레코드 연쇄"의 시작을 찾는다.
190///
191/// 후보 조건: 알려진 타입 범위(1..=0x7A) + Size ≥ 8·4의 배수·버퍼 안. 임의 바이트
192/// 위양성을 줄이기 위해 후보 뒤로도 같은 조건의 레코드가 이어지는지(또는 EOF/버퍼
193/// 끝에 닿는지) 2단계 연쇄를 확인한다.
194fn 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            // 큰 비트맵 레코드는 뒤가 다시 파단이어도 내부 필드 자기-일관성으로
199            // 단독 수용한다 — 이중 스트림 파일은 폴백 비트맵 뒤가 또 깨진 경우가 있다.
200            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
209/// EMR_STRETCHDIBITS 후보의 내부 오프셋/크기 필드가 레코드 안에서 맞물리는지 검사.
210/// 42KB급 레코드에서 이 조합이 임의 바이트로 성립할 확률은 무시할 수 있다.
211fn 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    // 고정부(레코드 시작 기준 80바이트) + BITMAPINFOHEADER 최소 40바이트
217    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        // BITMAPINFOHEADER.biSize == 40
231        && f(off_bmi) == 40
232}
233
234/// `pos`의 8바이트가 그럴듯한 레코드 헤더인지 검사.
235fn 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
251/// 후보 레코드 뒤로 `depth`개의 레코드가 이어서 그럴듯한지 확인한다.
252/// EOF 레코드나 버퍼 끝 도달은 유효한 종결로 본다.
253fn 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        // 객체
274        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        // 상태 — DC 스택
311        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        // 좌표계
322        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        // 색상/모드
329        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        // 드로잉
337        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        // 패스
399        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        // 텍스트
407        RT_EXT_TEXT_OUT_W => {
408            let payload = c.full_buf();
409            Record::ExtTextOutW(text::parse(payload)?)
410        }
411
412        // 비트맵
413        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/// 레코드 공통 헤더(8바이트).
427#[derive(Debug, Clone, Copy)]
428pub struct RecordHeader {
429    pub record_type: u32,
430    pub size: u32,
431}
432
433/// 리틀엔디언 스트림 리더. EMF 전역에서 재사용.
434pub 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    /// 커서의 원본 버퍼(페이로드 전체).
492    #[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}