Coverage Report

Created: 2026-09-03 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/woff2/src/woff2_dec.cc
Line
Count
Source
1
/* Copyright 2014 Google Inc. All Rights Reserved.
2
3
   Distributed under MIT license.
4
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5
*/
6
7
/* Library for converting WOFF2 format font files to their TTF versions. */
8
9
#include <woff2/decode.h>
10
11
#include <stdlib.h>
12
#include <algorithm>
13
#include <complex>
14
#include <cstring>
15
#include <limits>
16
#include <string>
17
#include <vector>
18
#include <map>
19
#include <memory>
20
#include <utility>
21
22
#include <brotli/decode.h>
23
#include "./buffer.h"
24
#include "./port.h"
25
#include "./round.h"
26
#include "./store_bytes.h"
27
#include "./table_tags.h"
28
#include "./variable_length.h"
29
#include "./woff2_common.h"
30
31
namespace woff2 {
32
33
namespace {
34
35
// simple glyph flags
36
const int kGlyfOnCurve = 1 << 0;
37
const int kGlyfXShort = 1 << 1;
38
const int kGlyfYShort = 1 << 2;
39
const int kGlyfRepeat = 1 << 3;
40
const int kGlyfThisXIsSame = 1 << 4;
41
const int kGlyfThisYIsSame = 1 << 5;
42
const int kOverlapSimple = 1 << 6;
43
44
// composite glyph flags
45
// See CompositeGlyph.java in sfntly for full definitions
46
const int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;
47
const int FLAG_WE_HAVE_A_SCALE = 1 << 3;
48
const int FLAG_MORE_COMPONENTS = 1 << 5;
49
const int FLAG_WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6;
50
const int FLAG_WE_HAVE_A_TWO_BY_TWO = 1 << 7;
51
const int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;
52
53
// glyf flags
54
const int FLAG_OVERLAP_SIMPLE_BITMAP = 1 << 0;
55
56
const size_t kCheckSumAdjustmentOffset = 8;
57
58
const size_t kEndPtsOfContoursOffset = 10;
59
const size_t kCompositeGlyphBegin = 10;
60
61
// 98% of Google Fonts have no glyph above 5k bytes
62
// Largest glyph ever observed was 72k bytes
63
const size_t kDefaultGlyphBuf = 5120;
64
65
// Over 14k test fonts the max compression ratio seen to date was ~20.
66
// >100 suggests you wrote a bad uncompressed size.
67
const float kMaxPlausibleCompressionRatio = 100.0;
68
69
// metadata for a TTC font entry
70
struct TtcFont {
71
  uint32_t flavor;
72
  uint32_t dst_offset;
73
  uint32_t header_checksum;
74
  std::vector<uint16_t> table_indices;
75
};
76
77
struct WOFF2Header {
78
  uint32_t flavor;
79
  uint32_t header_version;
80
  uint16_t num_tables;
81
  uint64_t compressed_offset;
82
  uint32_t compressed_length;
83
  uint32_t uncompressed_size;
84
  std::vector<Table> tables;  // num_tables unique tables
85
  std::vector<TtcFont> ttc_fonts;  // metadata to help rebuild font
86
};
87
88
/**
89
 * Accumulates data we may need to reconstruct a single font. One per font
90
 * created for a TTC.
91
 */
92
struct WOFF2FontInfo {
93
  uint16_t num_glyphs;
94
  uint16_t index_format;
95
  uint16_t num_hmetrics;
96
  std::vector<int16_t> x_mins;
97
  std::map<uint32_t, uint32_t> table_entry_by_tag;
98
};
99
100
// Accumulates metadata as we rebuild the font
101
struct RebuildMetadata {
102
  uint32_t header_checksum;  // set by WriteHeaders
103
  std::vector<WOFF2FontInfo> font_infos;
104
  // checksums for tables that have been written.
105
  // (tag, src_offset) => checksum. Need both because 0-length loca.
106
  std::map<std::pair<uint32_t, uint32_t>, uint32_t> checksums;
107
};
108
109
37.9M
int WithSign(int flag, int baseval) {
110
  // Precondition: 0 <= baseval < 65536 (to avoid integer overflow)
111
37.9M
  return (flag & 1) ? baseval : -baseval;
112
37.9M
}
113
114
48.3M
bool _SafeIntAddition(int a, int b, int* result) {
115
48.3M
  if (PREDICT_FALSE(
116
48.3M
          ((a > 0) && (b > std::numeric_limits<int>::max() - a)) ||
117
48.3M
          ((a < 0) && (b < std::numeric_limits<int>::min() - a)))) {
118
78
    return false;
119
78
  }
120
48.3M
  *result = a + b;
121
48.3M
  return true;
122
48.3M
}
123
124
bool TripletDecode(const uint8_t* flags_in, const uint8_t* in, size_t in_size,
125
126k
    unsigned int n_points, Point* result, size_t* in_bytes_consumed) {
126
126k
  int x = 0;
127
126k
  int y = 0;
128
129
126k
  if (PREDICT_FALSE(n_points > in_size)) {
130
36
    return FONT_COMPRESSION_FAILURE();
131
36
  }
132
125k
  unsigned int triplet_index = 0;
133
134
24.3M
  for (unsigned int i = 0; i < n_points; ++i) {
135
24.1M
    uint8_t flag = flags_in[i];
136
24.1M
    bool on_curve = !(flag >> 7);
137
24.1M
    flag &= 0x7f;
138
24.1M
    unsigned int n_data_bytes;
139
24.1M
    if (flag < 84) {
140
16.7M
      n_data_bytes = 1;
141
16.7M
    } else if (flag < 120) {
142
2.04M
      n_data_bytes = 2;
143
5.39M
    } else if (flag < 124) {
144
215k
      n_data_bytes = 3;
145
5.18M
    } else {
146
5.18M
      n_data_bytes = 4;
147
5.18M
    }
148
24.1M
    if (PREDICT_FALSE(triplet_index + n_data_bytes > in_size ||
149
24.1M
        triplet_index + n_data_bytes < triplet_index)) {
150
48
      return FONT_COMPRESSION_FAILURE();
151
48
    }
152
24.1M
    int dx, dy;
153
24.1M
    if (flag < 10) {
154
9.06M
      dx = 0;
155
9.06M
      dy = WithSign(flag, ((flag & 14) << 7) + in[triplet_index]);
156
15.1M
    } else if (flag < 20) {
157
1.39M
      dx = WithSign(flag, (((flag - 10) & 14) << 7) + in[triplet_index]);
158
1.39M
      dy = 0;
159
13.7M
    } else if (flag < 84) {
160
6.30M
      int b0 = flag - 20;
161
6.30M
      int b1 = in[triplet_index];
162
6.30M
      dx = WithSign(flag, 1 + (b0 & 0x30) + (b1 >> 4));
163
6.30M
      dy = WithSign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f));
164
7.43M
    } else if (flag < 120) {
165
2.04M
      int b0 = flag - 84;
166
2.04M
      dx = WithSign(flag, 1 + ((b0 / 12) << 8) + in[triplet_index]);
167
2.04M
      dy = WithSign(flag >> 1,
168
2.04M
                    1 + (((b0 % 12) >> 2) << 8) + in[triplet_index + 1]);
169
5.39M
    } else if (flag < 124) {
170
215k
      int b2 = in[triplet_index + 1];
171
215k
      dx = WithSign(flag, (in[triplet_index] << 4) + (b2 >> 4));
172
215k
      dy = WithSign(flag >> 1, ((b2 & 0x0f) << 8) + in[triplet_index + 2]);
173
5.18M
    } else {
174
5.18M
      dx = WithSign(flag, (in[triplet_index] << 8) + in[triplet_index + 1]);
175
5.18M
      dy = WithSign(flag >> 1,
176
5.18M
          (in[triplet_index + 2] << 8) + in[triplet_index + 3]);
177
5.18M
    }
178
24.1M
    triplet_index += n_data_bytes;
179
24.1M
    if (!_SafeIntAddition(x, dx, &x)) {
180
36
      return false;
181
36
    }
182
24.1M
    if (!_SafeIntAddition(y, dy, &y)) {
183
42
      return false;
184
42
    }
185
24.1M
    *result++ = {x, y, on_curve};
186
24.1M
  }
187
125k
  *in_bytes_consumed = triplet_index;
188
125k
  return true;
189
125k
}
190
191
// This function stores just the point data. On entry, dst points to the
192
// beginning of a simple glyph. Returns true on success.
193
bool StorePoints(unsigned int n_points, const Point* points,
194
                 unsigned int n_contours, unsigned int instruction_length,
195
                 bool has_overlap_bit, uint8_t* dst, size_t dst_size,
196
125k
                 size_t* glyph_size) {
197
  // I believe that n_contours < 65536, in which case this is safe. However, a
198
  // comment and/or an assert would be good.
199
125k
  unsigned int flag_offset = kEndPtsOfContoursOffset + 2 * n_contours + 2 +
200
125k
    instruction_length;
201
125k
  int last_flag = -1;
202
125k
  int repeat_count = 0;
203
125k
  int last_x = 0;
204
125k
  int last_y = 0;
205
125k
  unsigned int x_bytes = 0;
206
125k
  unsigned int y_bytes = 0;
207
208
9.29M
  for (unsigned int i = 0; i < n_points; ++i) {
209
9.17M
    const Point& point = points[i];
210
9.17M
    int flag = point.on_curve ? kGlyfOnCurve : 0;
211
9.17M
    if (has_overlap_bit && i == 0) {
212
267
      flag |= kOverlapSimple;
213
267
    }
214
215
9.17M
    int dx = point.x - last_x;
216
9.17M
    int dy = point.y - last_y;
217
9.17M
    if (dx == 0) {
218
5.36M
      flag |= kGlyfThisXIsSame;
219
5.36M
    } else if (dx > -256 && dx < 256) {
220
3.11M
      flag |= kGlyfXShort | (dx > 0 ? kGlyfThisXIsSame : 0);
221
3.11M
      x_bytes += 1;
222
3.11M
    } else {
223
690k
      x_bytes += 2;
224
690k
    }
225
9.17M
    if (dy == 0) {
226
4.06M
      flag |= kGlyfThisYIsSame;
227
5.10M
    } else if (dy > -256 && dy < 256) {
228
3.70M
      flag |= kGlyfYShort | (dy > 0 ? kGlyfThisYIsSame : 0);
229
3.70M
      y_bytes += 1;
230
3.70M
    } else {
231
1.40M
      y_bytes += 2;
232
1.40M
    }
233
234
9.17M
    if (flag == last_flag && repeat_count != 255) {
235
3.85M
      dst[flag_offset - 1] |= kGlyfRepeat;
236
3.85M
      repeat_count++;
237
5.31M
    } else {
238
5.31M
      if (repeat_count != 0) {
239
764k
        if (PREDICT_FALSE(flag_offset >= dst_size)) {
240
0
          return FONT_COMPRESSION_FAILURE();
241
0
        }
242
764k
        dst[flag_offset++] = repeat_count;
243
764k
      }
244
5.31M
      if (PREDICT_FALSE(flag_offset >= dst_size)) {
245
0
        return FONT_COMPRESSION_FAILURE();
246
0
      }
247
5.31M
      dst[flag_offset++] = flag;
248
5.31M
      repeat_count = 0;
249
5.31M
    }
250
9.17M
    last_x = point.x;
251
9.17M
    last_y = point.y;
252
9.17M
    last_flag = flag;
253
9.17M
  }
254
255
125k
  if (repeat_count != 0) {
256
42.9k
    if (PREDICT_FALSE(flag_offset >= dst_size)) {
257
0
      return FONT_COMPRESSION_FAILURE();
258
0
    }
259
42.9k
    dst[flag_offset++] = repeat_count;
260
42.9k
  }
261
125k
  unsigned int xy_bytes = x_bytes + y_bytes;
262
125k
  if (PREDICT_FALSE(xy_bytes < x_bytes ||
263
125k
      flag_offset + xy_bytes < flag_offset ||
264
125k
      flag_offset + xy_bytes > dst_size)) {
265
0
    return FONT_COMPRESSION_FAILURE();
266
0
  }
267
268
125k
  int x_offset = flag_offset;
269
125k
  int y_offset = flag_offset + x_bytes;
270
125k
  last_x = 0;
271
125k
  last_y = 0;
272
9.29M
  for (unsigned int i = 0; i < n_points; ++i) {
273
9.17M
    int dx = points[i].x - last_x;
274
9.17M
    if (dx == 0) {
275
      // pass
276
5.36M
    } else if (dx > -256 && dx < 256) {
277
3.11M
      dst[x_offset++] = std::abs(dx);
278
3.11M
    } else {
279
      // will always fit for valid input, but overflow is harmless
280
690k
      x_offset = Store16(dst, x_offset, dx);
281
690k
    }
282
9.17M
    last_x += dx;
283
9.17M
    int dy = points[i].y - last_y;
284
9.17M
    if (dy == 0) {
285
      // pass
286
5.10M
    } else if (dy > -256 && dy < 256) {
287
3.70M
      dst[y_offset++] = std::abs(dy);
288
3.70M
    } else {
289
1.40M
      y_offset = Store16(dst, y_offset, dy);
290
1.40M
    }
291
9.17M
    last_y += dy;
292
9.17M
  }
293
125k
  *glyph_size = y_offset;
294
125k
  return true;
295
125k
}
296
297
// Compute the bounding box of the coordinates, and store into a glyf buffer.
298
// A precondition is that there are at least 10 bytes available.
299
// dst should point to the beginning of a 'glyf' record.
300
124k
void ComputeBbox(unsigned int n_points, const Point* points, uint8_t* dst) {
301
124k
  int x_min = 0;
302
124k
  int y_min = 0;
303
124k
  int x_max = 0;
304
124k
  int y_max = 0;
305
306
124k
  if (n_points > 0) {
307
120k
    x_min = points[0].x;
308
120k
    x_max = points[0].x;
309
120k
    y_min = points[0].y;
310
120k
    y_max = points[0].y;
311
120k
  }
312
11.6M
  for (unsigned int i = 1; i < n_points; ++i) {
313
11.5M
    int x = points[i].x;
314
11.5M
    int y = points[i].y;
315
11.5M
    x_min = std::min(x, x_min);
316
11.5M
    x_max = std::max(x, x_max);
317
11.5M
    y_min = std::min(y, y_min);
318
11.5M
    y_max = std::max(y, y_max);
319
11.5M
  }
320
124k
  size_t offset = 2;
321
124k
  offset = Store16(dst, offset, x_min);
322
124k
  offset = Store16(dst, offset, y_min);
323
124k
  offset = Store16(dst, offset, x_max);
324
124k
  offset = Store16(dst, offset, y_max);
325
124k
}
326
327
328
bool SizeOfComposite(Buffer composite_stream, size_t* size,
329
1.14k
                     bool* have_instructions) {
330
1.14k
  size_t start_offset = composite_stream.offset();
331
1.14k
  bool we_have_instructions = false;
332
333
1.14k
  uint16_t flags = FLAG_MORE_COMPONENTS;
334
10.3k
  while (flags & FLAG_MORE_COMPONENTS) {
335
9.27k
    if (PREDICT_FALSE(!composite_stream.ReadU16(&flags))) {
336
13
      return FONT_COMPRESSION_FAILURE();
337
13
    }
338
9.26k
    we_have_instructions |= (flags & FLAG_WE_HAVE_INSTRUCTIONS) != 0;
339
9.26k
    size_t arg_size = 2;  // glyph index
340
9.26k
    if (flags & FLAG_ARG_1_AND_2_ARE_WORDS) {
341
4.63k
      arg_size += 4;
342
4.63k
    } else {
343
4.62k
      arg_size += 2;
344
4.62k
    }
345
9.26k
    if (flags & FLAG_WE_HAVE_A_SCALE) {
346
3.04k
      arg_size += 2;
347
6.22k
    } else if (flags & FLAG_WE_HAVE_AN_X_AND_Y_SCALE) {
348
1.69k
      arg_size += 4;
349
4.52k
    } else if (flags & FLAG_WE_HAVE_A_TWO_BY_TWO) {
350
1.44k
      arg_size += 8;
351
1.44k
    }
352
9.26k
    if (PREDICT_FALSE(!composite_stream.Skip(arg_size))) {
353
30
      return FONT_COMPRESSION_FAILURE();
354
30
    }
355
9.26k
  }
356
357
1.10k
  *size = composite_stream.offset() - start_offset;
358
1.10k
  *have_instructions = we_have_instructions;
359
360
1.10k
  return true;
361
1.14k
}
362
363
181k
bool Pad4(WOFF2Out* out) {
364
181k
  uint8_t zeroes[] = {0, 0, 0};
365
181k
  if (PREDICT_FALSE(out->Size() + 3 < out->Size())) {
366
0
    return FONT_COMPRESSION_FAILURE();
367
0
  }
368
181k
  uint32_t pad_bytes = Round4(out->Size()) - out->Size();
369
181k
  if (pad_bytes > 0) {
370
96.8k
    if (PREDICT_FALSE(!out->Write(&zeroes, pad_bytes))) {
371
0
      return FONT_COMPRESSION_FAILURE();
372
0
    }
373
96.8k
  }
374
181k
  return true;
375
181k
}
376
377
// Build TrueType loca table
378
bool StoreLoca(const std::vector<uint32_t>& loca_values, int index_format,
379
164
               uint32_t* checksum, WOFF2Out* out) {
380
  // TODO(user) figure out what index format to use based on whether max
381
  // offset fits into uint16_t or not
382
164
  const uint64_t loca_size = loca_values.size();
383
164
  const uint64_t offset_size = index_format ? 4 : 2;
384
164
  if (PREDICT_FALSE((loca_size << 2) >> 2 != loca_size)) {
385
0
    return FONT_COMPRESSION_FAILURE();
386
0
  }
387
164
  std::vector<uint8_t> loca_content(loca_size * offset_size);
388
164
  uint8_t* dst = &loca_content[0];
389
164
  size_t offset = 0;
390
115k
  for (size_t i = 0; i < loca_values.size(); ++i) {
391
115k
    uint32_t value = loca_values[i];
392
115k
    if (index_format) {
393
73.9k
      offset = StoreU32(dst, offset, value);
394
73.9k
    } else {
395
41.3k
      offset = Store16(dst, offset, value >> 1);
396
41.3k
    }
397
115k
  }
398
164
  *checksum = ComputeULongSum(&loca_content[0], loca_content.size());
399
164
  if (PREDICT_FALSE(!out->Write(&loca_content[0], loca_content.size()))) {
400
0
    return FONT_COMPRESSION_FAILURE();
401
0
  }
402
164
  return true;
403
164
}
404
405
// Reconstruct entire glyf table based on transformed original
406
bool ReconstructGlyf(const uint8_t* data, Table* glyf_table,
407
                     uint32_t* glyf_checksum, Table * loca_table,
408
                     uint32_t* loca_checksum, WOFF2FontInfo* info,
409
1.42k
                     WOFF2Out* out) {
410
1.42k
  static const int kNumSubStreams = 7;
411
1.42k
  Buffer file(data, glyf_table->transform_length);
412
1.42k
  uint16_t version;
413
1.42k
  std::vector<std::pair<const uint8_t*, size_t> > substreams(kNumSubStreams);
414
1.42k
  const size_t glyf_start = out->Size();
415
416
1.42k
  if (PREDICT_FALSE(!file.ReadU16(&version))) {
417
30
    return FONT_COMPRESSION_FAILURE();
418
30
  }
419
420
1.39k
  uint16_t flags;
421
1.39k
  if (PREDICT_FALSE(!file.ReadU16(&flags))) {
422
7
    return FONT_COMPRESSION_FAILURE();
423
7
  }
424
1.38k
  bool has_overlap_bitmap = (flags & FLAG_OVERLAP_SIMPLE_BITMAP);
425
426
1.38k
  if (PREDICT_FALSE(!file.ReadU16(&info->num_glyphs) ||
427
1.38k
      !file.ReadU16(&info->index_format))) {
428
44
    return FONT_COMPRESSION_FAILURE();
429
44
  }
430
431
  // https://dev.w3.org/webfonts/WOFF2/spec/#conform-mustRejectLoca
432
  // dst_length here is origLength in the spec
433
1.34k
  uint32_t expected_loca_dst_length = (info->index_format ? 4 : 2)
434
1.34k
    * (static_cast<uint32_t>(info->num_glyphs) + 1);
435
1.34k
  if (PREDICT_FALSE(loca_table->dst_length != expected_loca_dst_length)) {
436
100
    return FONT_COMPRESSION_FAILURE();
437
100
  }
438
439
1.24k
  unsigned int offset = (2 + kNumSubStreams) * 4;
440
1.24k
  if (PREDICT_FALSE(offset > glyf_table->transform_length)) {
441
6
    return FONT_COMPRESSION_FAILURE();
442
6
  }
443
  // Invariant from here on: data_size >= offset
444
9.29k
  for (int i = 0; i < kNumSubStreams; ++i) {
445
8.15k
    uint32_t substream_size;
446
8.15k
    if (PREDICT_FALSE(!file.ReadU32(&substream_size))) {
447
0
      return FONT_COMPRESSION_FAILURE();
448
0
    }
449
8.15k
    if (PREDICT_FALSE(substream_size > glyf_table->transform_length - offset)) {
450
93
      return FONT_COMPRESSION_FAILURE();
451
93
    }
452
8.05k
    substreams[i] = std::make_pair(data + offset, substream_size);
453
8.05k
    offset += substream_size;
454
8.05k
  }
455
1.14k
  Buffer n_contour_stream(substreams[0].first, substreams[0].second);
456
1.14k
  Buffer n_points_stream(substreams[1].first, substreams[1].second);
457
1.14k
  Buffer flag_stream(substreams[2].first, substreams[2].second);
458
1.14k
  Buffer glyph_stream(substreams[3].first, substreams[3].second);
459
1.14k
  Buffer composite_stream(substreams[4].first, substreams[4].second);
460
1.14k
  Buffer bbox_stream(substreams[5].first, substreams[5].second);
461
1.14k
  Buffer instruction_stream(substreams[6].first, substreams[6].second);
462
463
1.14k
  const uint8_t* overlap_bitmap = nullptr;
464
1.14k
  unsigned int overlap_bitmap_length = 0;
465
1.14k
  if (has_overlap_bitmap) {
466
308
    overlap_bitmap_length = (info->num_glyphs + 7) >> 3;
467
308
    overlap_bitmap = data + offset;
468
308
    if (PREDICT_FALSE(overlap_bitmap_length >
469
308
                           glyf_table->transform_length - offset)) {
470
8
      return FONT_COMPRESSION_FAILURE();
471
8
    }
472
308
  }
473
474
1.13k
  std::vector<uint32_t> loca_values(info->num_glyphs + 1);
475
1.13k
  std::vector<unsigned int> n_points_vec;
476
1.13k
  std::unique_ptr<Point[]> points;
477
1.13k
  size_t points_size = 0;
478
1.13k
  const uint8_t* bbox_bitmap = bbox_stream.buffer();
479
  // Safe because num_glyphs is bounded
480
1.13k
  unsigned int bitmap_length = ((info->num_glyphs + 31) >> 5) << 2;
481
1.13k
  if (!bbox_stream.Skip(bitmap_length)) {
482
22
    return FONT_COMPRESSION_FAILURE();
483
22
  }
484
485
  // Temp buffer for glyph's.
486
1.11k
  size_t glyph_buf_size = kDefaultGlyphBuf;
487
1.11k
  std::unique_ptr<uint8_t[]> glyph_buf(new uint8_t[glyph_buf_size]);
488
489
1.11k
  info->x_mins.resize(info->num_glyphs);
490
161k
  for (unsigned int i = 0; i < info->num_glyphs; ++i) {
491
161k
    size_t glyph_size = 0;
492
161k
    uint16_t n_contours = 0;
493
161k
    bool have_bbox = false;
494
161k
    if (bbox_bitmap[i >> 3] & (0x80 >> (i & 7))) {
495
2.38k
      have_bbox = true;
496
2.38k
    }
497
161k
    if (PREDICT_FALSE(!n_contour_stream.ReadU16(&n_contours))) {
498
17
      return FONT_COMPRESSION_FAILURE();
499
17
    }
500
501
161k
    if (n_contours == 0xffff) {
502
      // composite glyph
503
1.21k
      bool have_instructions = false;
504
1.21k
      unsigned int instruction_size = 0;
505
1.21k
      if (PREDICT_FALSE(!have_bbox)) {
506
        // composite glyphs must have an explicit bbox
507
70
        return FONT_COMPRESSION_FAILURE();
508
70
      }
509
510
1.14k
      size_t composite_size;
511
1.14k
      if (PREDICT_FALSE(!SizeOfComposite(composite_stream, &composite_size,
512
1.14k
                                         &have_instructions))) {
513
43
        return FONT_COMPRESSION_FAILURE();
514
43
      }
515
1.10k
      if (have_instructions) {
516
472
        if (PREDICT_FALSE(!Read255UShort(&glyph_stream, &instruction_size))) {
517
2
          return FONT_COMPRESSION_FAILURE();
518
2
        }
519
472
      }
520
521
1.10k
      size_t size_needed = 12 + composite_size + instruction_size;
522
1.10k
      if (PREDICT_FALSE(glyph_buf_size < size_needed)) {
523
14
        glyph_buf.reset(new uint8_t[size_needed]);
524
14
        glyph_buf_size = size_needed;
525
14
      }
526
527
1.10k
      glyph_size = Store16(glyph_buf.get(), glyph_size, n_contours);
528
1.10k
      if (PREDICT_FALSE(!bbox_stream.Read(glyph_buf.get() + glyph_size, 8))) {
529
14
        return FONT_COMPRESSION_FAILURE();
530
14
      }
531
1.08k
      glyph_size += 8;
532
533
1.08k
      if (PREDICT_FALSE(!composite_stream.Read(glyph_buf.get() + glyph_size,
534
1.08k
            composite_size))) {
535
0
        return FONT_COMPRESSION_FAILURE();
536
0
      }
537
1.08k
      glyph_size += composite_size;
538
1.08k
      if (have_instructions) {
539
463
        glyph_size = Store16(glyph_buf.get(), glyph_size, instruction_size);
540
463
        if (PREDICT_FALSE(!instruction_stream.Read(glyph_buf.get() + glyph_size,
541
463
              instruction_size))) {
542
65
          return FONT_COMPRESSION_FAILURE();
543
65
        }
544
398
        glyph_size += instruction_size;
545
398
      }
546
160k
    } else if (n_contours > 0) {
547
      // simple glyph
548
126k
      n_points_vec.clear();
549
126k
      unsigned int total_n_points = 0;
550
126k
      unsigned int n_points_contour;
551
1.19M
      for (unsigned int j = 0; j < n_contours; ++j) {
552
1.06M
        if (PREDICT_FALSE(
553
1.06M
            !Read255UShort(&n_points_stream, &n_points_contour))) {
554
218
          return FONT_COMPRESSION_FAILURE();
555
218
        }
556
1.06M
        n_points_vec.push_back(n_points_contour);
557
1.06M
        if (PREDICT_FALSE(total_n_points + n_points_contour < total_n_points)) {
558
0
          return FONT_COMPRESSION_FAILURE();
559
0
        }
560
1.06M
        total_n_points += n_points_contour;
561
1.06M
      }
562
126k
      unsigned int flag_size = total_n_points;
563
126k
      if (PREDICT_FALSE(
564
126k
          flag_size > flag_stream.length() - flag_stream.offset())) {
565
105
        return FONT_COMPRESSION_FAILURE();
566
105
      }
567
126k
      const uint8_t* flags_buf = flag_stream.buffer() + flag_stream.offset();
568
126k
      const uint8_t* triplet_buf = glyph_stream.buffer() +
569
126k
        glyph_stream.offset();
570
126k
      size_t triplet_size = glyph_stream.length() - glyph_stream.offset();
571
126k
      size_t triplet_bytes_consumed = 0;
572
126k
      if (points_size < total_n_points) {
573
2.30k
        points_size = total_n_points;
574
2.30k
        points.reset(new Point[points_size]);
575
2.30k
      }
576
126k
      if (PREDICT_FALSE(!TripletDecode(flags_buf, triplet_buf, triplet_size,
577
126k
          total_n_points, points.get(), &triplet_bytes_consumed))) {
578
162
        return FONT_COMPRESSION_FAILURE();
579
162
      }
580
125k
      if (PREDICT_FALSE(!flag_stream.Skip(flag_size))) {
581
0
        return FONT_COMPRESSION_FAILURE();
582
0
      }
583
125k
      if (PREDICT_FALSE(!glyph_stream.Skip(triplet_bytes_consumed))) {
584
0
        return FONT_COMPRESSION_FAILURE();
585
0
      }
586
125k
      unsigned int instruction_size;
587
125k
      if (PREDICT_FALSE(!Read255UShort(&glyph_stream, &instruction_size))) {
588
19
        return FONT_COMPRESSION_FAILURE();
589
19
      }
590
591
125k
      if (PREDICT_FALSE(total_n_points >= (1 << 27)
592
125k
                        || instruction_size >= (1 << 30))) {
593
0
        return FONT_COMPRESSION_FAILURE();
594
0
      }
595
125k
      size_t size_needed = 12 + 2 * n_contours + 5 * total_n_points
596
125k
                           + instruction_size;
597
125k
      if (PREDICT_FALSE(glyph_buf_size < size_needed)) {
598
354
        glyph_buf.reset(new uint8_t[size_needed]);
599
354
        glyph_buf_size = size_needed;
600
354
      }
601
602
125k
      glyph_size = Store16(glyph_buf.get(), glyph_size, n_contours);
603
125k
      if (have_bbox) {
604
1.11k
        if (PREDICT_FALSE(!bbox_stream.Read(glyph_buf.get() + glyph_size, 8))) {
605
42
          return FONT_COMPRESSION_FAILURE();
606
42
        }
607
124k
      } else {
608
124k
        ComputeBbox(total_n_points, points.get(), glyph_buf.get());
609
124k
      }
610
125k
      glyph_size = kEndPtsOfContoursOffset;
611
125k
      int end_point = -1;
612
519k
      for (unsigned int contour_ix = 0; contour_ix < n_contours; ++contour_ix) {
613
393k
        end_point += n_points_vec[contour_ix];
614
393k
        if (PREDICT_FALSE(end_point >= 65536)) {
615
17
          return FONT_COMPRESSION_FAILURE();
616
17
        }
617
393k
        glyph_size = Store16(glyph_buf.get(), glyph_size, end_point);
618
393k
      }
619
620
125k
      glyph_size = Store16(glyph_buf.get(), glyph_size, instruction_size);
621
125k
      if (PREDICT_FALSE(!instruction_stream.Read(glyph_buf.get() + glyph_size,
622
125k
                                                 instruction_size))) {
623
159
        return FONT_COMPRESSION_FAILURE();
624
159
      }
625
125k
      glyph_size += instruction_size;
626
627
125k
      bool has_overlap_bit =
628
125k
          has_overlap_bitmap && overlap_bitmap[i >> 3] & (0x80 >> (i & 7));
629
630
125k
      if (PREDICT_FALSE(!StorePoints(
631
125k
              total_n_points, points.get(), n_contours, instruction_size,
632
125k
              has_overlap_bit, glyph_buf.get(), glyph_buf_size, &glyph_size))) {
633
0
        return FONT_COMPRESSION_FAILURE();
634
0
      }
635
125k
    } else {
636
      // n_contours == 0; empty glyph. Must NOT have a bbox.
637
33.9k
      if (PREDICT_FALSE(have_bbox)) {
638
#ifdef FONT_COMPRESSION_BIN
639
        fprintf(stderr, "Empty glyph has a bbox\n");
640
#endif
641
16
        return FONT_COMPRESSION_FAILURE();
642
16
      }
643
33.9k
    }
644
645
160k
    loca_values[i] = out->Size() - glyf_start;
646
160k
    if (PREDICT_FALSE(!out->Write(glyph_buf.get(), glyph_size))) {
647
0
      return FONT_COMPRESSION_FAILURE();
648
0
    }
649
650
    // TODO(user) Old code aligned glyphs ... but do we actually need to?
651
160k
    if (PREDICT_FALSE(!Pad4(out))) {
652
0
      return FONT_COMPRESSION_FAILURE();
653
0
    }
654
655
160k
    *glyf_checksum += ComputeULongSum(glyph_buf.get(), glyph_size);
656
657
    // We may need x_min to reconstruct 'hmtx'
658
160k
    if (n_contours > 0) {
659
126k
      Buffer x_min_buf(glyph_buf.get() + 2, 2);
660
126k
      if (PREDICT_FALSE(!x_min_buf.ReadS16(&info->x_mins[i]))) {
661
0
        return FONT_COMPRESSION_FAILURE();
662
0
      }
663
126k
    }
664
160k
  }
665
666
  // glyf_table dst_offset was set by ReconstructFont
667
164
  glyf_table->dst_length = out->Size() - glyf_table->dst_offset;
668
164
  loca_table->dst_offset = out->Size();
669
  // loca[n] will be equal the length of the glyph data ('glyf') table
670
164
  loca_values[info->num_glyphs] = glyf_table->dst_length;
671
164
  if (PREDICT_FALSE(!StoreLoca(loca_values, info->index_format, loca_checksum,
672
164
      out))) {
673
0
    return FONT_COMPRESSION_FAILURE();
674
0
  }
675
164
  loca_table->dst_length = out->Size() - loca_table->dst_offset;
676
677
164
  return true;
678
164
}
679
680
9.04k
Table* FindTable(std::vector<Table*>* tables, uint32_t tag) {
681
66.3k
  for (Table* table : *tables) {
682
66.3k
    if (table->tag == tag) {
683
4.71k
      return table;
684
4.71k
    }
685
66.3k
  }
686
4.33k
  return NULL;
687
9.04k
}
688
689
// Get numberOfHMetrics, https://www.microsoft.com/typography/otspec/hhea.htm
690
bool ReadNumHMetrics(const uint8_t* data, size_t data_size,
691
949
                     uint16_t* num_hmetrics) {
692
  // Skip 34 to reach 'hhea' numberOfHMetrics
693
949
  Buffer buffer(data, data_size);
694
949
  if (PREDICT_FALSE(!buffer.Skip(34) || !buffer.ReadU16(num_hmetrics))) {
695
21
    return FONT_COMPRESSION_FAILURE();
696
21
  }
697
928
  return true;
698
949
}
699
700
// http://dev.w3.org/webfonts/WOFF2/spec/Overview.html#hmtx_table_format
701
bool ReconstructTransformedHmtx(const uint8_t* transformed_buf,
702
                                size_t transformed_size,
703
                                uint16_t num_glyphs,
704
                                uint16_t num_hmetrics,
705
                                const std::vector<int16_t>& x_mins,
706
                                uint32_t* checksum,
707
153
                                WOFF2Out* out) {
708
153
  Buffer hmtx_buff_in(transformed_buf, transformed_size);
709
710
153
  uint8_t hmtx_flags;
711
153
  if (PREDICT_FALSE(!hmtx_buff_in.ReadU8(&hmtx_flags))) {
712
4
    return FONT_COMPRESSION_FAILURE();
713
4
  }
714
715
149
  std::vector<uint16_t> advance_widths;
716
149
  std::vector<int16_t> lsbs;
717
149
  bool has_proportional_lsbs = (hmtx_flags & 1) == 0;
718
149
  bool has_monospace_lsbs = (hmtx_flags & 2) == 0;
719
720
  // Bits 2-7 are reserved and MUST be zero.
721
149
  if ((hmtx_flags & 0xFC) != 0) {
722
#ifdef FONT_COMPRESSION_BIN
723
    fprintf(stderr, "Illegal hmtx flags; bits 2-7 must be 0\n");
724
#endif
725
31
    return FONT_COMPRESSION_FAILURE();
726
31
  }
727
728
  // you say you transformed but there is little evidence of it
729
118
  if (has_proportional_lsbs && has_monospace_lsbs) {
730
17
    return FONT_COMPRESSION_FAILURE();
731
17
  }
732
733
118
  assert(x_mins.size() == num_glyphs);
734
735
  // num_glyphs 0 is OK if there is no 'glyf' but cannot then xform 'hmtx'.
736
101
  if (PREDICT_FALSE(num_hmetrics > num_glyphs)) {
737
26
    return FONT_COMPRESSION_FAILURE();
738
26
  }
739
740
  // https://www.microsoft.com/typography/otspec/hmtx.htm
741
  // "...only one entry need be in the array, but that entry is required."
742
75
  if (PREDICT_FALSE(num_hmetrics < 1)) {
743
4
    return FONT_COMPRESSION_FAILURE();
744
4
  }
745
746
449
  for (uint16_t i = 0; i < num_hmetrics; i++) {
747
379
    uint16_t advance_width;
748
379
    if (PREDICT_FALSE(!hmtx_buff_in.ReadU16(&advance_width))) {
749
1
      return FONT_COMPRESSION_FAILURE();
750
1
    }
751
378
    advance_widths.push_back(advance_width);
752
378
  }
753
754
437
  for (uint16_t i = 0; i < num_hmetrics; i++) {
755
369
    int16_t lsb;
756
369
    if (has_proportional_lsbs) {
757
139
      if (PREDICT_FALSE(!hmtx_buff_in.ReadS16(&lsb))) {
758
2
        return FONT_COMPRESSION_FAILURE();
759
2
      }
760
230
    } else {
761
230
      lsb = x_mins[i];
762
230
    }
763
367
    lsbs.push_back(lsb);
764
367
  }
765
766
386
  for (uint16_t i = num_hmetrics; i < num_glyphs; i++) {
767
319
    int16_t lsb;
768
319
    if (has_monospace_lsbs) {
769
139
      if (PREDICT_FALSE(!hmtx_buff_in.ReadS16(&lsb))) {
770
1
        return FONT_COMPRESSION_FAILURE();
771
1
      }
772
180
    } else {
773
180
      lsb = x_mins[i];
774
180
    }
775
318
    lsbs.push_back(lsb);
776
318
  }
777
778
  // bake me a shiny new hmtx table
779
67
  uint32_t hmtx_output_size = 2 * num_glyphs + 2 * num_hmetrics;
780
67
  std::vector<uint8_t> hmtx_table(hmtx_output_size);
781
67
  uint8_t* dst = &hmtx_table[0];
782
67
  size_t dst_offset = 0;
783
742
  for (uint32_t i = 0; i < num_glyphs; i++) {
784
675
    if (i < num_hmetrics) {
785
360
      Store16(advance_widths[i], &dst_offset, dst);
786
360
    }
787
675
    Store16(lsbs[i], &dst_offset, dst);
788
675
  }
789
790
67
  *checksum = ComputeULongSum(&hmtx_table[0], hmtx_output_size);
791
67
  if (PREDICT_FALSE(!out->Write(&hmtx_table[0], hmtx_output_size))) {
792
0
    return FONT_COMPRESSION_FAILURE();
793
0
  }
794
795
67
  return true;
796
67
}
797
798
bool Woff2Uncompress(uint8_t* dst_buf, size_t dst_size,
799
11.5k
  const uint8_t* src_buf, size_t src_size) {
800
11.5k
  size_t uncompressed_size = dst_size;
801
11.5k
  BrotliDecoderResult result = BrotliDecoderDecompress(
802
11.5k
      src_size, src_buf, &uncompressed_size, dst_buf);
803
11.5k
  if (PREDICT_FALSE(result != BROTLI_DECODER_RESULT_SUCCESS ||
804
11.5k
                    uncompressed_size != dst_size)) {
805
9.17k
    return FONT_COMPRESSION_FAILURE();
806
9.17k
  }
807
2.42k
  return true;
808
11.5k
}
809
810
bool ReadTableDirectory(Buffer* file, std::vector<Table>* tables,
811
15.1k
    size_t num_tables) {
812
15.1k
  uint32_t src_offset = 0;
813
2.76M
  for (size_t i = 0; i < num_tables; ++i) {
814
2.75M
    Table* table = &(*tables)[i];
815
2.75M
    uint8_t flag_byte;
816
2.75M
    if (PREDICT_FALSE(!file->ReadU8(&flag_byte))) {
817
166
      return FONT_COMPRESSION_FAILURE();
818
166
    }
819
2.75M
    uint32_t tag;
820
2.75M
    if ((flag_byte & 0x3f) == 0x3f) {
821
26.1k
      if (PREDICT_FALSE(!file->ReadU32(&tag))) {
822
22
        return FONT_COMPRESSION_FAILURE();
823
22
      }
824
2.72M
    } else {
825
2.72M
      tag = kKnownTags[flag_byte & 0x3f];
826
2.72M
    }
827
2.75M
    uint32_t flags = 0;
828
2.75M
    uint8_t xform_version = (flag_byte >> 6) & 0x03;
829
830
    // 0 means xform for glyph/loca, non-0 for others
831
2.75M
    if (tag == kGlyfTableTag || tag == kLocaTableTag) {
832
36.3k
      if (xform_version == 0) {
833
12.4k
        flags |= kWoff2FlagsTransform;
834
12.4k
      }
835
2.71M
    } else if (xform_version != 0) {
836
199k
      flags |= kWoff2FlagsTransform;
837
199k
    }
838
2.75M
    flags |= xform_version;
839
840
2.75M
    uint32_t dst_length;
841
2.75M
    if (PREDICT_FALSE(!ReadBase128(file, &dst_length))) {
842
244
      return FONT_COMPRESSION_FAILURE();
843
244
    }
844
2.75M
    uint32_t transform_length = dst_length;
845
2.75M
    if ((flags & kWoff2FlagsTransform) != 0) {
846
211k
      if (PREDICT_FALSE(!ReadBase128(file, &transform_length))) {
847
36
        return FONT_COMPRESSION_FAILURE();
848
36
      }
849
211k
      if (PREDICT_FALSE(tag == kLocaTableTag && transform_length)) {
850
131
        return FONT_COMPRESSION_FAILURE();
851
131
      }
852
211k
    }
853
2.75M
    if (PREDICT_FALSE(src_offset + transform_length < src_offset)) {
854
4
      return FONT_COMPRESSION_FAILURE();
855
4
    }
856
2.75M
    table->src_offset = src_offset;
857
2.75M
    table->src_length = transform_length;
858
2.75M
    src_offset += transform_length;
859
860
2.75M
    table->tag = tag;
861
2.75M
    table->flags = flags;
862
2.75M
    table->transform_length = transform_length;
863
2.75M
    table->dst_length = dst_length;
864
2.75M
  }
865
14.5k
  return true;
866
15.1k
}
867
868
// Writes a single Offset Table entry
869
size_t StoreOffsetTable(uint8_t* result, size_t offset, uint32_t flavor,
870
19.7k
                        uint16_t num_tables) {
871
19.7k
  offset = StoreU32(result, offset, flavor);  // sfnt version
872
19.7k
  offset = Store16(result, offset, num_tables);  // num_tables
873
19.7k
  unsigned max_pow2 = 0;
874
74.2k
  while (1u << (max_pow2 + 1) <= num_tables) {
875
54.4k
    max_pow2++;
876
54.4k
  }
877
19.7k
  const uint16_t output_search_range = (1u << max_pow2) << 4;
878
19.7k
  offset = Store16(result, offset, output_search_range);  // searchRange
879
19.7k
  offset = Store16(result, offset, max_pow2);  // entrySelector
880
  // rangeShift
881
19.7k
  offset = Store16(result, offset, (num_tables << 4) - output_search_range);
882
19.7k
  return offset;
883
19.7k
}
884
885
1.61M
size_t StoreTableEntry(uint8_t* result, uint32_t offset, uint32_t tag) {
886
1.61M
  offset = StoreU32(result, offset, tag);
887
1.61M
  offset = StoreU32(result, offset, 0);
888
1.61M
  offset = StoreU32(result, offset, 0);
889
1.61M
  offset = StoreU32(result, offset, 0);
890
1.61M
  return offset;
891
1.61M
}
892
893
// First table goes after all the headers, table directory, etc
894
27.2k
uint64_t ComputeOffsetToFirstTable(const WOFF2Header& hdr) {
895
27.2k
  uint64_t offset = kSfntHeaderSize +
896
27.2k
    kSfntEntrySize * static_cast<uint64_t>(hdr.num_tables);
897
27.2k
  if (hdr.header_version) {
898
997
    offset = CollectionHeaderSize(hdr.header_version, hdr.ttc_fonts.size())
899
997
      + kSfntHeaderSize * hdr.ttc_fonts.size();
900
15.3k
    for (const auto& ttc_font : hdr.ttc_fonts) {
901
15.3k
      offset += kSfntEntrySize * ttc_font.table_indices.size();
902
15.3k
    }
903
997
  }
904
27.2k
  return offset;
905
27.2k
}
906
907
3.14k
std::vector<Table*> Tables(WOFF2Header* hdr, size_t font_index) {
908
3.14k
  std::vector<Table*> tables;
909
3.14k
  if (PREDICT_FALSE(hdr->header_version)) {
910
5.66k
    for (auto index : hdr->ttc_fonts[font_index].table_indices) {
911
5.66k
      tables.push_back(&hdr->tables[index]);
912
5.66k
    }
913
2.21k
  } else {
914
26.7k
    for (auto& table : hdr->tables) {
915
26.7k
      tables.push_back(&table);
916
26.7k
    }
917
2.21k
  }
918
3.14k
  return tables;
919
3.14k
}
920
921
// Offset tables assumed to have been written in with 0's initially.
922
// WOFF2Header isn't const so we can use [] instead of at() (which upsets FF)
923
bool ReconstructFont(uint8_t* transformed_buf,
924
                     const uint32_t transformed_buf_size,
925
                     RebuildMetadata* metadata,
926
                     WOFF2Header* hdr,
927
                     size_t font_index,
928
3.14k
                     WOFF2Out* out) {
929
3.14k
  size_t dest_offset = out->Size();
930
3.14k
  uint8_t table_entry[12];
931
3.14k
  WOFF2FontInfo* info = &metadata->font_infos[font_index];
932
3.14k
  std::vector<Table*> tables = Tables(hdr, font_index);
933
934
  // 'glyf' without 'loca' doesn't make sense
935
3.14k
  const Table* glyf_table = FindTable(&tables, kGlyfTableTag);
936
3.14k
  const Table* loca_table = FindTable(&tables, kLocaTableTag);
937
3.14k
  if (PREDICT_FALSE(static_cast<bool>(glyf_table) !=
938
3.14k
                    static_cast<bool>(loca_table))) {
939
#ifdef FONT_COMPRESSION_BIN
940
      fprintf(stderr, "Cannot have just one of glyf/loca\n");
941
#endif
942
7
    return FONT_COMPRESSION_FAILURE();
943
7
  }
944
945
3.14k
  if (glyf_table != NULL) {
946
1.48k
    if (PREDICT_FALSE((glyf_table->flags & kWoff2FlagsTransform)
947
1.48k
                      != (loca_table->flags & kWoff2FlagsTransform))) {
948
#ifdef FONT_COMPRESSION_BIN
949
      fprintf(stderr, "Cannot transform just one of glyf/loca\n");
950
#endif
951
3
      return FONT_COMPRESSION_FAILURE();
952
3
    }
953
1.48k
  }
954
955
3.13k
  uint32_t font_checksum = metadata->header_checksum;
956
3.13k
  if (hdr->header_version) {
957
929
    font_checksum = hdr->ttc_fonts[font_index].header_checksum;
958
929
  }
959
960
3.13k
  uint32_t loca_checksum = 0;
961
23.9k
  for (size_t i = 0; i < tables.size(); i++) {
962
22.6k
    Table& table = *tables[i];
963
964
22.6k
    std::pair<uint32_t, uint32_t> checksum_key = {table.tag, table.src_offset};
965
22.6k
    bool reused = metadata->checksums.find(checksum_key)
966
22.6k
               != metadata->checksums.end();
967
22.6k
    if (PREDICT_FALSE(font_index == 0 && reused)) {
968
32
      return FONT_COMPRESSION_FAILURE();
969
32
    }
970
971
    // TODO(user) a collection with optimized hmtx that reused glyf/loca
972
    // would fail. We don't optimize hmtx for collections yet.
973
22.6k
    if (PREDICT_FALSE(static_cast<uint64_t>(table.src_offset) + table.src_length
974
22.6k
        > transformed_buf_size)) {
975
0
      return FONT_COMPRESSION_FAILURE();
976
0
    }
977
978
22.6k
    if (table.tag == kHheaTableTag) {
979
949
      if (!ReadNumHMetrics(transformed_buf + table.src_offset,
980
949
          table.src_length, &info->num_hmetrics)) {
981
21
        return FONT_COMPRESSION_FAILURE();
982
21
      }
983
949
    }
984
985
22.5k
    uint32_t checksum = 0;
986
22.5k
    if (!reused) {
987
18.0k
      if ((table.flags & kWoff2FlagsTransform) != kWoff2FlagsTransform) {
988
15.9k
        if (table.tag == kHeadTableTag) {
989
370
          if (PREDICT_FALSE(table.src_length < 12)) {
990
24
            return FONT_COMPRESSION_FAILURE();
991
24
          }
992
          // checkSumAdjustment = 0
993
346
          StoreU32(transformed_buf + table.src_offset, 8, 0);
994
346
        }
995
15.9k
        table.dst_offset = dest_offset;
996
15.9k
        checksum = ComputeULongSum(transformed_buf + table.src_offset,
997
15.9k
                                   table.src_length);
998
15.9k
        if (PREDICT_FALSE(!out->Write(transformed_buf + table.src_offset,
999
15.9k
            table.src_length))) {
1000
0
          return FONT_COMPRESSION_FAILURE();
1001
0
        }
1002
15.9k
      } else {
1003
2.09k
        if (table.tag == kGlyfTableTag) {
1004
1.42k
          table.dst_offset = dest_offset;
1005
1006
1.42k
          Table* loca_table = FindTable(&tables, kLocaTableTag);
1007
1.42k
          if (PREDICT_FALSE(!ReconstructGlyf(transformed_buf + table.src_offset,
1008
1.42k
              &table, &checksum, loca_table, &loca_checksum, info, out))) {
1009
1.25k
            return FONT_COMPRESSION_FAILURE();
1010
1.25k
          }
1011
1.42k
        } else if (table.tag == kLocaTableTag) {
1012
          // All the work was done by ReconstructGlyf. We already know checksum.
1013
193
          checksum = loca_checksum;
1014
481
        } else if (table.tag == kHmtxTableTag) {
1015
153
          table.dst_offset = dest_offset;
1016
          // Tables are sorted so all the info we need has been gathered.
1017
153
          if (PREDICT_FALSE(!ReconstructTransformedHmtx(
1018
153
              transformed_buf + table.src_offset, table.src_length,
1019
153
              info->num_glyphs, info->num_hmetrics, info->x_mins, &checksum,
1020
153
              out))) {
1021
86
            return FONT_COMPRESSION_FAILURE();
1022
86
          }
1023
328
        } else {
1024
328
          return FONT_COMPRESSION_FAILURE();  // transform unknown
1025
328
        }
1026
2.09k
      }
1027
16.3k
      metadata->checksums[checksum_key] = checksum;
1028
16.3k
    } else {
1029
4.54k
      checksum = metadata->checksums[checksum_key];
1030
4.54k
    }
1031
20.8k
    font_checksum += checksum;
1032
1033
    // update the table entry with real values.
1034
20.8k
    StoreU32(table_entry, 0, checksum);
1035
20.8k
    StoreU32(table_entry, 4, table.dst_offset);
1036
20.8k
    StoreU32(table_entry, 8, table.dst_length);
1037
20.8k
    if (PREDICT_FALSE(!out->Write(table_entry,
1038
20.8k
        info->table_entry_by_tag[table.tag] + 4, 12))) {
1039
0
      return FONT_COMPRESSION_FAILURE();
1040
0
    }
1041
1042
    // We replaced 0's. Update overall checksum.
1043
20.8k
    font_checksum += ComputeULongSum(table_entry, 12);
1044
1045
20.8k
    if (PREDICT_FALSE(!Pad4(out))) {
1046
0
      return FONT_COMPRESSION_FAILURE();
1047
0
    }
1048
1049
20.8k
    if (PREDICT_FALSE(static_cast<uint64_t>(table.dst_offset + table.dst_length)
1050
20.8k
        > out->Size())) {
1051
56
      return FONT_COMPRESSION_FAILURE();
1052
56
    }
1053
20.8k
    dest_offset = out->Size();
1054
20.8k
  }
1055
1056
  // Update 'head' checkSumAdjustment. We already set it to 0 and summed font.
1057
1.33k
  Table* head_table = FindTable(&tables, kHeadTableTag);
1058
1.33k
  if (head_table) {
1059
308
    if (PREDICT_FALSE(head_table->dst_length < 12)) {
1060
1
      return FONT_COMPRESSION_FAILURE();
1061
1
    }
1062
307
    uint8_t checksum_adjustment[4];
1063
307
    StoreU32(checksum_adjustment, 0, 0xB1B0AFBA - font_checksum);
1064
307
    if (PREDICT_FALSE(!out->Write(checksum_adjustment,
1065
307
                                  head_table->dst_offset + 8, 4))) {
1066
0
      return FONT_COMPRESSION_FAILURE();
1067
0
    }
1068
307
  }
1069
1070
1.33k
  return true;
1071
1.33k
}
1072
1073
15.9k
bool ReadWOFF2Header(const uint8_t* data, size_t length, WOFF2Header* hdr) {
1074
15.9k
  Buffer file(data, length);
1075
1076
15.9k
  uint32_t signature;
1077
15.9k
  if (PREDICT_FALSE(!file.ReadU32(&signature) || signature != kWoff2Signature ||
1078
15.9k
      !file.ReadU32(&hdr->flavor))) {
1079
176
    return FONT_COMPRESSION_FAILURE();
1080
176
  }
1081
1082
  // TODO(user): Should call IsValidVersionTag() here.
1083
1084
15.7k
  uint32_t reported_length;
1085
15.7k
  if (PREDICT_FALSE(
1086
15.7k
      !file.ReadU32(&reported_length) || length != reported_length)) {
1087
146
    return FONT_COMPRESSION_FAILURE();
1088
146
  }
1089
15.5k
  if (PREDICT_FALSE(!file.ReadU16(&hdr->num_tables) || !hdr->num_tables)) {
1090
6
    return FONT_COMPRESSION_FAILURE();
1091
6
  }
1092
1093
  // We don't care about these fields of the header:
1094
  //   uint16_t reserved
1095
  //   uint32_t total_sfnt_size, we don't believe this, will compute later
1096
15.5k
  if (PREDICT_FALSE(!file.Skip(6))) {
1097
42
    return FONT_COMPRESSION_FAILURE();
1098
42
  }
1099
15.5k
  if (PREDICT_FALSE(!file.ReadU32(&hdr->compressed_length))) {
1100
8
    return FONT_COMPRESSION_FAILURE();
1101
8
  }
1102
  // We don't care about these fields of the header:
1103
  //   uint16_t major_version, minor_version
1104
15.5k
  if (PREDICT_FALSE(!file.Skip(2 * 2))) {
1105
6
    return FONT_COMPRESSION_FAILURE();
1106
6
  }
1107
15.5k
  uint32_t meta_offset;
1108
15.5k
  uint32_t meta_length;
1109
15.5k
  uint32_t meta_length_orig;
1110
15.5k
  if (PREDICT_FALSE(!file.ReadU32(&meta_offset) ||
1111
15.5k
      !file.ReadU32(&meta_length) ||
1112
15.5k
      !file.ReadU32(&meta_length_orig))) {
1113
18
    return FONT_COMPRESSION_FAILURE();
1114
18
  }
1115
15.4k
  if (meta_offset) {
1116
602
    if (PREDICT_FALSE(
1117
602
        meta_offset >= length || length - meta_offset < meta_length)) {
1118
173
      return FONT_COMPRESSION_FAILURE();
1119
173
    }
1120
602
  }
1121
15.3k
  uint32_t priv_offset;
1122
15.3k
  uint32_t priv_length;
1123
15.3k
  if (PREDICT_FALSE(!file.ReadU32(&priv_offset) ||
1124
15.3k
      !file.ReadU32(&priv_length))) {
1125
26
    return FONT_COMPRESSION_FAILURE();
1126
26
  }
1127
15.2k
  if (priv_offset) {
1128
548
    if (PREDICT_FALSE(
1129
548
        priv_offset >= length || length - priv_offset < priv_length)) {
1130
166
      return FONT_COMPRESSION_FAILURE();
1131
166
    }
1132
548
  }
1133
15.1k
  hdr->tables.resize(hdr->num_tables);
1134
15.1k
  if (PREDICT_FALSE(!ReadTableDirectory(
1135
15.1k
          &file, &hdr->tables, hdr->num_tables))) {
1136
603
    return FONT_COMPRESSION_FAILURE();
1137
603
  }
1138
1139
  // Before we sort for output the last table end is the uncompressed size.
1140
14.5k
  Table& last_table = hdr->tables.back();
1141
14.5k
  hdr->uncompressed_size = last_table.src_offset + last_table.src_length;
1142
14.5k
  if (PREDICT_FALSE(hdr->uncompressed_size < last_table.src_offset)) {
1143
0
    return FONT_COMPRESSION_FAILURE();
1144
0
  }
1145
1146
14.5k
  hdr->header_version = 0;
1147
1148
14.5k
  if (hdr->flavor == kTtcFontFlavor) {
1149
1.16k
    if (PREDICT_FALSE(!file.ReadU32(&hdr->header_version))) {
1150
20
      return FONT_COMPRESSION_FAILURE();
1151
20
    }
1152
1.14k
    if (PREDICT_FALSE(hdr->header_version != 0x00010000
1153
1.14k
                   && hdr->header_version != 0x00020000)) {
1154
147
      return FONT_COMPRESSION_FAILURE();
1155
147
    }
1156
996
    uint32_t num_fonts;
1157
996
    if (PREDICT_FALSE(!Read255UShort(&file, &num_fonts) || !num_fonts)) {
1158
15
      return FONT_COMPRESSION_FAILURE();
1159
15
    }
1160
981
    hdr->ttc_fonts.resize(num_fonts);
1161
1162
11.4k
    for (uint32_t i = 0; i < num_fonts; i++) {
1163
10.9k
      TtcFont& ttc_font = hdr->ttc_fonts[i];
1164
10.9k
      uint32_t num_tables;
1165
10.9k
      if (PREDICT_FALSE(!Read255UShort(&file, &num_tables) || !num_tables)) {
1166
109
        return FONT_COMPRESSION_FAILURE();
1167
109
      }
1168
10.8k
      if (PREDICT_FALSE(!file.ReadU32(&ttc_font.flavor))) {
1169
51
        return FONT_COMPRESSION_FAILURE();
1170
51
      }
1171
1172
10.7k
      ttc_font.table_indices.resize(num_tables);
1173
1174
1175
10.7k
      unsigned int glyf_idx = 0;
1176
10.7k
      unsigned int loca_idx = 0;
1177
1178
391k
      for (uint32_t j = 0; j < num_tables; j++) {
1179
380k
        unsigned int table_idx;
1180
380k
        if (PREDICT_FALSE(!Read255UShort(&file, &table_idx)) ||
1181
380k
            table_idx >= hdr->tables.size()) {
1182
281
          return FONT_COMPRESSION_FAILURE();
1183
281
        }
1184
380k
        ttc_font.table_indices[j] = table_idx;
1185
1186
380k
        const Table& table = hdr->tables[table_idx];
1187
380k
        if (table.tag == kLocaTableTag) {
1188
6.50k
          loca_idx = table_idx;
1189
6.50k
        }
1190
380k
        if (table.tag == kGlyfTableTag) {
1191
1.30k
          glyf_idx = table_idx;
1192
1.30k
        }
1193
1194
380k
      }
1195
1196
      // if we have both glyf and loca make sure they are consecutive
1197
      // if we have just one we'll reject the font elsewhere
1198
10.4k
      if (glyf_idx > 0 || loca_idx > 0) {
1199
1.07k
        if (PREDICT_FALSE(glyf_idx > loca_idx || loca_idx - glyf_idx != 1)) {
1200
#ifdef FONT_COMPRESSION_BIN
1201
        fprintf(stderr, "TTC font %d has non-consecutive glyf/loca\n", i);
1202
#endif
1203
33
          return FONT_COMPRESSION_FAILURE();
1204
33
        }
1205
1.07k
      }
1206
10.4k
    }
1207
981
  }
1208
1209
13.8k
  const uint64_t first_table_offset = ComputeOffsetToFirstTable(*hdr);
1210
1211
13.8k
  hdr->compressed_offset = file.offset();
1212
13.8k
  if (PREDICT_FALSE(hdr->compressed_offset >
1213
13.8k
                    std::numeric_limits<uint32_t>::max())) {
1214
0
    return FONT_COMPRESSION_FAILURE();
1215
0
  }
1216
13.8k
  uint64_t src_offset = Round4(hdr->compressed_offset + hdr->compressed_length);
1217
13.8k
  uint64_t dst_offset = first_table_offset;
1218
1219
1220
13.8k
  if (PREDICT_FALSE(src_offset > length)) {
1221
#ifdef FONT_COMPRESSION_BIN
1222
    fprintf(stderr, "offset fail; src_offset %" PRIu64 " length %lu "
1223
      "dst_offset %" PRIu64 "\n",
1224
      src_offset, length, dst_offset);
1225
#endif
1226
284
    return FONT_COMPRESSION_FAILURE();
1227
284
  }
1228
13.5k
  if (meta_offset) {
1229
124
    if (PREDICT_FALSE(src_offset != meta_offset)) {
1230
64
      return FONT_COMPRESSION_FAILURE();
1231
64
    }
1232
60
    src_offset = Round4(meta_offset + meta_length);
1233
60
    if (PREDICT_FALSE(src_offset > std::numeric_limits<uint32_t>::max())) {
1234
0
      return FONT_COMPRESSION_FAILURE();
1235
0
    }
1236
60
  }
1237
1238
13.5k
  if (priv_offset) {
1239
111
    if (PREDICT_FALSE(src_offset != priv_offset)) {
1240
51
      return FONT_COMPRESSION_FAILURE();
1241
51
    }
1242
60
    src_offset = Round4(priv_offset + priv_length);
1243
60
    if (PREDICT_FALSE(src_offset > std::numeric_limits<uint32_t>::max())) {
1244
0
      return FONT_COMPRESSION_FAILURE();
1245
0
    }
1246
60
  }
1247
1248
13.4k
  if (PREDICT_FALSE(src_offset != Round4(length))) {
1249
80
    return FONT_COMPRESSION_FAILURE();
1250
80
  }
1251
1252
13.3k
  return true;
1253
13.4k
}
1254
1255
// Write everything before the actual table data
1256
bool WriteHeaders(const uint8_t* data, size_t length, RebuildMetadata* metadata,
1257
13.3k
                  WOFF2Header* hdr, WOFF2Out* out) {
1258
13.3k
  std::vector<uint8_t> output(ComputeOffsetToFirstTable(*hdr), 0);
1259
1260
  // Re-order tables in output (OTSpec) order
1261
13.3k
  std::vector<Table> sorted_tables(hdr->tables);
1262
13.3k
  if (hdr->header_version) {
1263
    // collection; we have to sort the table offset vector in each font
1264
6.86k
    for (auto& ttc_font : hdr->ttc_fonts) {
1265
6.86k
      std::map<uint32_t, uint16_t> sorted_index_by_tag;
1266
221k
      for (auto table_index : ttc_font.table_indices) {
1267
221k
        sorted_index_by_tag[hdr->tables[table_index].tag] = table_index;
1268
221k
      }
1269
6.86k
      uint16_t index = 0;
1270
59.9k
      for (auto& i : sorted_index_by_tag) {
1271
59.9k
        ttc_font.table_indices[index++] = i.second;
1272
59.9k
      }
1273
6.86k
    }
1274
12.9k
  } else {
1275
    // non-collection; we can just sort the tables
1276
12.9k
    std::sort(sorted_tables.begin(), sorted_tables.end());
1277
12.9k
  }
1278
1279
  // Start building the font
1280
13.3k
  uint8_t* result = &output[0];
1281
13.3k
  size_t offset = 0;
1282
13.3k
  if (hdr->header_version) {
1283
    // TTC header
1284
490
    offset = StoreU32(result, offset, hdr->flavor);  // TAG TTCTag
1285
490
    offset = StoreU32(result, offset, hdr->header_version);  // FIXED Version
1286
490
    offset = StoreU32(result, offset, hdr->ttc_fonts.size());  // ULONG numFonts
1287
    // Space for ULONG OffsetTable[numFonts] (zeroed initially)
1288
490
    size_t offset_table = offset;  // keep start of offset table for later
1289
7.35k
    for (size_t i = 0; i < hdr->ttc_fonts.size(); i++) {
1290
6.86k
      offset = StoreU32(result, offset, 0);  // will fill real values in later
1291
6.86k
    }
1292
    // space for DSIG fields for header v2
1293
490
    if (hdr->header_version == 0x00020000) {
1294
298
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigTag
1295
298
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigLength
1296
298
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigOffset
1297
298
    }
1298
1299
    // write Offset Tables and store the location of each in TTC Header
1300
490
    metadata->font_infos.resize(hdr->ttc_fonts.size());
1301
7.35k
    for (size_t i = 0; i < hdr->ttc_fonts.size(); i++) {
1302
6.86k
      TtcFont& ttc_font = hdr->ttc_fonts[i];
1303
1304
      // write Offset Table location into TTC Header
1305
6.86k
      offset_table = StoreU32(result, offset_table, offset);
1306
1307
      // write the actual offset table so our header doesn't lie
1308
6.86k
      ttc_font.dst_offset = offset;
1309
6.86k
      offset = StoreOffsetTable(result, offset, ttc_font.flavor,
1310
6.86k
                                ttc_font.table_indices.size());
1311
1312
221k
      for (const auto table_index : ttc_font.table_indices) {
1313
221k
        uint32_t tag = hdr->tables[table_index].tag;
1314
221k
        metadata->font_infos[i].table_entry_by_tag[tag] = offset;
1315
221k
        offset = StoreTableEntry(result, offset, tag);
1316
221k
      }
1317
1318
6.86k
      ttc_font.header_checksum = ComputeULongSum(&output[ttc_font.dst_offset],
1319
6.86k
                                                 offset - ttc_font.dst_offset);
1320
6.86k
    }
1321
12.9k
  } else {
1322
12.9k
    metadata->font_infos.resize(1);
1323
12.9k
    offset = StoreOffsetTable(result, offset, hdr->flavor, hdr->num_tables);
1324
1.41M
    for (uint16_t i = 0; i < hdr->num_tables; ++i) {
1325
1.39M
      metadata->font_infos[0].table_entry_by_tag[sorted_tables[i].tag] = offset;
1326
1.39M
      offset = StoreTableEntry(result, offset, sorted_tables[i].tag);
1327
1.39M
    }
1328
12.9k
  }
1329
1330
13.3k
  if (PREDICT_FALSE(!out->Write(&output[0], output.size()))) {
1331
0
    return FONT_COMPRESSION_FAILURE();
1332
0
  }
1333
13.3k
  metadata->header_checksum = ComputeULongSum(&output[0], output.size());
1334
13.3k
  return true;
1335
13.3k
}
1336
1337
}  // namespace
1338
1339
7.47k
size_t ComputeWOFF2FinalSize(const uint8_t* data, size_t length) {
1340
7.47k
  Buffer file(data, length);
1341
7.47k
  uint32_t total_length;
1342
1343
7.47k
  if (!file.Skip(16) ||
1344
7.35k
      !file.ReadU32(&total_length)) {
1345
122
    return 0;
1346
122
  }
1347
7.35k
  return total_length;
1348
7.47k
}
1349
1350
bool ConvertWOFF2ToTTF(uint8_t *result, size_t result_length,
1351
0
                       const uint8_t *data, size_t length) {
1352
0
  WOFF2MemoryOut out(result, result_length);
1353
0
  return ConvertWOFF2ToTTF(data, length, &out);
1354
0
}
1355
1356
bool ConvertWOFF2ToTTF(const uint8_t* data, size_t length,
1357
15.9k
                       WOFF2Out* out) {
1358
15.9k
  RebuildMetadata metadata;
1359
15.9k
  WOFF2Header hdr;
1360
15.9k
  if (!ReadWOFF2Header(data, length, &hdr)) {
1361
2.50k
    return FONT_COMPRESSION_FAILURE();
1362
2.50k
  }
1363
1364
13.3k
  if (!WriteHeaders(data, length, &metadata, &hdr, out)) {
1365
0
    return FONT_COMPRESSION_FAILURE();
1366
0
  }
1367
1368
13.3k
  const float compression_ratio = (float) hdr.uncompressed_size / length;
1369
13.3k
  if (compression_ratio > kMaxPlausibleCompressionRatio) {
1370
#ifdef FONT_COMPRESSION_BIN
1371
    fprintf(stderr, "Implausible compression ratio %.01f\n", compression_ratio);
1372
#endif
1373
1.68k
    return FONT_COMPRESSION_FAILURE();
1374
1.68k
  }
1375
1376
11.7k
  const uint8_t* src_buf = data + hdr.compressed_offset;
1377
11.7k
  std::vector<uint8_t> uncompressed_buf(hdr.uncompressed_size);
1378
11.7k
  if (PREDICT_FALSE(hdr.uncompressed_size < 1)) {
1379
113
    return FONT_COMPRESSION_FAILURE();
1380
113
  }
1381
11.5k
  if (PREDICT_FALSE(!Woff2Uncompress(&uncompressed_buf[0],
1382
11.5k
                                     hdr.uncompressed_size, src_buf,
1383
11.5k
                                     hdr.compressed_length))) {
1384
9.17k
    return FONT_COMPRESSION_FAILURE();
1385
9.17k
  }
1386
1387
3.75k
  for (size_t i = 0; i < metadata.font_infos.size(); i++) {
1388
3.14k
    if (PREDICT_FALSE(!ReconstructFont(&uncompressed_buf[0],
1389
3.14k
                                       hdr.uncompressed_size,
1390
3.14k
                                       &metadata, &hdr, i, out))) {
1391
1.81k
      return FONT_COMPRESSION_FAILURE();
1392
1.81k
    }
1393
3.14k
  }
1394
1395
604
  return true;
1396
2.42k
}
1397
1398
} // namespace woff2