1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This is the implementation of decompression of the proposed WOFF Ultra
6 // Condensed file format.
12 #include "third_party/brotli/dec/decode.h"
14 #include "opentype-sanitiser.h"
15 #include "ots-memory-stream.h"
19 #define TABLE_NAME "WOFF2"
24 const uint8_t kGlyfOnCurve
= 1 << 0;
25 const uint8_t kGlyfXShort
= 1 << 1;
26 const uint8_t kGlyfYShort
= 1 << 2;
27 const uint8_t kGlyfRepeat
= 1 << 3;
28 const uint8_t kGlyfThisXIsSame
= 1 << 4;
29 const uint8_t kGlyfThisYIsSame
= 1 << 5;
31 // composite glyph flags
32 const int FLAG_ARG_1_AND_2_ARE_WORDS
= 1 << 0;
33 const int FLAG_WE_HAVE_A_SCALE
= 1 << 3;
34 const int FLAG_MORE_COMPONENTS
= 1 << 5;
35 const int FLAG_WE_HAVE_AN_X_AND_Y_SCALE
= 1 << 6;
36 const int FLAG_WE_HAVE_A_TWO_BY_TWO
= 1 << 7;
37 const int FLAG_WE_HAVE_INSTRUCTIONS
= 1 << 8;
39 const size_t kSfntHeaderSize
= 12;
40 const size_t kSfntEntrySize
= 16;
41 const size_t kCheckSumAdjustmentOffset
= 8;
43 const size_t kEndPtsOfContoursOffset
= 10;
44 const size_t kCompositeGlyphBegin
= 10;
46 const unsigned int kWoff2FlagsTransform
= 1 << 5;
48 const uint32_t kKnownTags
[] = {
49 OTS_TAG('c','m','a','p'), // 0
50 OTS_TAG('h','e','a','d'), // 1
51 OTS_TAG('h','h','e','a'), // 2
52 OTS_TAG('h','m','t','x'), // 3
53 OTS_TAG('m','a','x','p'), // 4
54 OTS_TAG('n','a','m','e'), // 5
55 OTS_TAG('O','S','/','2'), // 6
56 OTS_TAG('p','o','s','t'), // 7
57 OTS_TAG('c','v','t',' '), // 8
58 OTS_TAG('f','p','g','m'), // 9
59 OTS_TAG('g','l','y','f'), // 10
60 OTS_TAG('l','o','c','a'), // 11
61 OTS_TAG('p','r','e','p'), // 12
62 OTS_TAG('C','F','F',' '), // 13
63 OTS_TAG('V','O','R','G'), // 14
64 OTS_TAG('E','B','D','T'), // 15
65 OTS_TAG('E','B','L','C'), // 16
66 OTS_TAG('g','a','s','p'), // 17
67 OTS_TAG('h','d','m','x'), // 18
68 OTS_TAG('k','e','r','n'), // 19
69 OTS_TAG('L','T','S','H'), // 20
70 OTS_TAG('P','C','L','T'), // 21
71 OTS_TAG('V','D','M','X'), // 22
72 OTS_TAG('v','h','e','a'), // 23
73 OTS_TAG('v','m','t','x'), // 24
74 OTS_TAG('B','A','S','E'), // 25
75 OTS_TAG('G','D','E','F'), // 26
76 OTS_TAG('G','P','O','S'), // 27
77 OTS_TAG('G','S','U','B'), // 28
78 OTS_TAG('E','B','S','C'), // 29
79 OTS_TAG('J','S','T','F'), // 30
80 OTS_TAG('M','A','T','H'), // 31
81 OTS_TAG('C','B','D','T'), // 32
82 OTS_TAG('C','B','L','C'), // 33
83 OTS_TAG('C','O','L','R'), // 34
84 OTS_TAG('C','P','A','L'), // 35
85 OTS_TAG('S','V','G',' '), // 36
86 OTS_TAG('s','b','i','x'), // 37
87 OTS_TAG('a','c','n','t'), // 38
88 OTS_TAG('a','v','a','r'), // 39
89 OTS_TAG('b','d','a','t'), // 40
90 OTS_TAG('b','l','o','c'), // 41
91 OTS_TAG('b','s','l','n'), // 42
92 OTS_TAG('c','v','a','r'), // 43
93 OTS_TAG('f','d','s','c'), // 44
94 OTS_TAG('f','e','a','t'), // 45
95 OTS_TAG('f','m','t','x'), // 46
96 OTS_TAG('f','v','a','r'), // 47
97 OTS_TAG('g','v','a','r'), // 48
98 OTS_TAG('h','s','t','y'), // 49
99 OTS_TAG('j','u','s','t'), // 50
100 OTS_TAG('l','c','a','r'), // 51
101 OTS_TAG('m','o','r','t'), // 52
102 OTS_TAG('m','o','r','x'), // 53
103 OTS_TAG('o','p','b','d'), // 54
104 OTS_TAG('p','r','o','p'), // 55
105 OTS_TAG('t','r','a','k'), // 56
106 OTS_TAG('Z','a','p','f'), // 57
107 OTS_TAG('S','i','l','f'), // 58
108 OTS_TAG('G','l','a','t'), // 59
109 OTS_TAG('G','l','o','c'), // 60
110 OTS_TAG('F','e','a','t'), // 61
111 OTS_TAG('S','i','l','l'), // 62
124 uint32_t transform_length
;
136 bool operator<(const Table
& other
) const {
137 return tag
< other
.tag
;
141 // Based on section 6.1.1 of MicroType Express draft spec
142 bool Read255UShort(ots::Buffer
* buf
, uint16_t* value
) {
143 static const uint8_t kWordCode
= 253;
144 static const uint8_t kOneMoreByteCode2
= 254;
145 static const uint8_t kOneMoreByteCode1
= 255;
146 static const uint8_t kLowestUCode
= 253;
148 if (!buf
->ReadU8(&code
)) {
149 return OTS_FAILURE();
151 if (code
== kWordCode
) {
153 if (!buf
->ReadU16(&result
)) {
154 return OTS_FAILURE();
158 } else if (code
== kOneMoreByteCode1
) {
160 if (!buf
->ReadU8(&result
)) {
161 return OTS_FAILURE();
163 *value
= result
+ kLowestUCode
;
165 } else if (code
== kOneMoreByteCode2
) {
167 if (!buf
->ReadU8(&result
)) {
168 return OTS_FAILURE();
170 *value
= result
+ kLowestUCode
* 2;
178 bool ReadBase128(ots::Buffer
* buf
, uint32_t* value
) {
180 for (size_t i
= 0; i
< 5; ++i
) {
182 if (!buf
->ReadU8(&code
)) {
183 return OTS_FAILURE();
185 // If any of the top seven bits are set then we're about to overflow.
186 if (result
& 0xfe000000U
) {
187 return OTS_FAILURE();
189 result
= (result
<< 7) | (code
& 0x7f);
190 if ((code
& 0x80) == 0) {
195 // Make sure not to exceed the size bound
196 return OTS_FAILURE();
199 // Caller must ensure that buffer overrun won't happen.
200 // TODO(ksakamaoto): Consider creating 'writer' version of the Buffer class
201 // and use it across the code.
202 size_t StoreU32(uint8_t* dst
, size_t offset
, uint32_t x
) {
203 dst
[offset
] = x
>> 24;
204 dst
[offset
+ 1] = (x
>> 16) & 0xff;
205 dst
[offset
+ 2] = (x
>> 8) & 0xff;
206 dst
[offset
+ 3] = x
& 0xff;
210 size_t StoreU16(uint8_t* dst
, size_t offset
, uint16_t x
) {
211 dst
[offset
] = x
>> 8;
212 dst
[offset
+ 1] = x
& 0xff;
216 int WithSign(int flag
, int baseval
) {
217 assert(0 <= baseval
&& baseval
< 65536);
218 return (flag
& 1) ? baseval
: -baseval
;
221 bool TripletDecode(const uint8_t* flags_in
, const uint8_t* in
, size_t in_size
,
222 unsigned int n_points
, std::vector
<Point
>* result
,
223 size_t* in_bytes_consumed
) {
227 // Early return if |in| buffer is too small. Each point consumes 1-4 bytes.
228 if (n_points
> in_size
) {
229 return OTS_FAILURE();
231 unsigned int triplet_index
= 0;
233 for (unsigned int i
= 0; i
< n_points
; ++i
) {
234 uint8_t flag
= flags_in
[i
];
235 bool on_curve
= !(flag
>> 7);
237 unsigned int n_data_bytes
;
240 } else if (flag
< 120) {
242 } else if (flag
< 124) {
247 if (triplet_index
+ n_data_bytes
> in_size
||
248 triplet_index
+ n_data_bytes
< triplet_index
) {
249 return OTS_FAILURE();
254 dy
= WithSign(flag
, ((flag
& 14) << 7) + in
[triplet_index
]);
255 } else if (flag
< 20) {
256 dx
= WithSign(flag
, (((flag
- 10) & 14) << 7) + in
[triplet_index
]);
258 } else if (flag
< 84) {
260 int b1
= in
[triplet_index
];
261 dx
= WithSign(flag
, 1 + (b0
& 0x30) + (b1
>> 4));
262 dy
= WithSign(flag
>> 1, 1 + ((b0
& 0x0c) << 2) + (b1
& 0x0f));
263 } else if (flag
< 120) {
265 dx
= WithSign(flag
, 1 + ((b0
/ 12) << 8) + in
[triplet_index
]);
266 dy
= WithSign(flag
>> 1,
267 1 + (((b0
% 12) >> 2) << 8) + in
[triplet_index
+ 1]);
268 } else if (flag
< 124) {
269 int b2
= in
[triplet_index
+ 1];
270 dx
= WithSign(flag
, (in
[triplet_index
] << 4) + (b2
>> 4));
271 dy
= WithSign(flag
>> 1, ((b2
& 0x0f) << 8) + in
[triplet_index
+ 2]);
273 dx
= WithSign(flag
, (in
[triplet_index
] << 8) + in
[triplet_index
+ 1]);
274 dy
= WithSign(flag
>> 1,
275 (in
[triplet_index
+ 2] << 8) + in
[triplet_index
+ 3]);
277 triplet_index
+= n_data_bytes
;
278 // Possible overflow but coordinate values are not security sensitive
281 result
->push_back(Point());
282 Point
& back
= result
->back();
283 back
.x
= static_cast<int16_t>(x
);
284 back
.y
= static_cast<int16_t>(y
);
285 back
.on_curve
= on_curve
;
287 *in_bytes_consumed
= triplet_index
;
291 // This function stores just the point data. On entry, dst points to the
292 // beginning of a simple glyph. Returns true on success.
293 bool StorePoints(const std::vector
<Point
>& points
,
294 unsigned int n_contours
, unsigned int instruction_length
,
295 uint8_t* dst
, size_t dst_size
, size_t* glyph_size
) {
296 // I believe that n_contours < 65536, in which case this is safe. However, a
297 // comment and/or an assert would be good.
298 unsigned int flag_offset
= kEndPtsOfContoursOffset
+ 2 * n_contours
+ 2 +
300 uint8_t last_flag
= 0xff;
301 uint8_t repeat_count
= 0;
304 unsigned int x_bytes
= 0;
305 unsigned int y_bytes
= 0;
307 for (size_t i
= 0; i
< points
.size(); ++i
) {
308 const Point
& point
= points
.at(i
);
309 uint8_t flag
= point
.on_curve
? kGlyfOnCurve
: 0;
310 int dx
= point
.x
- last_x
;
311 int dy
= point
.y
- last_y
;
313 flag
|= kGlyfThisXIsSame
;
314 } else if (dx
> -256 && dx
< 256) {
315 flag
|= kGlyfXShort
| (dx
> 0 ? kGlyfThisXIsSame
: 0);
321 flag
|= kGlyfThisYIsSame
;
322 } else if (dy
> -256 && dy
< 256) {
323 flag
|= kGlyfYShort
| (dy
> 0 ? kGlyfThisYIsSame
: 0);
329 if (flag
== last_flag
&& repeat_count
!= 255) {
330 dst
[flag_offset
- 1] |= kGlyfRepeat
;
333 if (repeat_count
!= 0) {
334 if (flag_offset
>= dst_size
) {
335 return OTS_FAILURE();
337 dst
[flag_offset
++] = repeat_count
;
339 if (flag_offset
>= dst_size
) {
340 return OTS_FAILURE();
342 dst
[flag_offset
++] = flag
;
350 if (repeat_count
!= 0) {
351 if (flag_offset
>= dst_size
) {
352 return OTS_FAILURE();
354 dst
[flag_offset
++] = repeat_count
;
356 unsigned int xy_bytes
= x_bytes
+ y_bytes
;
357 if (xy_bytes
< x_bytes
||
358 flag_offset
+ xy_bytes
< flag_offset
||
359 flag_offset
+ xy_bytes
> dst_size
) {
360 return OTS_FAILURE();
363 int x_offset
= flag_offset
;
364 int y_offset
= flag_offset
+ x_bytes
;
367 for (size_t i
= 0; i
< points
.size(); ++i
) {
368 int dx
= points
.at(i
).x
- last_x
;
371 } else if (dx
> -256 && dx
< 256) {
372 dst
[x_offset
++] = static_cast<uint8_t>(std::abs(dx
));
374 // will always fit for valid input, but overflow is harmless
375 x_offset
= StoreU16(dst
, x_offset
, static_cast<uint16_t>(dx
));
378 int dy
= points
.at(i
).y
- last_y
;
381 } else if (dy
> -256 && dy
< 256) {
382 dst
[y_offset
++] = static_cast<uint8_t>(std::abs(dy
));
384 y_offset
= StoreU16(dst
, y_offset
, static_cast<uint16_t>(dy
));
388 *glyph_size
= y_offset
;
392 // Compute the bounding box of the coordinates, and store into a glyf buffer.
393 // A precondition is that there are at least 10 bytes available.
394 void ComputeBbox(const std::vector
<Point
>& points
, uint8_t* dst
) {
400 for (size_t i
= 0; i
< points
.size(); ++i
) {
401 int16_t x
= points
.at(i
).x
;
402 int16_t y
= points
.at(i
).y
;
403 if (i
== 0 || x
< x_min
) x_min
= x
;
404 if (i
== 0 || x
> x_max
) x_max
= x
;
405 if (i
== 0 || y
< y_min
) y_min
= y
;
406 if (i
== 0 || y
> y_max
) y_max
= y
;
409 offset
= StoreU16(dst
, offset
, x_min
);
410 offset
= StoreU16(dst
, offset
, y_min
);
411 offset
= StoreU16(dst
, offset
, x_max
);
412 offset
= StoreU16(dst
, offset
, y_max
);
415 // Process entire bbox stream. This is done as a separate pass to allow for
416 // composite bbox computations (an optional more aggressive transform).
417 bool ProcessBboxStream(ots::Buffer
* bbox_stream
, unsigned int n_glyphs
,
418 const std::vector
<uint32_t>& loca_values
, uint8_t* glyf_buf
,
419 size_t glyf_buf_length
) {
420 const uint8_t* buf
= bbox_stream
->buffer();
421 if (n_glyphs
>= 65536 || loca_values
.size() != n_glyphs
+ 1) {
422 return OTS_FAILURE();
424 // Safe because n_glyphs is bounded
425 unsigned int bitmap_length
= ((n_glyphs
+ 31) >> 5) << 2;
426 if (!bbox_stream
->Skip(bitmap_length
)) {
427 return OTS_FAILURE();
429 for (unsigned int i
= 0; i
< n_glyphs
; ++i
) {
430 if (buf
[i
>> 3] & (0x80 >> (i
& 7))) {
431 uint32_t loca_offset
= loca_values
.at(i
);
432 if (loca_values
.at(i
+ 1) - loca_offset
< kEndPtsOfContoursOffset
) {
433 return OTS_FAILURE();
435 if (glyf_buf_length
< 2 + 10 ||
436 loca_offset
> glyf_buf_length
- 2 - 10) {
437 return OTS_FAILURE();
439 if (!bbox_stream
->Read(glyf_buf
+ loca_offset
+ 2, 8)) {
440 return OTS_FAILURE();
447 bool ProcessComposite(ots::Buffer
* composite_stream
, uint8_t* dst
,
448 size_t dst_size
, size_t* glyph_size
, bool* have_instructions
) {
449 size_t start_offset
= composite_stream
->offset();
450 bool we_have_instructions
= false;
452 uint16_t flags
= FLAG_MORE_COMPONENTS
;
453 while (flags
& FLAG_MORE_COMPONENTS
) {
454 if (!composite_stream
->ReadU16(&flags
)) {
455 return OTS_FAILURE();
457 we_have_instructions
|= (flags
& FLAG_WE_HAVE_INSTRUCTIONS
) != 0;
458 size_t arg_size
= 2; // glyph index
459 if (flags
& FLAG_ARG_1_AND_2_ARE_WORDS
) {
464 if (flags
& FLAG_WE_HAVE_A_SCALE
) {
466 } else if (flags
& FLAG_WE_HAVE_AN_X_AND_Y_SCALE
) {
468 } else if (flags
& FLAG_WE_HAVE_A_TWO_BY_TWO
) {
471 if (!composite_stream
->Skip(arg_size
)) {
472 return OTS_FAILURE();
475 size_t composite_glyph_size
= composite_stream
->offset() - start_offset
;
476 if (composite_glyph_size
+ kCompositeGlyphBegin
> dst_size
) {
477 return OTS_FAILURE();
479 StoreU16(dst
, 0, 0xffff); // nContours = -1 for composite glyph
480 std::memcpy(dst
+ kCompositeGlyphBegin
,
481 composite_stream
->buffer() + start_offset
,
482 composite_glyph_size
);
483 *glyph_size
= kCompositeGlyphBegin
+ composite_glyph_size
;
484 *have_instructions
= we_have_instructions
;
488 // Build TrueType loca table
489 bool StoreLoca(const std::vector
<uint32_t>& loca_values
, int index_format
,
490 uint8_t* dst
, size_t dst_size
) {
491 const uint64_t loca_size
= loca_values
.size();
492 const uint64_t offset_size
= index_format
? 4 : 2;
493 if ((loca_size
<< 2) >> 2 != loca_size
) {
494 return OTS_FAILURE();
496 // No integer overflow here (loca_size <= 2^16).
497 if (offset_size
* loca_size
> dst_size
) {
498 return OTS_FAILURE();
501 for (size_t i
= 0; i
< loca_values
.size(); ++i
) {
502 uint32_t value
= loca_values
.at(i
);
504 offset
= StoreU32(dst
, offset
, value
);
506 offset
= StoreU16(dst
, offset
, static_cast<uint16_t>(value
>> 1));
512 // Reconstruct entire glyf table based on transformed original
513 bool ReconstructGlyf(ots::OpenTypeFile
* file
,
514 const uint8_t* data
, size_t data_size
,
515 uint8_t* dst
, size_t dst_size
,
516 uint8_t* loca_buf
, size_t loca_size
) {
517 static const int kNumSubStreams
= 7;
518 ots::Buffer
buffer(data
, data_size
);
520 std::vector
<std::pair
<const uint8_t*, size_t> > substreams(kNumSubStreams
);
522 if (!buffer
.ReadU32(&version
)) {
523 return OTS_FAILURE_MSG("Failed to read 'version' of transformed 'glyf' table");
526 if (!buffer
.ReadU16(&num_glyphs
)) {
527 return OTS_FAILURE_MSG("Failed to read 'numGlyphs' from transformed 'glyf' table");
529 uint16_t index_format
;
530 if (!buffer
.ReadU16(&index_format
)) {
531 return OTS_FAILURE_MSG("Failed to read 'indexFormat' from transformed 'glyf' table");
533 unsigned int offset
= (2 + kNumSubStreams
) * 4;
534 if (offset
> data_size
) {
535 return OTS_FAILURE_MSG("Size of transformed 'glyf' table is too small to fit its data");
537 // Invariant from here on: data_size >= offset
538 for (int i
= 0; i
< kNumSubStreams
; ++i
) {
539 uint32_t substream_size
;
540 if (!buffer
.ReadU32(&substream_size
)) {
541 return OTS_FAILURE_MSG("Failed to read substream size %d of transformed 'glyf' table", i
);
543 if (substream_size
> data_size
- offset
) {
544 return OTS_FAILURE_MSG("Size of substream %d of transformed 'glyf' table does not fit in table size");
546 substreams
.at(i
) = std::make_pair(data
+ offset
, substream_size
);
547 offset
+= substream_size
;
549 ots::Buffer
n_contour_stream(substreams
.at(0).first
, substreams
.at(0).second
);
550 ots::Buffer
n_points_stream(substreams
.at(1).first
, substreams
.at(1).second
);
551 ots::Buffer
flag_stream(substreams
.at(2).first
, substreams
.at(2).second
);
552 ots::Buffer
glyph_stream(substreams
.at(3).first
, substreams
.at(3).second
);
553 ots::Buffer
composite_stream(substreams
.at(4).first
, substreams
.at(4).second
);
554 ots::Buffer
bbox_stream(substreams
.at(5).first
, substreams
.at(5).second
);
555 ots::Buffer
instruction_stream(substreams
.at(6).first
,
556 substreams
.at(6).second
);
558 std::vector
<uint32_t> loca_values
;
559 loca_values
.reserve(num_glyphs
+ 1);
560 std::vector
<uint16_t> n_points_vec
;
561 std::vector
<Point
> points
;
562 uint32_t loca_offset
= 0;
563 for (unsigned int i
= 0; i
< num_glyphs
; ++i
) {
564 size_t glyph_size
= 0;
565 uint16_t n_contours
= 0;
566 if (!n_contour_stream
.ReadU16(&n_contours
)) {
567 return OTS_FAILURE_MSG("Filed to read 'numberOfContours' of glyph %d from transformed 'glyf' table", i
);
569 uint8_t* glyf_dst
= dst
+ loca_offset
;
570 size_t glyf_dst_size
= dst_size
- loca_offset
;
571 if (n_contours
== 0xffff) {
573 bool have_instructions
= false;
574 uint16_t instruction_size
= 0;
575 if (!ProcessComposite(&composite_stream
, glyf_dst
, glyf_dst_size
,
576 &glyph_size
, &have_instructions
)) {
577 return OTS_FAILURE_MSG("Filed to process composite glyph %d from transformed 'glyf' table", i
);
579 if (have_instructions
) {
580 if (!Read255UShort(&glyph_stream
, &instruction_size
)) {
581 return OTS_FAILURE_MSG("Failed to read 'instructionLength' of glyph %d from transformed 'glyf' table", i
);
583 // No integer overflow here (instruction_size < 2^16).
584 if (instruction_size
+ 2U > glyf_dst_size
- glyph_size
) {
585 return OTS_FAILURE_MSG("'instructionLength' of glyph %d from transformed 'glyf' table does not fit in the destination glyph size", i
);
587 StoreU16(glyf_dst
, glyph_size
, instruction_size
);
588 if (!instruction_stream
.Read(glyf_dst
+ glyph_size
+ 2,
590 return OTS_FAILURE_MSG("Filed to read instructions of glyph %d from transformed 'glyf' table", i
);
592 glyph_size
+= instruction_size
+ 2;
594 } else if (n_contours
> 0) {
596 n_points_vec
.clear();
598 uint32_t total_n_points
= 0;
599 uint16_t n_points_contour
;
600 for (uint32_t j
= 0; j
< n_contours
; ++j
) {
601 if (!Read255UShort(&n_points_stream
, &n_points_contour
)) {
602 return OTS_FAILURE_MSG("Filed to read number of points of contour %d of glyph %d from transformed 'glyf' table", j
, i
);
604 n_points_vec
.push_back(n_points_contour
);
605 if (total_n_points
+ n_points_contour
< total_n_points
) {
606 return OTS_FAILURE_MSG("Negative number of points of contour %d of glyph %d from transformed 'glyf' table", j
, i
);
608 total_n_points
+= n_points_contour
;
610 uint32_t flag_size
= total_n_points
;
611 if (flag_size
> flag_stream
.length() - flag_stream
.offset()) {
612 return OTS_FAILURE();
614 const uint8_t* flags_buf
= flag_stream
.buffer() + flag_stream
.offset();
615 const uint8_t* triplet_buf
= glyph_stream
.buffer() +
616 glyph_stream
.offset();
617 size_t triplet_size
= glyph_stream
.length() - glyph_stream
.offset();
618 size_t triplet_bytes_consumed
= 0;
619 if (!TripletDecode(flags_buf
, triplet_buf
, triplet_size
, total_n_points
,
620 &points
, &triplet_bytes_consumed
)) {
621 return OTS_FAILURE();
623 const uint32_t header_and_endpts_contours_size
=
624 kEndPtsOfContoursOffset
+ 2 * n_contours
;
625 if (glyf_dst_size
< header_and_endpts_contours_size
) {
626 return OTS_FAILURE();
628 StoreU16(glyf_dst
, 0, n_contours
);
629 ComputeBbox(points
, glyf_dst
);
630 size_t endpts_offset
= kEndPtsOfContoursOffset
;
632 for (unsigned int contour_ix
= 0; contour_ix
< n_contours
; ++contour_ix
) {
633 end_point
+= n_points_vec
.at(contour_ix
);
634 if (end_point
>= 65536) {
635 return OTS_FAILURE();
637 endpts_offset
= StoreU16(glyf_dst
, endpts_offset
, static_cast<uint16_t>(end_point
));
639 if (!flag_stream
.Skip(flag_size
)) {
640 return OTS_FAILURE();
642 if (!glyph_stream
.Skip(triplet_bytes_consumed
)) {
643 return OTS_FAILURE();
645 uint16_t instruction_size
;
646 if (!Read255UShort(&glyph_stream
, &instruction_size
)) {
647 return OTS_FAILURE();
649 // No integer overflow here (instruction_size < 2^16).
650 if (glyf_dst_size
- header_and_endpts_contours_size
<
651 instruction_size
+ 2U) {
652 return OTS_FAILURE();
654 uint8_t* instruction_dst
= glyf_dst
+ header_and_endpts_contours_size
;
655 StoreU16(instruction_dst
, 0, instruction_size
);
656 if (!instruction_stream
.Read(instruction_dst
+ 2, instruction_size
)) {
657 return OTS_FAILURE();
659 if (!StorePoints(points
, n_contours
, instruction_size
,
660 glyf_dst
, glyf_dst_size
, &glyph_size
)) {
661 return OTS_FAILURE_MSG("Failed to store points of glyph %d from the transformed 'glyf' table", i
);
666 loca_values
.push_back(loca_offset
);
667 if (glyph_size
+ 3 < glyph_size
) {
668 return OTS_FAILURE();
670 glyph_size
= ots::Round2(glyph_size
);
671 if (glyph_size
> dst_size
- loca_offset
) {
672 // This shouldn't happen, but this test defensively maintains the
673 // invariant that loca_offset <= dst_size.
674 return OTS_FAILURE();
676 loca_offset
+= glyph_size
;
678 loca_values
.push_back(loca_offset
);
679 assert(loca_values
.size() == static_cast<size_t>(num_glyphs
+ 1));
680 if (!ProcessBboxStream(&bbox_stream
, num_glyphs
, loca_values
,
682 return OTS_FAILURE_MSG("Filed to process 'bboxStream' from the transformed 'glyf' table");
684 return StoreLoca(loca_values
, index_format
, loca_buf
, loca_size
);
687 // This is linear search, but could be changed to binary because we
688 // do have a guarantee that the tables are sorted by tag. But the total
689 // cpu time is expected to be very small in any case.
690 const Table
* FindTable(const std::vector
<Table
>& tables
, uint32_t tag
) {
691 size_t n_tables
= tables
.size();
692 for (size_t i
= 0; i
< n_tables
; ++i
) {
693 if (tables
.at(i
).tag
== tag
) {
694 return &tables
.at(i
);
700 bool ReconstructTransformed(ots::OpenTypeFile
* file
,
701 const std::vector
<Table
>& tables
, uint32_t tag
,
702 const uint8_t* transformed_buf
, size_t transformed_size
,
703 uint8_t* dst
, size_t dst_length
) {
704 if (tag
== OTS_TAG('g','l','y','f')) {
705 const Table
* glyf_table
= FindTable(tables
, tag
);
706 const Table
* loca_table
= FindTable(tables
, OTS_TAG('l','o','c','a'));
707 if (glyf_table
== NULL
|| loca_table
== NULL
) {
708 return OTS_FAILURE();
710 if (static_cast<uint64_t>(glyf_table
->dst_offset
) + glyf_table
->dst_length
>
712 return OTS_FAILURE();
714 if (static_cast<uint64_t>(loca_table
->dst_offset
) + loca_table
->dst_length
>
716 return OTS_FAILURE();
718 return ReconstructGlyf(file
, transformed_buf
, transformed_size
,
719 dst
+ glyf_table
->dst_offset
, glyf_table
->dst_length
,
720 dst
+ loca_table
->dst_offset
, loca_table
->dst_length
);
721 } else if (tag
== OTS_TAG('l','o','c','a')) {
722 // processing was already done by glyf table, but validate
723 if (!FindTable(tables
, OTS_TAG('g','l','y','f'))) {
724 return OTS_FAILURE();
727 // transform for the tag is not known
728 return OTS_FAILURE();
733 uint32_t ComputeChecksum(const uint8_t* buf
, size_t size
) {
734 uint32_t checksum
= 0;
735 for (size_t i
= 0; i
< size
; i
+= 4) {
736 // We assume the addition is mod 2^32, which is valid because unsigned
737 checksum
+= (buf
[i
] << 24) | (buf
[i
+ 1] << 16) |
738 (buf
[i
+ 2] << 8) | buf
[i
+ 3];
743 bool FixChecksums(const std::vector
<Table
>& tables
, uint8_t* dst
) {
744 const Table
* head_table
= FindTable(tables
, OTS_TAG('h','e','a','d'));
745 if (head_table
== NULL
||
746 head_table
->dst_length
< kCheckSumAdjustmentOffset
+ 4) {
747 return OTS_FAILURE();
749 size_t adjustment_offset
= head_table
->dst_offset
+ kCheckSumAdjustmentOffset
;
750 if (adjustment_offset
< head_table
->dst_offset
) {
751 return OTS_FAILURE();
753 StoreU32(dst
, adjustment_offset
, 0);
754 size_t n_tables
= tables
.size();
755 uint32_t file_checksum
= 0;
756 for (size_t i
= 0; i
< n_tables
; ++i
) {
757 const Table
* table
= &tables
.at(i
);
758 size_t table_length
= table
->dst_length
;
759 uint8_t* table_data
= dst
+ table
->dst_offset
;
760 uint32_t checksum
= ComputeChecksum(table_data
, table_length
);
761 StoreU32(dst
, kSfntHeaderSize
+ i
* kSfntEntrySize
+ 4, checksum
);
762 file_checksum
+= checksum
; // The addition is mod 2^32
764 file_checksum
+= ComputeChecksum(dst
,
765 kSfntHeaderSize
+ kSfntEntrySize
* n_tables
);
766 uint32_t checksum_adjustment
= 0xb1b0afba - file_checksum
;
767 StoreU32(dst
, adjustment_offset
, checksum_adjustment
);
771 bool ReadTableDirectory(ots::OpenTypeFile
* file
,
772 ots::Buffer
* buffer
, std::vector
<Table
>* tables
,
774 for (size_t i
= 0; i
< num_tables
; ++i
) {
775 Table
* table
= &tables
->at(i
);
777 if (!buffer
->ReadU8(&flag_byte
)) {
778 return OTS_FAILURE_MSG("Failed to read the flags of table directory entry %d", i
);
781 if ((flag_byte
& 0x3f) == 0x3f) {
782 if (!buffer
->ReadU32(&tag
)) {
783 return OTS_FAILURE_MSG("Failed to read the tag of table directory entry %d", i
);
786 tag
= kKnownTags
[flag_byte
& 0x3f];
788 // Bits 6 and 7 are reserved and must be 0.
789 if ((flag_byte
& 0xc0) != 0) {
790 return OTS_FAILURE_MSG("Bits 6 and 7 are not 0 for table directory entry %d", i
);
793 // Always transform the glyf and loca tables
794 if (tag
== OTS_TAG('g','l','y','f') ||
795 tag
== OTS_TAG('l','o','c','a')) {
796 flags
|= kWoff2FlagsTransform
;
799 if (!ReadBase128(buffer
, &dst_length
)) {
800 return OTS_FAILURE_MSG("Failed to read 'origLength' for table '%c%c%c%c'", OTS_UNTAG(tag
));
802 uint32_t transform_length
= dst_length
;
803 if ((flags
& kWoff2FlagsTransform
) != 0) {
804 if (!ReadBase128(buffer
, &transform_length
)) {
805 return OTS_FAILURE_MSG("Failed to read 'transformLength' for table '%c%c%c%c'", OTS_UNTAG(tag
));
808 if (tag
== OTS_TAG('l','o','c','a') && transform_length
!= 0) {
809 return OTS_FAILURE_MSG("The 'transformLength' of 'loca' table must be zero: %d", transform_length
);
812 // Disallow huge numbers (> 1GB) for sanity.
813 if (transform_length
> 1024 * 1024 * 1024 ||
814 dst_length
> 1024 * 1024 * 1024) {
815 return OTS_FAILURE_MSG("'origLength' or 'transformLength' > 1GB");
818 table
->flags
= flags
;
819 table
->transform_length
= transform_length
;
820 table
->dst_length
= dst_length
;
829 size_t ComputeWOFF2FinalSize(const uint8_t* data
, size_t length
) {
830 ots::Buffer
file(data
, length
);
831 uint32_t total_length
;
833 if (!file
.Skip(16) ||
834 !file
.ReadU32(&total_length
)) {
840 bool ConvertWOFF2ToSFNT(ots::OpenTypeFile
* file
,
841 uint8_t* result
, size_t result_length
,
842 const uint8_t* data
, size_t length
) {
843 static const uint32_t kWoff2Signature
= 0x774f4632; // "wOF2"
844 ots::Buffer
buffer(data
, length
);
848 if (!buffer
.ReadU32(&signature
) || signature
!= kWoff2Signature
||
849 !buffer
.ReadU32(&flavor
)) {
850 return OTS_FAILURE_MSG("Failed to read 'signature' or 'flavor', or not WOFF2 signature");
853 if (!IsValidVersionTag(ntohl(flavor
))) {
854 return OTS_FAILURE_MSG("Invalid 'flavor'");
857 uint32_t reported_length
;
858 if (!buffer
.ReadU32(&reported_length
) || length
!= reported_length
) {
859 return OTS_FAILURE_MSG("Failed to read 'length' or it does not match the actual file size");
862 if (!buffer
.ReadU16(&num_tables
) || !num_tables
) {
863 return OTS_FAILURE_MSG("Failed to read 'numTables'");
866 uint16_t reserved_value
;
867 if (!buffer
.ReadU16(&reserved_value
)) {
868 return OTS_FAILURE_MSG("Failed to read 'reserved' field");
871 // We don't care about these fields of the header:
872 // uint32_t total_sfnt_size, the caller already passes it as result_length
873 if (!buffer
.Skip(4)) {
874 return OTS_FAILURE_MSG("Failed to read 'totalSfntSize'");
876 uint32_t compressed_length
;
877 if (!buffer
.ReadU32(&compressed_length
)) {
878 return OTS_FAILURE_MSG("Failed to read 'totalCompressedSize'");
880 if (compressed_length
> std::numeric_limits
<uint32_t>::max()) {
881 return OTS_FAILURE();
884 // We don't care about these fields of the header:
885 // uint16_t major_version, minor_version
886 if (!buffer
.Skip(2 * 2)) {
887 return OTS_FAILURE_MSG("Failed to read 'majorVersion' or 'minorVersion'");
890 // Checks metadata block size.
891 uint32_t meta_offset
;
892 uint32_t meta_length
;
893 uint32_t meta_length_orig
;
894 if (!buffer
.ReadU32(&meta_offset
) ||
895 !buffer
.ReadU32(&meta_length
) ||
896 !buffer
.ReadU32(&meta_length_orig
)) {
897 return OTS_FAILURE_MSG("Failed to read header metadata block fields");
900 if (meta_offset
>= length
|| length
- meta_offset
< meta_length
) {
901 return OTS_FAILURE_MSG("Invalid metadata block offset or length");
905 // Checks private data block size.
906 uint32_t priv_offset
;
907 uint32_t priv_length
;
908 if (!buffer
.ReadU32(&priv_offset
) ||
909 !buffer
.ReadU32(&priv_length
)) {
910 return OTS_FAILURE_MSG("Failed to read header private block fields");
913 if (priv_offset
>= length
|| length
- priv_offset
< priv_length
) {
914 return OTS_FAILURE_MSG("Invalid private block offset or length");
918 std::vector
<Table
> tables(num_tables
);
919 if (!ReadTableDirectory(file
, &buffer
, &tables
, num_tables
)) {
920 return OTS_FAILURE_MSG("Failed to read table directory");
922 uint64_t compressed_offset
= buffer
.offset();
923 if (compressed_offset
> std::numeric_limits
<uint32_t>::max()) {
924 return OTS_FAILURE();
926 uint64_t dst_offset
= kSfntHeaderSize
+
927 kSfntEntrySize
* static_cast<uint64_t>(num_tables
);
928 for (uint16_t i
= 0; i
< num_tables
; ++i
) {
929 Table
* table
= &tables
.at(i
);
930 table
->dst_offset
= static_cast<uint32_t>(dst_offset
);
931 dst_offset
+= table
->dst_length
;
932 if (dst_offset
> std::numeric_limits
<uint32_t>::max()) {
933 return OTS_FAILURE();
935 dst_offset
= ots::Round4(dst_offset
);
938 uint64_t block_end
= ots::Round4(compressed_offset
+ compressed_length
);
939 if (block_end
> length
|| dst_offset
!= result_length
) {
940 return OTS_FAILURE_MSG("Uncompressed sfnt size mismatch");
943 const uint32_t sfnt_header_and_table_directory_size
= 12 + 16 * num_tables
;
944 if (sfnt_header_and_table_directory_size
> result_length
) {
945 return OTS_FAILURE();
949 if (block_end
!= meta_offset
) {
950 return OTS_FAILURE_MSG("Invalid metadata block offset");
952 block_end
= ots::Round4(static_cast<uint64_t>(meta_offset
) +
953 static_cast<uint64_t>(meta_length
));
954 if (block_end
> std::numeric_limits
<uint32_t>::max()) {
955 return OTS_FAILURE_MSG("Invalid metadata block length");
960 if (block_end
!= priv_offset
) {
961 return OTS_FAILURE_MSG("Invalid private block offset");
963 block_end
= ots::Round4(static_cast<uint64_t>(priv_offset
) +
964 static_cast<uint64_t>(priv_length
));
965 if (block_end
> std::numeric_limits
<uint32_t>::max()) {
966 return OTS_FAILURE_MSG("Invalid private block length");
970 if (block_end
!= ots::Round4(length
)) {
971 return OTS_FAILURE_MSG("File length mismatch (trailing junk?)");
974 // Start building the font
976 offset
= StoreU32(result
, offset
, flavor
);
977 offset
= StoreU16(result
, offset
, num_tables
);
978 uint8_t max_pow2
= 0;
979 while (1u << (max_pow2
+ 1) <= num_tables
) {
982 const uint16_t output_search_range
= (1u << max_pow2
) << 4;
983 offset
= StoreU16(result
, offset
, output_search_range
);
984 offset
= StoreU16(result
, offset
, max_pow2
);
985 offset
= StoreU16(result
, offset
, (num_tables
<< 4) - output_search_range
);
987 // sort tags in the table directory in ascending alphabetical order
988 std::vector
<Table
> sorted_tables(tables
);
989 std::sort(sorted_tables
.begin(), sorted_tables
.end());
991 for (uint16_t i
= 0; i
< num_tables
; ++i
) {
992 const Table
* table
= &sorted_tables
.at(i
);
993 offset
= StoreU32(result
, offset
, table
->tag
);
994 offset
= StoreU32(result
, offset
, 0); // checksum, to fill in later
995 offset
= StoreU32(result
, offset
, table
->dst_offset
);
996 offset
= StoreU32(result
, offset
, table
->dst_length
);
998 std::vector
<uint8_t> uncompressed_buf
;
999 const uint8_t* transform_buf
= NULL
;
1000 uint64_t total_size
= 0;
1002 for (uint16_t i
= 0; i
< num_tables
; ++i
) {
1003 total_size
+= tables
.at(i
).transform_length
;
1004 if (total_size
> std::numeric_limits
<uint32_t>::max()) {
1005 return OTS_FAILURE();
1008 // Enforce same 30M limit on uncompressed tables as OTS
1009 if (total_size
> 30 * 1024 * 1024) {
1010 return OTS_FAILURE();
1012 size_t uncompressed_size
= static_cast<size_t>(total_size
);
1013 uncompressed_buf
.resize(uncompressed_size
);
1014 const uint8_t* compressed_buf
= data
+ compressed_offset
;
1015 if (!BrotliDecompressBuffer(compressed_length
, compressed_buf
,
1016 &uncompressed_size
, &uncompressed_buf
[0])) {
1017 return OTS_FAILURE_MSG("Failed to uncompress font data");
1019 if (uncompressed_size
!= static_cast<size_t>(total_size
)) {
1020 return OTS_FAILURE_MSG("Decompressed font data size does not match the sum of 'origLength' and 'transformLength'");
1022 transform_buf
= &uncompressed_buf
[0];
1024 for (uint16_t i
= 0; i
< num_tables
; ++i
) {
1025 const Table
* table
= &tables
.at(i
);
1026 uint32_t flags
= table
->flags
;
1027 size_t transform_length
= table
->transform_length
;
1029 if ((flags
& kWoff2FlagsTransform
) == 0) {
1030 if (transform_length
!= table
->dst_length
) {
1031 return OTS_FAILURE();
1033 if (static_cast<uint64_t>(table
->dst_offset
) + transform_length
>
1035 return OTS_FAILURE();
1037 std::memcpy(result
+ table
->dst_offset
, transform_buf
,
1040 if (!ReconstructTransformed(file
, tables
, table
->tag
,
1041 transform_buf
, transform_length
, result
, result_length
)) {
1042 return OTS_FAILURE_MSG("Failed to reconstruct '%c%c%c%c' table", OTS_UNTAG(table
->tag
));
1046 transform_buf
+= transform_length
;
1047 if (transform_buf
> &uncompressed_buf
[0] + uncompressed_buf
.size()) {
1048 return OTS_FAILURE();
1052 return FixChecksums(sorted_tables
, result
);