1/*
2 * Copyright © 2007,2008,2009,2010 Red Hat, Inc.
3 * Copyright © 2012,2018 Google, Inc.
4 *
5 * This is part of HarfBuzz, a text shaping library.
6 *
7 * Permission is hereby granted, without written agreement and without
8 * license or royalty fees, to use, copy, modify, and distribute this
9 * software and its documentation for any purpose, provided that the
10 * above copyright notice and the following two paragraphs appear in
11 * all copies of this software.
12 *
13 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17 * DAMAGE.
18 *
19 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
22 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24 *
25 * Red Hat Author(s): Behdad Esfahbod
26 * Google Author(s): Behdad Esfahbod
27 */
28
29#ifndef HB_SANITIZE_HH
30#define HB_SANITIZE_HH
31
32#include "hb.hh"
33#include "hb-blob.hh"
34#include "hb-dispatch.hh"
35
36
37/*
38 * Sanitize
39 *
40 *
41 * === Introduction ===
42 *
43 * The sanitize machinery is at the core of our zero-cost font loading. We
44 * mmap() font file into memory and create a blob out of it. Font subtables
45 * are returned as a readonly sub-blob of the main font blob. These table
46 * blobs are then sanitized before use, to ensure invalid memory access does
47 * not happen. The toplevel sanitize API use is like, eg. to load the 'head'
48 * table:
49 *
50 * hb_blob_t *head_blob = hb_sanitize_context_t ().reference_table<OT::head> (face);
51 *
52 * The blob then can be converted to a head table struct with:
53 *
54 * const head *head_table = head_blob->as<head> ();
55 *
56 * What the reference_table does is, to call hb_face_reference_table() to load
57 * the table blob, sanitize it and return either the sanitized blob, or empty
58 * blob if sanitization failed. The blob->as() function returns the null
59 * object of its template type argument if the blob is empty. Otherwise, it
60 * just casts the blob contents to the desired type.
61 *
62 * Sanitizing a blob of data with a type T works as follows (with minor
63 * simplification):
64 *
65 * - Cast blob content to T*, call sanitize() method of it,
66 * - If sanitize succeeded, return blob.
67 * - Otherwise, if blob is not writable, try making it writable,
68 * or copy if cannot be made writable in-place,
69 * - Call sanitize() again. Return blob if sanitize succeeded.
70 * - Return empty blob otherwise.
71 *
72 *
73 * === The sanitize() contract ===
74 *
75 * The sanitize() method of each object type shall return true if it's safe to
76 * call other methods of the object, and false otherwise.
77 *
78 * Note that what sanitize() checks for might align with what the specification
79 * describes as valid table data, but does not have to be. In particular, we
80 * do NOT want to be pedantic and concern ourselves with validity checks that
81 * are irrelevant to our use of the table. On the contrary, we want to be
82 * lenient with error handling and accept invalid data to the extent that it
83 * does not impose extra burden on us.
84 *
85 * Based on the sanitize contract, one can see that what we check for depends
86 * on how we use the data in other table methods. Ie. if other table methods
87 * assume that offsets do NOT point out of the table data block, then that's
88 * something sanitize() must check for (GSUB/GPOS/GDEF/etc work this way). On
89 * the other hand, if other methods do such checks themselves, then sanitize()
90 * does not have to bother with them (glyf/local work this way). The choice
91 * depends on the table structure and sanitize() performance. For example, to
92 * check glyf/loca offsets in sanitize() would cost O(num-glyphs). We try hard
93 * to avoid such costs during font loading. By postponing such checks to the
94 * actual glyph loading, we reduce the sanitize cost to O(1) and total runtime
95 * cost to O(used-glyphs). As such, this is preferred.
96 *
97 * The same argument can be made re GSUB/GPOS/GDEF, but there, the table
98 * structure is so complicated that by checking all offsets at sanitize() time,
99 * we make the code much simpler in other methods, as offsets and referenced
100 * objects do not need to be validated at each use site.
101 */
102
103/* This limits sanitizing time on really broken fonts. */
104#ifndef HB_SANITIZE_MAX_EDITS
105#define HB_SANITIZE_MAX_EDITS 32
106#endif
107#ifndef HB_SANITIZE_MAX_OPS_FACTOR
108#define HB_SANITIZE_MAX_OPS_FACTOR 8
109#endif
110#ifndef HB_SANITIZE_MAX_OPS_MIN
111#define HB_SANITIZE_MAX_OPS_MIN 16384
112#endif
113#ifndef HB_SANITIZE_MAX_OPS_MAX
114#define HB_SANITIZE_MAX_OPS_MAX 0x3FFFFFFF
115#endif
116
117struct hb_sanitize_context_t :
118 hb_dispatch_context_t<hb_sanitize_context_t, bool, HB_DEBUG_SANITIZE>
119{
120 hb_sanitize_context_t () :
121 debug_depth (0),
122 start (nullptr), end (nullptr),
123 max_ops (0),
124 writable (false), edit_count (0),
125 blob (nullptr),
126 num_glyphs (65536),
127 num_glyphs_set (false) {}
128
129 const char *get_name () { return "SANITIZE"; }
130 template <typename T, typename F>
131 bool may_dispatch (const T *obj HB_UNUSED, const F *format)
132 { return format->sanitize (this); }
133 static return_t default_return_value () { return true; }
134 static return_t no_dispatch_return_value () { return false; }
135 bool stop_sublookup_iteration (const return_t r) const { return !r; }
136
137 private:
138 template <typename T, typename ...Ts> auto
139 _dispatch (const T &obj, hb_priority<1>, Ts&&... ds) HB_AUTO_RETURN
140 ( obj.sanitize (this, hb_forward<Ts> (ds)...) )
141 template <typename T, typename ...Ts> auto
142 _dispatch (const T &obj, hb_priority<0>, Ts&&... ds) HB_AUTO_RETURN
143 ( obj.dispatch (this, hb_forward<Ts> (ds)...) )
144 public:
145 template <typename T, typename ...Ts> auto
146 dispatch (const T &obj, Ts&&... ds) HB_AUTO_RETURN
147 ( _dispatch (obj, hb_prioritize, hb_forward<Ts> (ds)...) )
148
149
150 void init (hb_blob_t *b)
151 {
152 this->blob = hb_blob_reference (b);
153 this->writable = false;
154 }
155
156 void set_num_glyphs (unsigned int num_glyphs_)
157 {
158 num_glyphs = num_glyphs_;
159 num_glyphs_set = true;
160 }
161 unsigned int get_num_glyphs () { return num_glyphs; }
162
163 void set_max_ops (int max_ops_) { max_ops = max_ops_; }
164
165 template <typename T>
166 void set_object (const T *obj)
167 {
168 reset_object ();
169
170 if (!obj) return;
171
172 const char *obj_start = (const char *) obj;
173 if (unlikely (obj_start < this->start || this->end <= obj_start))
174 this->start = this->end = nullptr;
175 else
176 {
177 this->start = obj_start;
178 this->end = obj_start + hb_min (size_t (this->end - obj_start), obj->get_size ());
179 }
180 }
181
182 void reset_object ()
183 {
184 this->start = this->blob->data;
185 this->end = this->start + this->blob->length;
186 assert (this->start <= this->end); /* Must not overflow. */
187 }
188
189 void start_processing ()
190 {
191 reset_object ();
192 this->max_ops = hb_max ((unsigned int) (this->end - this->start) * HB_SANITIZE_MAX_OPS_FACTOR,
193 (unsigned) HB_SANITIZE_MAX_OPS_MIN);
194 this->edit_count = 0;
195 this->debug_depth = 0;
196
197 DEBUG_MSG_LEVEL (SANITIZE, start, 0, +1,
198 "start [%p..%p] (%lu bytes)",
199 this->start, this->end,
200 (unsigned long) (this->end - this->start));
201 }
202
203 void end_processing ()
204 {
205 DEBUG_MSG_LEVEL (SANITIZE, this->start, 0, -1,
206 "end [%p..%p] %u edit requests",
207 this->start, this->end, this->edit_count);
208
209 hb_blob_destroy (this->blob);
210 this->blob = nullptr;
211 this->start = this->end = nullptr;
212 }
213
214 unsigned get_edit_count () { return edit_count; }
215
216 bool check_range (const void *base,
217 unsigned int len) const
218 {
219 const char *p = (const char *) base;
220 bool ok = !len ||
221 (this->start <= p &&
222 p <= this->end &&
223 (unsigned int) (this->end - p) >= len &&
224 this->max_ops-- > 0);
225
226 DEBUG_MSG_LEVEL (SANITIZE, p, this->debug_depth+1, 0,
227 "check_range [%p..%p]"
228 " (%d bytes) in [%p..%p] -> %s",
229 p, p + len, len,
230 this->start, this->end,
231 ok ? "OK" : "OUT-OF-RANGE");
232
233 return likely (ok);
234 }
235
236 template <typename T>
237 bool check_range (const T *base,
238 unsigned int a,
239 unsigned int b) const
240 {
241 return !hb_unsigned_mul_overflows (a, b) &&
242 this->check_range (base, a * b);
243 }
244
245 template <typename T>
246 bool check_range (const T *base,
247 unsigned int a,
248 unsigned int b,
249 unsigned int c) const
250 {
251 return !hb_unsigned_mul_overflows (a, b) &&
252 this->check_range (base, a * b, c);
253 }
254
255 template <typename T>
256 bool check_array (const T *base, unsigned int len) const
257 {
258 return this->check_range (base, len, hb_static_size (T));
259 }
260
261 template <typename T>
262 bool check_array (const T *base,
263 unsigned int a,
264 unsigned int b) const
265 {
266 return this->check_range (base, a, b, hb_static_size (T));
267 }
268
269 template <typename Type>
270 bool check_struct (const Type *obj) const
271 { return likely (this->check_range (obj, obj->min_size)); }
272
273 bool may_edit (const void *base, unsigned int len)
274 {
275 if (this->edit_count >= HB_SANITIZE_MAX_EDITS)
276 return false;
277
278 const char *p = (const char *) base;
279 this->edit_count++;
280
281 DEBUG_MSG_LEVEL (SANITIZE, p, this->debug_depth+1, 0,
282 "may_edit(%u) [%p..%p] (%d bytes) in [%p..%p] -> %s",
283 this->edit_count,
284 p, p + len, len,
285 this->start, this->end,
286 this->writable ? "GRANTED" : "DENIED");
287
288 return this->writable;
289 }
290
291 template <typename Type, typename ValueType>
292 bool try_set (const Type *obj, const ValueType &v)
293 {
294 if (this->may_edit (obj, hb_static_size (Type)))
295 {
296 * const_cast<Type *> (obj) = v;
297 return true;
298 }
299 return false;
300 }
301
302 template <typename Type>
303 hb_blob_t *sanitize_blob (hb_blob_t *blob)
304 {
305 bool sane;
306
307 init (blob);
308
309 retry:
310 DEBUG_MSG_FUNC (SANITIZE, start, "start");
311
312 start_processing ();
313
314 if (unlikely (!start))
315 {
316 end_processing ();
317 return blob;
318 }
319
320 Type *t = reinterpret_cast<Type *> (const_cast<char *> (start));
321
322 sane = t->sanitize (this);
323 if (sane)
324 {
325 if (edit_count)
326 {
327 DEBUG_MSG_FUNC (SANITIZE, start, "passed first round with %d edits; going for second round", edit_count);
328
329 /* sanitize again to ensure no toe-stepping */
330 edit_count = 0;
331 sane = t->sanitize (this);
332 if (edit_count) {
333 DEBUG_MSG_FUNC (SANITIZE, start, "requested %d edits in second round; FAILLING", edit_count);
334 sane = false;
335 }
336 }
337 }
338 else
339 {
340 if (edit_count && !writable) {
341 start = hb_blob_get_data_writable (blob, nullptr);
342 end = start + blob->length;
343
344 if (start)
345 {
346 writable = true;
347 /* ok, we made it writable by relocating. try again */
348 DEBUG_MSG_FUNC (SANITIZE, start, "retry");
349 goto retry;
350 }
351 }
352 }
353
354 end_processing ();
355
356 DEBUG_MSG_FUNC (SANITIZE, start, sane ? "PASSED" : "FAILED");
357 if (sane)
358 {
359 hb_blob_make_immutable (blob);
360 return blob;
361 }
362 else
363 {
364 hb_blob_destroy (blob);
365 return hb_blob_get_empty ();
366 }
367 }
368
369 template <typename Type>
370 hb_blob_t *reference_table (const hb_face_t *face, hb_tag_t tableTag = Type::tableTag)
371 {
372 if (!num_glyphs_set)
373 set_num_glyphs (hb_face_get_glyph_count (face));
374 return sanitize_blob<Type> (hb_face_reference_table (face, tableTag));
375 }
376
377 mutable unsigned int debug_depth;
378 const char *start, *end;
379 mutable int max_ops;
380 private:
381 bool writable;
382 unsigned int edit_count;
383 hb_blob_t *blob;
384 unsigned int num_glyphs;
385 bool num_glyphs_set;
386};
387
388struct hb_sanitize_with_object_t
389{
390 template <typename T>
391 hb_sanitize_with_object_t (hb_sanitize_context_t *c, const T& obj) : c (c)
392 { c->set_object (obj); }
393 ~hb_sanitize_with_object_t ()
394 { c->reset_object (); }
395
396 private:
397 hb_sanitize_context_t *c;
398};
399
400
401#endif /* HB_SANITIZE_HH */
402