skrifa/outline/glyf/hint/engine/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! TrueType bytecode interpreter.

mod arith;
mod control_flow;
mod cvt;
mod data;
mod definition;
mod delta;
mod dispatch;
mod graphics;
mod logical;
mod misc;
mod outline;
mod round;
mod stack;
mod storage;

use read_fonts::{
    tables::glyf::bytecode::Instruction,
    types::{F26Dot6, F2Dot14, Point},
};

use super::{
    super::Outlines,
    cvt::Cvt,
    definition::DefinitionState,
    error::{HintError, HintErrorKind},
    graphics::{GraphicsState, RetainedGraphicsState},
    math,
    program::ProgramState,
    storage::Storage,
    value_stack::ValueStack,
    zone::Zone,
};

pub type OpResult = Result<(), HintErrorKind>;

/// TrueType bytecode interpreter.
pub struct Engine<'a> {
    program: ProgramState<'a>,
    graphics: GraphicsState<'a>,
    definitions: DefinitionState<'a>,
    cvt: Cvt<'a>,
    storage: Storage<'a>,
    value_stack: ValueStack<'a>,
    loop_budget: LoopBudget,
    axis_count: u16,
    coords: &'a [F2Dot14],
}

impl<'a> Engine<'a> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        outlines: &Outlines,
        program: ProgramState<'a>,
        graphics: RetainedGraphicsState,
        definitions: DefinitionState<'a>,
        cvt: impl Into<Cvt<'a>>,
        storage: impl Into<Storage<'a>>,
        value_stack: ValueStack<'a>,
        twilight: Zone<'a>,
        glyph: Zone<'a>,
        axis_count: u16,
        coords: &'a [F2Dot14],
        is_composite: bool,
    ) -> Self {
        let point_count = if glyph.points.is_empty() {
            None
        } else {
            Some(glyph.points.len())
        };
        let graphics = GraphicsState {
            retained: graphics,
            zones: [twilight, glyph],
            is_composite,
            ..Default::default()
        };
        Self {
            program,
            graphics,
            definitions,
            cvt: cvt.into(),
            storage: storage.into(),
            value_stack,
            loop_budget: LoopBudget::new(outlines, point_count),
            axis_count,
            coords,
        }
    }

    pub fn backward_compatibility(&self) -> bool {
        self.graphics.backward_compatibility
    }

    pub fn retained_graphics_state(&self) -> &RetainedGraphicsState {
        &self.graphics.retained
    }
}

/// Tracks budgets for loops to limit execution time.
struct LoopBudget {
    /// Maximum number of times we can do backward jumps or
    /// loop calls.
    limit: usize,
    /// Current number of backward jumps executed.
    backward_jumps: usize,
    /// Current number of loop call iterations executed.
    loop_calls: usize,
}

impl LoopBudget {
    fn new(outlines: &Outlines, point_count: Option<usize>) -> Self {
        let cvt_len = outlines.cvt_len as usize;
        // Compute limits for loop calls and backward jumps.
        // See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/truetype/ttinterp.c#L6955>
        let limit = if let Some(point_count) = point_count {
            (point_count * 10).max(50) + (cvt_len / 10).max(50)
        } else {
            300 + 22 * cvt_len
        };
        // FreeType has two variables for neg_jump_counter_max and
        // loopcall_counter_max but sets them to the same value so
        // we'll just use a single limit.
        Self {
            limit,
            backward_jumps: 0,
            loop_calls: 0,
        }
    }

    fn reset(&mut self) {
        self.backward_jumps = 0;
        self.loop_calls = 0;
    }

    fn doing_backward_jump(&mut self) -> Result<(), HintErrorKind> {
        self.backward_jumps += 1;
        if self.backward_jumps > self.limit {
            Err(HintErrorKind::ExceededExecutionBudget)
        } else {
            Ok(())
        }
    }

    fn doing_loop_call(&mut self, count: usize) -> Result<(), HintErrorKind> {
        self.loop_calls += count;
        if self.loop_calls > self.limit {
            Err(HintErrorKind::ExceededExecutionBudget)
        } else {
            Ok(())
        }
    }
}

#[cfg(test)]
use mock::MockEngine;

#[cfg(test)]
mod mock {
    use super::{
        super::{
            cow_slice::CowSlice,
            definition::{Definition, DefinitionMap, DefinitionState},
            program::{Program, ProgramState},
            zone::Zone,
            Point, PointFlags,
        },
        Engine, F26Dot6, GraphicsState, LoopBudget, ValueStack,
    };

    /// Mock engine for testing.
    pub(super) struct MockEngine {
        cvt_storage: Vec<i32>,
        value_stack: Vec<i32>,
        definitions: Vec<Definition>,
        unscaled: Vec<Point<i32>>,
        points: Vec<Point<F26Dot6>>,
        point_flags: Vec<PointFlags>,
        contours: Vec<u16>,
        twilight: Vec<Point<F26Dot6>>,
        twilight_flags: Vec<PointFlags>,
    }

    impl MockEngine {
        pub fn new() -> Self {
            Self {
                cvt_storage: vec![0; 32],
                value_stack: vec![0; 32],
                definitions: vec![Default::default(); 8],
                unscaled: vec![Default::default(); 32],
                points: vec![Default::default(); 64],
                point_flags: vec![Default::default(); 32],
                contours: vec![31],
                twilight: vec![Default::default(); 32],
                twilight_flags: vec![Default::default(); 32],
            }
        }

        pub fn engine(&mut self) -> Engine {
            let font_code = &[];
            let cv_code = &[];
            let glyph_code = &[];
            let (cvt, storage) = self.cvt_storage.split_at_mut(16);
            let (function_defs, instruction_defs) = self.definitions.split_at_mut(5);
            let definition = DefinitionState::new(
                DefinitionMap::Mut(function_defs),
                DefinitionMap::Mut(instruction_defs),
            );
            for (i, point) in self.unscaled.iter_mut().enumerate() {
                let i = i as i32;
                point.x = 57 + i * 2;
                point.y = -point.x * 3;
            }
            let (points, original) = self.points.split_at_mut(32);
            let glyph_zone = Zone::new(
                &self.unscaled,
                original,
                points,
                &mut self.point_flags,
                &self.contours,
            );
            let (points, original) = self.twilight.split_at_mut(16);
            let twilight_zone = Zone::new(&[], original, points, &mut self.twilight_flags, &[]);
            let mut graphics_state = GraphicsState {
                zones: [twilight_zone, glyph_zone],
                ..Default::default()
            };
            graphics_state.update_projection_state();
            Engine {
                graphics: graphics_state,
                cvt: CowSlice::new_mut(cvt).into(),
                storage: CowSlice::new_mut(storage).into(),
                value_stack: ValueStack::new(&mut self.value_stack, false),
                program: ProgramState::new(font_code, cv_code, glyph_code, Program::Font),
                loop_budget: LoopBudget {
                    limit: 10,
                    backward_jumps: 0,
                    loop_calls: 0,
                },
                definitions: definition,
                axis_count: 0,
                coords: &[],
            }
        }
    }

    impl Default for MockEngine {
        fn default() -> Self {
            Self::new()
        }
    }

    impl<'a> Engine<'a> {
        /// Helper to push values to the stack, invoke a callback and check
        /// the expected result.    
        pub(super) fn test_exec(
            &mut self,
            push: &[i32],
            expected_result: impl Into<i32>,
            mut f: impl FnMut(&mut Engine),
        ) {
            for &val in push {
                self.value_stack.push(val).unwrap();
            }
            f(self);
            assert_eq!(self.value_stack.pop().ok(), Some(expected_result.into()));
        }
    }
}