Coverage Report

Created: 2025-07-12 06:32

/src/woff2/src/woff2_dec.cc
Line
Count
Source (jump to first uncovered line)
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
34.6M
int WithSign(int flag, int baseval) {
110
  // Precondition: 0 <= baseval < 65536 (to avoid integer overflow)
111
34.6M
  return (flag & 1) ? baseval : -baseval;
112
34.6M
}
113
114
43.2M
bool _SafeIntAddition(int a, int b, int* result) {
115
43.2M
  if (PREDICT_FALSE(
116
43.2M
          ((a > 0) && (b > std::numeric_limits<int>::max() - a)) ||
117
43.2M
          ((a < 0) && (b < std::numeric_limits<int>::min() - a)))) {
118
58
    return false;
119
58
  }
120
43.2M
  *result = a + b;
121
43.2M
  return true;
122
43.2M
}
123
124
bool TripletDecode(const uint8_t* flags_in, const uint8_t* in, size_t in_size,
125
139k
    unsigned int n_points, Point* result, size_t* in_bytes_consumed) {
126
139k
  int x = 0;
127
139k
  int y = 0;
128
129
139k
  if (PREDICT_FALSE(n_points > in_size)) {
130
28
    return FONT_COMPRESSION_FAILURE();
131
28
  }
132
139k
  unsigned int triplet_index = 0;
133
134
21.7M
  for (unsigned int i = 0; i < n_points; ++i) {
135
21.6M
    uint8_t flag = flags_in[i];
136
21.6M
    bool on_curve = !(flag >> 7);
137
21.6M
    flag &= 0x7f;
138
21.6M
    unsigned int n_data_bytes;
139
21.6M
    if (flag < 84) {
140
14.7M
      n_data_bytes = 1;
141
14.7M
    } else if (flag < 120) {
142
2.56M
      n_data_bytes = 2;
143
4.28M
    } else if (flag < 124) {
144
215k
      n_data_bytes = 3;
145
4.07M
    } else {
146
4.07M
      n_data_bytes = 4;
147
4.07M
    }
148
21.6M
    if (PREDICT_FALSE(triplet_index + n_data_bytes > in_size ||
149
21.6M
        triplet_index + n_data_bytes < triplet_index)) {
150
41
      return FONT_COMPRESSION_FAILURE();
151
41
    }
152
21.6M
    int dx, dy;
153
21.6M
    if (flag < 10) {
154
6.94M
      dx = 0;
155
6.94M
      dy = WithSign(flag, ((flag & 14) << 7) + in[triplet_index]);
156
14.7M
    } else if (flag < 20) {
157
1.73M
      dx = WithSign(flag, (((flag - 10) & 14) << 7) + in[triplet_index]);
158
1.73M
      dy = 0;
159
12.9M
    } else if (flag < 84) {
160
6.11M
      int b0 = flag - 20;
161
6.11M
      int b1 = in[triplet_index];
162
6.11M
      dx = WithSign(flag, 1 + (b0 & 0x30) + (b1 >> 4));
163
6.11M
      dy = WithSign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f));
164
6.85M
    } else if (flag < 120) {
165
2.56M
      int b0 = flag - 84;
166
2.56M
      dx = WithSign(flag, 1 + ((b0 / 12) << 8) + in[triplet_index]);
167
2.56M
      dy = WithSign(flag >> 1,
168
2.56M
                    1 + (((b0 % 12) >> 2) << 8) + in[triplet_index + 1]);
169
4.28M
    } 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
4.07M
    } else {
174
4.07M
      dx = WithSign(flag, (in[triplet_index] << 8) + in[triplet_index + 1]);
175
4.07M
      dy = WithSign(flag >> 1,
176
4.07M
          (in[triplet_index + 2] << 8) + in[triplet_index + 3]);
177
4.07M
    }
178
21.6M
    triplet_index += n_data_bytes;
179
21.6M
    if (!_SafeIntAddition(x, dx, &x)) {
180
31
      return false;
181
31
    }
182
21.6M
    if (!_SafeIntAddition(y, dy, &y)) {
183
27
      return false;
184
27
    }
185
21.6M
    *result++ = {x, y, on_curve};
186
21.6M
  }
187
139k
  *in_bytes_consumed = triplet_index;
188
139k
  return true;
189
139k
}
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
139k
                 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
139k
  unsigned int flag_offset = kEndPtsOfContoursOffset + 2 * n_contours + 2 +
200
139k
    instruction_length;
201
139k
  int last_flag = -1;
202
139k
  int repeat_count = 0;
203
139k
  int last_x = 0;
204
139k
  int last_y = 0;
205
139k
  unsigned int x_bytes = 0;
206
139k
  unsigned int y_bytes = 0;
207
208
9.76M
  for (unsigned int i = 0; i < n_points; ++i) {
209
9.62M
    const Point& point = points[i];
210
9.62M
    int flag = point.on_curve ? kGlyfOnCurve : 0;
211
9.62M
    if (has_overlap_bit && i == 0) {
212
222
      flag |= kOverlapSimple;
213
222
    }
214
215
9.62M
    int dx = point.x - last_x;
216
9.62M
    int dy = point.y - last_y;
217
9.62M
    if (dx == 0) {
218
5.05M
      flag |= kGlyfThisXIsSame;
219
5.05M
    } else if (dx > -256 && dx < 256) {
220
3.76M
      flag |= kGlyfXShort | (dx > 0 ? kGlyfThisXIsSame : 0);
221
3.76M
      x_bytes += 1;
222
3.76M
    } else {
223
809k
      x_bytes += 2;
224
809k
    }
225
9.62M
    if (dy == 0) {
226
4.02M
      flag |= kGlyfThisYIsSame;
227
5.60M
    } else if (dy > -256 && dy < 256) {
228
4.16M
      flag |= kGlyfYShort | (dy > 0 ? kGlyfThisYIsSame : 0);
229
4.16M
      y_bytes += 1;
230
4.16M
    } else {
231
1.44M
      y_bytes += 2;
232
1.44M
    }
233
234
9.62M
    if (flag == last_flag && repeat_count != 255) {
235
3.33M
      dst[flag_offset - 1] |= kGlyfRepeat;
236
3.33M
      repeat_count++;
237
6.29M
    } else {
238
6.29M
      if (repeat_count != 0) {
239
855k
        if (PREDICT_FALSE(flag_offset >= dst_size)) {
240
0
          return FONT_COMPRESSION_FAILURE();
241
0
        }
242
855k
        dst[flag_offset++] = repeat_count;
243
855k
      }
244
6.29M
      if (PREDICT_FALSE(flag_offset >= dst_size)) {
245
0
        return FONT_COMPRESSION_FAILURE();
246
0
      }
247
6.29M
      dst[flag_offset++] = flag;
248
6.29M
      repeat_count = 0;
249
6.29M
    }
250
9.62M
    last_x = point.x;
251
9.62M
    last_y = point.y;
252
9.62M
    last_flag = flag;
253
9.62M
  }
254
255
139k
  if (repeat_count != 0) {
256
36.5k
    if (PREDICT_FALSE(flag_offset >= dst_size)) {
257
0
      return FONT_COMPRESSION_FAILURE();
258
0
    }
259
36.5k
    dst[flag_offset++] = repeat_count;
260
36.5k
  }
261
139k
  unsigned int xy_bytes = x_bytes + y_bytes;
262
139k
  if (PREDICT_FALSE(xy_bytes < x_bytes ||
263
139k
      flag_offset + xy_bytes < flag_offset ||
264
139k
      flag_offset + xy_bytes > dst_size)) {
265
0
    return FONT_COMPRESSION_FAILURE();
266
0
  }
267
268
139k
  int x_offset = flag_offset;
269
139k
  int y_offset = flag_offset + x_bytes;
270
139k
  last_x = 0;
271
139k
  last_y = 0;
272
9.76M
  for (unsigned int i = 0; i < n_points; ++i) {
273
9.62M
    int dx = points[i].x - last_x;
274
9.62M
    if (dx == 0) {
275
      // pass
276
5.05M
    } else if (dx > -256 && dx < 256) {
277
3.76M
      dst[x_offset++] = std::abs(dx);
278
3.76M
    } else {
279
      // will always fit for valid input, but overflow is harmless
280
809k
      x_offset = Store16(dst, x_offset, dx);
281
809k
    }
282
9.62M
    last_x += dx;
283
9.62M
    int dy = points[i].y - last_y;
284
9.62M
    if (dy == 0) {
285
      // pass
286
5.60M
    } else if (dy > -256 && dy < 256) {
287
4.16M
      dst[y_offset++] = std::abs(dy);
288
4.16M
    } else {
289
1.44M
      y_offset = Store16(dst, y_offset, dy);
290
1.44M
    }
291
9.62M
    last_y += dy;
292
9.62M
  }
293
139k
  *glyph_size = y_offset;
294
139k
  return true;
295
139k
}
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
138k
void ComputeBbox(unsigned int n_points, const Point* points, uint8_t* dst) {
301
138k
  int x_min = 0;
302
138k
  int y_min = 0;
303
138k
  int x_max = 0;
304
138k
  int y_max = 0;
305
306
138k
  if (n_points > 0) {
307
134k
    x_min = points[0].x;
308
134k
    x_max = points[0].x;
309
134k
    y_min = points[0].y;
310
134k
    y_max = points[0].y;
311
134k
  }
312
11.0M
  for (unsigned int i = 1; i < n_points; ++i) {
313
10.9M
    int x = points[i].x;
314
10.9M
    int y = points[i].y;
315
10.9M
    x_min = std::min(x, x_min);
316
10.9M
    x_max = std::max(x, x_max);
317
10.9M
    y_min = std::min(y, y_min);
318
10.9M
    y_max = std::max(y, y_max);
319
10.9M
  }
320
138k
  size_t offset = 2;
321
138k
  offset = Store16(dst, offset, x_min);
322
138k
  offset = Store16(dst, offset, y_min);
323
138k
  offset = Store16(dst, offset, x_max);
324
138k
  offset = Store16(dst, offset, y_max);
325
138k
}
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
8.24k
  while (flags & FLAG_MORE_COMPONENTS) {
335
7.14k
    if (PREDICT_FALSE(!composite_stream.ReadU16(&flags))) {
336
9
      return FONT_COMPRESSION_FAILURE();
337
9
    }
338
7.13k
    we_have_instructions |= (flags & FLAG_WE_HAVE_INSTRUCTIONS) != 0;
339
7.13k
    size_t arg_size = 2;  // glyph index
340
7.13k
    if (flags & FLAG_ARG_1_AND_2_ARE_WORDS) {
341
3.90k
      arg_size += 4;
342
3.90k
    } else {
343
3.23k
      arg_size += 2;
344
3.23k
    }
345
7.13k
    if (flags & FLAG_WE_HAVE_A_SCALE) {
346
2.90k
      arg_size += 2;
347
4.23k
    } else if (flags & FLAG_WE_HAVE_AN_X_AND_Y_SCALE) {
348
1.39k
      arg_size += 4;
349
2.84k
    } else if (flags & FLAG_WE_HAVE_A_TWO_BY_TWO) {
350
969
      arg_size += 8;
351
969
    }
352
7.13k
    if (PREDICT_FALSE(!composite_stream.Skip(arg_size))) {
353
32
      return FONT_COMPRESSION_FAILURE();
354
32
    }
355
7.13k
  }
356
357
1.09k
  *size = composite_stream.offset() - start_offset;
358
1.09k
  *have_instructions = we_have_instructions;
359
360
1.09k
  return true;
361
1.14k
}
362
363
178k
bool Pad4(WOFF2Out* out) {
364
178k
  uint8_t zeroes[] = {0, 0, 0};
365
178k
  if (PREDICT_FALSE(out->Size() + 3 < out->Size())) {
366
0
    return FONT_COMPRESSION_FAILURE();
367
0
  }
368
178k
  uint32_t pad_bytes = Round4(out->Size()) - out->Size();
369
178k
  if (pad_bytes > 0) {
370
107k
    if (PREDICT_FALSE(!out->Write(&zeroes, pad_bytes))) {
371
0
      return FONT_COMPRESSION_FAILURE();
372
0
    }
373
107k
  }
374
178k
  return true;
375
178k
}
376
377
// Build TrueType loca table
378
bool StoreLoca(const std::vector<uint32_t>& loca_values, int index_format,
379
138
               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
138
  const uint64_t loca_size = loca_values.size();
383
138
  const uint64_t offset_size = index_format ? 4 : 2;
384
138
  if (PREDICT_FALSE((loca_size << 2) >> 2 != loca_size)) {
385
0
    return FONT_COMPRESSION_FAILURE();
386
0
  }
387
138
  std::vector<uint8_t> loca_content(loca_size * offset_size);
388
138
  uint8_t* dst = &loca_content[0];
389
138
  size_t offset = 0;
390
115k
  for (size_t i = 0; i < loca_values.size(); ++i) {
391
114k
    uint32_t value = loca_values[i];
392
114k
    if (index_format) {
393
87.3k
      offset = StoreU32(dst, offset, value);
394
87.3k
    } else {
395
27.5k
      offset = Store16(dst, offset, value >> 1);
396
27.5k
    }
397
114k
  }
398
138
  *checksum = ComputeULongSum(&loca_content[0], loca_content.size());
399
138
  if (PREDICT_FALSE(!out->Write(&loca_content[0], loca_content.size()))) {
400
0
    return FONT_COMPRESSION_FAILURE();
401
0
  }
402
138
  return true;
403
138
}
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.20k
                     WOFF2Out* out) {
410
1.20k
  static const int kNumSubStreams = 7;
411
1.20k
  Buffer file(data, glyf_table->transform_length);
412
1.20k
  uint16_t version;
413
1.20k
  std::vector<std::pair<const uint8_t*, size_t> > substreams(kNumSubStreams);
414
1.20k
  const size_t glyf_start = out->Size();
415
416
1.20k
  if (PREDICT_FALSE(!file.ReadU16(&version))) {
417
15
    return FONT_COMPRESSION_FAILURE();
418
15
  }
419
420
1.19k
  uint16_t flags;
421
1.19k
  if (PREDICT_FALSE(!file.ReadU16(&flags))) {
422
2
    return FONT_COMPRESSION_FAILURE();
423
2
  }
424
1.19k
  bool has_overlap_bitmap = (flags & FLAG_OVERLAP_SIMPLE_BITMAP);
425
426
1.19k
  if (PREDICT_FALSE(!file.ReadU16(&info->num_glyphs) ||
427
1.19k
      !file.ReadU16(&info->index_format))) {
428
30
    return FONT_COMPRESSION_FAILURE();
429
30
  }
430
431
  // https://dev.w3.org/webfonts/WOFF2/spec/#conform-mustRejectLoca
432
  // dst_length here is origLength in the spec
433
1.16k
  uint32_t expected_loca_dst_length = (info->index_format ? 4 : 2)
434
1.16k
    * (static_cast<uint32_t>(info->num_glyphs) + 1);
435
1.16k
  if (PREDICT_FALSE(loca_table->dst_length != expected_loca_dst_length)) {
436
111
    return FONT_COMPRESSION_FAILURE();
437
111
  }
438
439
1.05k
  unsigned int offset = (2 + kNumSubStreams) * 4;
440
1.05k
  if (PREDICT_FALSE(offset > glyf_table->transform_length)) {
441
2
    return FONT_COMPRESSION_FAILURE();
442
2
  }
443
  // Invariant from here on: data_size >= offset
444
7.87k
  for (int i = 0; i < kNumSubStreams; ++i) {
445
6.90k
    uint32_t substream_size;
446
6.90k
    if (PREDICT_FALSE(!file.ReadU32(&substream_size))) {
447
0
      return FONT_COMPRESSION_FAILURE();
448
0
    }
449
6.90k
    if (PREDICT_FALSE(substream_size > glyf_table->transform_length - offset)) {
450
82
      return FONT_COMPRESSION_FAILURE();
451
82
    }
452
6.82k
    substreams[i] = std::make_pair(data + offset, substream_size);
453
6.82k
    offset += substream_size;
454
6.82k
  }
455
966
  Buffer n_contour_stream(substreams[0].first, substreams[0].second);
456
966
  Buffer n_points_stream(substreams[1].first, substreams[1].second);
457
966
  Buffer flag_stream(substreams[2].first, substreams[2].second);
458
966
  Buffer glyph_stream(substreams[3].first, substreams[3].second);
459
966
  Buffer composite_stream(substreams[4].first, substreams[4].second);
460
966
  Buffer bbox_stream(substreams[5].first, substreams[5].second);
461
966
  Buffer instruction_stream(substreams[6].first, substreams[6].second);
462
463
966
  const uint8_t* overlap_bitmap = nullptr;
464
966
  unsigned int overlap_bitmap_length = 0;
465
966
  if (has_overlap_bitmap) {
466
324
    overlap_bitmap_length = (info->num_glyphs + 7) >> 3;
467
324
    overlap_bitmap = data + offset;
468
324
    if (PREDICT_FALSE(overlap_bitmap_length >
469
324
                           glyf_table->transform_length - offset)) {
470
8
      return FONT_COMPRESSION_FAILURE();
471
8
    }
472
324
  }
473
474
958
  std::vector<uint32_t> loca_values(info->num_glyphs + 1);
475
958
  std::vector<unsigned int> n_points_vec;
476
958
  std::unique_ptr<Point[]> points;
477
958
  size_t points_size = 0;
478
958
  const uint8_t* bbox_bitmap = bbox_stream.buffer();
479
  // Safe because num_glyphs is bounded
480
958
  unsigned int bitmap_length = ((info->num_glyphs + 31) >> 5) << 2;
481
958
  if (!bbox_stream.Skip(bitmap_length)) {
482
2
    return FONT_COMPRESSION_FAILURE();
483
2
  }
484
485
  // Temp buffer for glyph's.
486
956
  size_t glyph_buf_size = kDefaultGlyphBuf;
487
956
  std::unique_ptr<uint8_t[]> glyph_buf(new uint8_t[glyph_buf_size]);
488
489
956
  info->x_mins.resize(info->num_glyphs);
490
164k
  for (unsigned int i = 0; i < info->num_glyphs; ++i) {
491
164k
    size_t glyph_size = 0;
492
164k
    uint16_t n_contours = 0;
493
164k
    bool have_bbox = false;
494
164k
    if (bbox_bitmap[i >> 3] & (0x80 >> (i & 7))) {
495
2.28k
      have_bbox = true;
496
2.28k
    }
497
164k
    if (PREDICT_FALSE(!n_contour_stream.ReadU16(&n_contours))) {
498
8
      return FONT_COMPRESSION_FAILURE();
499
8
    }
500
501
164k
    if (n_contours == 0xffff) {
502
      // composite glyph
503
1.19k
      bool have_instructions = false;
504
1.19k
      unsigned int instruction_size = 0;
505
1.19k
      if (PREDICT_FALSE(!have_bbox)) {
506
        // composite glyphs must have an explicit bbox
507
50
        return FONT_COMPRESSION_FAILURE();
508
50
      }
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
41
        return FONT_COMPRESSION_FAILURE();
514
41
      }
515
1.09k
      if (have_instructions) {
516
459
        if (PREDICT_FALSE(!Read255UShort(&glyph_stream, &instruction_size))) {
517
2
          return FONT_COMPRESSION_FAILURE();
518
2
        }
519
459
      }
520
521
1.09k
      size_t size_needed = 12 + composite_size + instruction_size;
522
1.09k
      if (PREDICT_FALSE(glyph_buf_size < size_needed)) {
523
15
        glyph_buf.reset(new uint8_t[size_needed]);
524
15
        glyph_buf_size = size_needed;
525
15
      }
526
527
1.09k
      glyph_size = Store16(glyph_buf.get(), glyph_size, n_contours);
528
1.09k
      if (PREDICT_FALSE(!bbox_stream.Read(glyph_buf.get() + glyph_size, 8))) {
529
16
        return FONT_COMPRESSION_FAILURE();
530
16
      }
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
448
        glyph_size = Store16(glyph_buf.get(), glyph_size, instruction_size);
540
448
        if (PREDICT_FALSE(!instruction_stream.Read(glyph_buf.get() + glyph_size,
541
448
              instruction_size))) {
542
65
          return FONT_COMPRESSION_FAILURE();
543
65
        }
544
383
        glyph_size += instruction_size;
545
383
      }
546
163k
    } else if (n_contours > 0) {
547
      // simple glyph
548
139k
      n_points_vec.clear();
549
139k
      unsigned int total_n_points = 0;
550
139k
      unsigned int n_points_contour;
551
1.23M
      for (unsigned int j = 0; j < n_contours; ++j) {
552
1.09M
        if (PREDICT_FALSE(
553
1.09M
            !Read255UShort(&n_points_stream, &n_points_contour))) {
554
162
          return FONT_COMPRESSION_FAILURE();
555
162
        }
556
1.09M
        n_points_vec.push_back(n_points_contour);
557
1.09M
        if (PREDICT_FALSE(total_n_points + n_points_contour < total_n_points)) {
558
0
          return FONT_COMPRESSION_FAILURE();
559
0
        }
560
1.09M
        total_n_points += n_points_contour;
561
1.09M
      }
562
139k
      unsigned int flag_size = total_n_points;
563
139k
      if (PREDICT_FALSE(
564
139k
          flag_size > flag_stream.length() - flag_stream.offset())) {
565
117
        return FONT_COMPRESSION_FAILURE();
566
117
      }
567
139k
      const uint8_t* flags_buf = flag_stream.buffer() + flag_stream.offset();
568
139k
      const uint8_t* triplet_buf = glyph_stream.buffer() +
569
139k
        glyph_stream.offset();
570
139k
      size_t triplet_size = glyph_stream.length() - glyph_stream.offset();
571
139k
      size_t triplet_bytes_consumed = 0;
572
139k
      if (points_size < total_n_points) {
573
2.28k
        points_size = total_n_points;
574
2.28k
        points.reset(new Point[points_size]);
575
2.28k
      }
576
139k
      if (PREDICT_FALSE(!TripletDecode(flags_buf, triplet_buf, triplet_size,
577
139k
          total_n_points, points.get(), &triplet_bytes_consumed))) {
578
127
        return FONT_COMPRESSION_FAILURE();
579
127
      }
580
139k
      if (PREDICT_FALSE(!flag_stream.Skip(flag_size))) {
581
0
        return FONT_COMPRESSION_FAILURE();
582
0
      }
583
139k
      if (PREDICT_FALSE(!glyph_stream.Skip(triplet_bytes_consumed))) {
584
0
        return FONT_COMPRESSION_FAILURE();
585
0
      }
586
139k
      unsigned int instruction_size;
587
139k
      if (PREDICT_FALSE(!Read255UShort(&glyph_stream, &instruction_size))) {
588
24
        return FONT_COMPRESSION_FAILURE();
589
24
      }
590
591
139k
      if (PREDICT_FALSE(total_n_points >= (1 << 27)
592
139k
                        || instruction_size >= (1 << 30))) {
593
0
        return FONT_COMPRESSION_FAILURE();
594
0
      }
595
139k
      size_t size_needed = 12 + 2 * n_contours + 5 * total_n_points
596
139k
                           + instruction_size;
597
139k
      if (PREDICT_FALSE(glyph_buf_size < size_needed)) {
598
332
        glyph_buf.reset(new uint8_t[size_needed]);
599
332
        glyph_buf_size = size_needed;
600
332
      }
601
602
139k
      glyph_size = Store16(glyph_buf.get(), glyph_size, n_contours);
603
139k
      if (have_bbox) {
604
1.06k
        if (PREDICT_FALSE(!bbox_stream.Read(glyph_buf.get() + glyph_size, 8))) {
605
29
          return FONT_COMPRESSION_FAILURE();
606
29
        }
607
138k
      } else {
608
138k
        ComputeBbox(total_n_points, points.get(), glyph_buf.get());
609
138k
      }
610
139k
      glyph_size = kEndPtsOfContoursOffset;
611
139k
      int end_point = -1;
612
551k
      for (unsigned int contour_ix = 0; contour_ix < n_contours; ++contour_ix) {
613
412k
        end_point += n_points_vec[contour_ix];
614
412k
        if (PREDICT_FALSE(end_point >= 65536)) {
615
8
          return FONT_COMPRESSION_FAILURE();
616
8
        }
617
412k
        glyph_size = Store16(glyph_buf.get(), glyph_size, end_point);
618
412k
      }
619
620
139k
      glyph_size = Store16(glyph_buf.get(), glyph_size, instruction_size);
621
139k
      if (PREDICT_FALSE(!instruction_stream.Read(glyph_buf.get() + glyph_size,
622
139k
                                                 instruction_size))) {
623
155
        return FONT_COMPRESSION_FAILURE();
624
155
      }
625
139k
      glyph_size += instruction_size;
626
627
139k
      bool has_overlap_bit =
628
139k
          has_overlap_bitmap && overlap_bitmap[i >> 3] & (0x80 >> (i & 7));
629
630
139k
      if (PREDICT_FALSE(!StorePoints(
631
139k
              total_n_points, points.get(), n_contours, instruction_size,
632
139k
              has_overlap_bit, glyph_buf.get(), glyph_buf_size, &glyph_size))) {
633
0
        return FONT_COMPRESSION_FAILURE();
634
0
      }
635
139k
    } else {
636
      // n_contours == 0; empty glyph. Must NOT have a bbox.
637
23.4k
      if (PREDICT_FALSE(have_bbox)) {
638
#ifdef FONT_COMPRESSION_BIN
639
        fprintf(stderr, "Empty glyph has a bbox\n");
640
#endif
641
14
        return FONT_COMPRESSION_FAILURE();
642
14
      }
643
23.4k
    }
644
645
163k
    loca_values[i] = out->Size() - glyf_start;
646
163k
    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
163k
    if (PREDICT_FALSE(!Pad4(out))) {
652
0
      return FONT_COMPRESSION_FAILURE();
653
0
    }
654
655
163k
    *glyf_checksum += ComputeULongSum(glyph_buf.get(), glyph_size);
656
657
    // We may need x_min to reconstruct 'hmtx'
658
163k
    if (n_contours > 0) {
659
140k
      Buffer x_min_buf(glyph_buf.get() + 2, 2);
660
140k
      if (PREDICT_FALSE(!x_min_buf.ReadS16(&info->x_mins[i]))) {
661
0
        return FONT_COMPRESSION_FAILURE();
662
0
      }
663
140k
    }
664
163k
  }
665
666
  // glyf_table dst_offset was set by ReconstructFont
667
138
  glyf_table->dst_length = out->Size() - glyf_table->dst_offset;
668
138
  loca_table->dst_offset = out->Size();
669
  // loca[n] will be equal the length of the glyph data ('glyf') table
670
138
  loca_values[info->num_glyphs] = glyf_table->dst_length;
671
138
  if (PREDICT_FALSE(!StoreLoca(loca_values, info->index_format, loca_checksum,
672
138
      out))) {
673
0
    return FONT_COMPRESSION_FAILURE();
674
0
  }
675
138
  loca_table->dst_length = out->Size() - loca_table->dst_offset;
676
677
138
  return true;
678
138
}
679
680
7.43k
Table* FindTable(std::vector<Table*>* tables, uint32_t tag) {
681
49.9k
  for (Table* table : *tables) {
682
49.9k
    if (table->tag == tag) {
683
3.96k
      return table;
684
3.96k
    }
685
49.9k
  }
686
3.47k
  return NULL;
687
7.43k
}
688
689
// Get numberOfHMetrics, https://www.microsoft.com/typography/otspec/hhea.htm
690
bool ReadNumHMetrics(const uint8_t* data, size_t data_size,
691
630
                     uint16_t* num_hmetrics) {
692
  // Skip 34 to reach 'hhea' numberOfHMetrics
693
630
  Buffer buffer(data, data_size);
694
630
  if (PREDICT_FALSE(!buffer.Skip(34) || !buffer.ReadU16(num_hmetrics))) {
695
21
    return FONT_COMPRESSION_FAILURE();
696
21
  }
697
609
  return true;
698
630
}
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
120
                                WOFF2Out* out) {
708
120
  Buffer hmtx_buff_in(transformed_buf, transformed_size);
709
710
120
  uint8_t hmtx_flags;
711
120
  if (PREDICT_FALSE(!hmtx_buff_in.ReadU8(&hmtx_flags))) {
712
2
    return FONT_COMPRESSION_FAILURE();
713
2
  }
714
715
118
  std::vector<uint16_t> advance_widths;
716
118
  std::vector<int16_t> lsbs;
717
118
  bool has_proportional_lsbs = (hmtx_flags & 1) == 0;
718
118
  bool has_monospace_lsbs = (hmtx_flags & 2) == 0;
719
720
  // Bits 2-7 are reserved and MUST be zero.
721
118
  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
8
    return FONT_COMPRESSION_FAILURE();
726
8
  }
727
728
  // you say you transformed but there is little evidence of it
729
110
  if (has_proportional_lsbs && has_monospace_lsbs) {
730
21
    return FONT_COMPRESSION_FAILURE();
731
21
  }
732
733
89
  assert(x_mins.size() == num_glyphs);
734
735
  // num_glyphs 0 is OK if there is no 'glyf' but cannot then xform 'hmtx'.
736
89
  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
63
  if (PREDICT_FALSE(num_hmetrics < 1)) {
743
4
    return FONT_COMPRESSION_FAILURE();
744
4
  }
745
746
359
  for (uint16_t i = 0; i < num_hmetrics; i++) {
747
301
    uint16_t advance_width;
748
301
    if (PREDICT_FALSE(!hmtx_buff_in.ReadU16(&advance_width))) {
749
1
      return FONT_COMPRESSION_FAILURE();
750
1
    }
751
300
    advance_widths.push_back(advance_width);
752
300
  }
753
754
350
  for (uint16_t i = 0; i < num_hmetrics; i++) {
755
294
    int16_t lsb;
756
294
    if (has_proportional_lsbs) {
757
127
      if (PREDICT_FALSE(!hmtx_buff_in.ReadS16(&lsb))) {
758
2
        return FONT_COMPRESSION_FAILURE();
759
2
      }
760
167
    } else {
761
167
      lsb = x_mins[i];
762
167
    }
763
292
    lsbs.push_back(lsb);
764
292
  }
765
766
323
  for (uint16_t i = num_hmetrics; i < num_glyphs; i++) {
767
268
    int16_t lsb;
768
268
    if (has_monospace_lsbs) {
769
122
      if (PREDICT_FALSE(!hmtx_buff_in.ReadS16(&lsb))) {
770
1
        return FONT_COMPRESSION_FAILURE();
771
1
      }
772
146
    } else {
773
146
      lsb = x_mins[i];
774
146
    }
775
267
    lsbs.push_back(lsb);
776
267
  }
777
778
  // bake me a shiny new hmtx table
779
55
  uint32_t hmtx_output_size = 2 * num_glyphs + 2 * num_hmetrics;
780
55
  std::vector<uint8_t> hmtx_table(hmtx_output_size);
781
55
  uint8_t* dst = &hmtx_table[0];
782
55
  size_t dst_offset = 0;
783
600
  for (uint32_t i = 0; i < num_glyphs; i++) {
784
545
    if (i < num_hmetrics) {
785
280
      Store16(advance_widths[i], &dst_offset, dst);
786
280
    }
787
545
    Store16(lsbs[i], &dst_offset, dst);
788
545
  }
789
790
55
  *checksum = ComputeULongSum(&hmtx_table[0], hmtx_output_size);
791
55
  if (PREDICT_FALSE(!out->Write(&hmtx_table[0], hmtx_output_size))) {
792
0
    return FONT_COMPRESSION_FAILURE();
793
0
  }
794
795
55
  return true;
796
55
}
797
798
bool Woff2Uncompress(uint8_t* dst_buf, size_t dst_size,
799
9.59k
  const uint8_t* src_buf, size_t src_size) {
800
9.59k
  size_t uncompressed_size = dst_size;
801
9.59k
  BrotliDecoderResult result = BrotliDecoderDecompress(
802
9.59k
      src_size, src_buf, &uncompressed_size, dst_buf);
803
9.59k
  if (PREDICT_FALSE(result != BROTLI_DECODER_RESULT_SUCCESS ||
804
9.59k
                    uncompressed_size != dst_size)) {
805
7.49k
    return FONT_COMPRESSION_FAILURE();
806
7.49k
  }
807
2.10k
  return true;
808
9.59k
}
809
810
bool ReadTableDirectory(Buffer* file, std::vector<Table>* tables,
811
12.8k
    size_t num_tables) {
812
12.8k
  uint32_t src_offset = 0;
813
1.97M
  for (size_t i = 0; i < num_tables; ++i) {
814
1.96M
    Table* table = &(*tables)[i];
815
1.96M
    uint8_t flag_byte;
816
1.96M
    if (PREDICT_FALSE(!file->ReadU8(&flag_byte))) {
817
118
      return FONT_COMPRESSION_FAILURE();
818
118
    }
819
1.96M
    uint32_t tag;
820
1.96M
    if ((flag_byte & 0x3f) == 0x3f) {
821
22.8k
      if (PREDICT_FALSE(!file->ReadU32(&tag))) {
822
14
        return FONT_COMPRESSION_FAILURE();
823
14
      }
824
1.93M
    } else {
825
1.93M
      tag = kKnownTags[flag_byte & 0x3f];
826
1.93M
    }
827
1.96M
    uint32_t flags = 0;
828
1.96M
    uint8_t xform_version = (flag_byte >> 6) & 0x03;
829
830
    // 0 means xform for glyph/loca, non-0 for others
831
1.96M
    if (tag == kGlyfTableTag || tag == kLocaTableTag) {
832
27.5k
      if (xform_version == 0) {
833
10.0k
        flags |= kWoff2FlagsTransform;
834
10.0k
      }
835
1.93M
    } else if (xform_version != 0) {
836
142k
      flags |= kWoff2FlagsTransform;
837
142k
    }
838
1.96M
    flags |= xform_version;
839
840
1.96M
    uint32_t dst_length;
841
1.96M
    if (PREDICT_FALSE(!ReadBase128(file, &dst_length))) {
842
168
      return FONT_COMPRESSION_FAILURE();
843
168
    }
844
1.96M
    uint32_t transform_length = dst_length;
845
1.96M
    if ((flags & kWoff2FlagsTransform) != 0) {
846
152k
      if (PREDICT_FALSE(!ReadBase128(file, &transform_length))) {
847
34
        return FONT_COMPRESSION_FAILURE();
848
34
      }
849
152k
      if (PREDICT_FALSE(tag == kLocaTableTag && transform_length)) {
850
103
        return FONT_COMPRESSION_FAILURE();
851
103
      }
852
152k
    }
853
1.96M
    if (PREDICT_FALSE(src_offset + transform_length < src_offset)) {
854
2
      return FONT_COMPRESSION_FAILURE();
855
2
    }
856
1.96M
    table->src_offset = src_offset;
857
1.96M
    table->src_length = transform_length;
858
1.96M
    src_offset += transform_length;
859
860
1.96M
    table->tag = tag;
861
1.96M
    table->flags = flags;
862
1.96M
    table->transform_length = transform_length;
863
1.96M
    table->dst_length = dst_length;
864
1.96M
  }
865
12.3k
  return true;
866
12.8k
}
867
868
// Writes a single Offset Table entry
869
size_t StoreOffsetTable(uint8_t* result, size_t offset, uint32_t flavor,
870
17.0k
                        uint16_t num_tables) {
871
17.0k
  offset = StoreU32(result, offset, flavor);  // sfnt version
872
17.0k
  offset = Store16(result, offset, num_tables);  // num_tables
873
17.0k
  unsigned max_pow2 = 0;
874
65.1k
  while (1u << (max_pow2 + 1) <= num_tables) {
875
48.0k
    max_pow2++;
876
48.0k
  }
877
17.0k
  const uint16_t output_search_range = (1u << max_pow2) << 4;
878
17.0k
  offset = Store16(result, offset, output_search_range);  // searchRange
879
17.0k
  offset = Store16(result, offset, max_pow2);  // entrySelector
880
  // rangeShift
881
17.0k
  offset = Store16(result, offset, (num_tables << 4) - output_search_range);
882
17.0k
  return offset;
883
17.0k
}
884
885
1.29M
size_t StoreTableEntry(uint8_t* result, uint32_t offset, uint32_t tag) {
886
1.29M
  offset = StoreU32(result, offset, tag);
887
1.29M
  offset = StoreU32(result, offset, 0);
888
1.29M
  offset = StoreU32(result, offset, 0);
889
1.29M
  offset = StoreU32(result, offset, 0);
890
1.29M
  return offset;
891
1.29M
}
892
893
// First table goes after all the headers, table directory, etc
894
23.0k
uint64_t ComputeOffsetToFirstTable(const WOFF2Header& hdr) {
895
23.0k
  uint64_t offset = kSfntHeaderSize +
896
23.0k
    kSfntEntrySize * static_cast<uint64_t>(hdr.num_tables);
897
23.0k
  if (hdr.header_version) {
898
841
    offset = CollectionHeaderSize(hdr.header_version, hdr.ttc_fonts.size())
899
841
      + kSfntHeaderSize * hdr.ttc_fonts.size();
900
12.6k
    for (const auto& ttc_font : hdr.ttc_fonts) {
901
12.6k
      offset += kSfntEntrySize * ttc_font.table_indices.size();
902
12.6k
    }
903
841
  }
904
23.0k
  return offset;
905
23.0k
}
906
907
2.58k
std::vector<Table*> Tables(WOFF2Header* hdr, size_t font_index) {
908
2.58k
  std::vector<Table*> tables;
909
2.58k
  if (PREDICT_FALSE(hdr->header_version)) {
910
3.64k
    for (auto index : hdr->ttc_fonts[font_index].table_indices) {
911
3.64k
      tables.push_back(&hdr->tables[index]);
912
3.64k
    }
913
1.87k
  } else {
914
20.9k
    for (auto& table : hdr->tables) {
915
20.9k
      tables.push_back(&table);
916
20.9k
    }
917
1.87k
  }
918
2.58k
  return tables;
919
2.58k
}
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
2.58k
                     WOFF2Out* out) {
929
2.58k
  size_t dest_offset = out->Size();
930
2.58k
  uint8_t table_entry[12];
931
2.58k
  WOFF2FontInfo* info = &metadata->font_infos[font_index];
932
2.58k
  std::vector<Table*> tables = Tables(hdr, font_index);
933
934
  // 'glyf' without 'loca' doesn't make sense
935
2.58k
  const Table* glyf_table = FindTable(&tables, kGlyfTableTag);
936
2.58k
  const Table* loca_table = FindTable(&tables, kLocaTableTag);
937
2.58k
  if (PREDICT_FALSE(static_cast<bool>(glyf_table) !=
938
2.58k
                    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
2.58k
  if (glyf_table != NULL) {
946
1.28k
    if (PREDICT_FALSE((glyf_table->flags & kWoff2FlagsTransform)
947
1.28k
                      != (loca_table->flags & kWoff2FlagsTransform))) {
948
#ifdef FONT_COMPRESSION_BIN
949
      fprintf(stderr, "Cannot transform just one of glyf/loca\n");
950
#endif
951
2
      return FONT_COMPRESSION_FAILURE();
952
2
    }
953
1.28k
  }
954
955
2.57k
  uint32_t font_checksum = metadata->header_checksum;
956
2.57k
  if (hdr->header_version) {
957
706
    font_checksum = hdr->ttc_fonts[font_index].header_checksum;
958
706
  }
959
960
2.57k
  uint32_t loca_checksum = 0;
961
17.7k
  for (size_t i = 0; i < tables.size(); i++) {
962
16.7k
    Table& table = *tables[i];
963
964
16.7k
    std::pair<uint32_t, uint32_t> checksum_key = {table.tag, table.src_offset};
965
16.7k
    bool reused = metadata->checksums.find(checksum_key)
966
16.7k
               != metadata->checksums.end();
967
16.7k
    if (PREDICT_FALSE(font_index == 0 && reused)) {
968
34
      return FONT_COMPRESSION_FAILURE();
969
34
    }
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
16.6k
    if (PREDICT_FALSE(static_cast<uint64_t>(table.src_offset) + table.src_length
974
16.6k
        > transformed_buf_size)) {
975
0
      return FONT_COMPRESSION_FAILURE();
976
0
    }
977
978
16.6k
    if (table.tag == kHheaTableTag) {
979
630
      if (!ReadNumHMetrics(transformed_buf + table.src_offset,
980
630
          table.src_length, &info->num_hmetrics)) {
981
21
        return FONT_COMPRESSION_FAILURE();
982
21
      }
983
630
    }
984
985
16.6k
    uint32_t checksum = 0;
986
16.6k
    if (!reused) {
987
13.7k
      if ((table.flags & kWoff2FlagsTransform) != kWoff2FlagsTransform) {
988
12.0k
        if (table.tag == kHeadTableTag) {
989
209
          if (PREDICT_FALSE(table.src_length < 12)) {
990
11
            return FONT_COMPRESSION_FAILURE();
991
11
          }
992
          // checkSumAdjustment = 0
993
198
          StoreU32(transformed_buf + table.src_offset, 8, 0);
994
198
        }
995
11.9k
        table.dst_offset = dest_offset;
996
11.9k
        checksum = ComputeULongSum(transformed_buf + table.src_offset,
997
11.9k
                                   table.src_length);
998
11.9k
        if (PREDICT_FALSE(!out->Write(transformed_buf + table.src_offset,
999
11.9k
            table.src_length))) {
1000
0
          return FONT_COMPRESSION_FAILURE();
1001
0
        }
1002
11.9k
      } else {
1003
1.76k
        if (table.tag == kGlyfTableTag) {
1004
1.20k
          table.dst_offset = dest_offset;
1005
1006
1.20k
          Table* loca_table = FindTable(&tables, kLocaTableTag);
1007
1.20k
          if (PREDICT_FALSE(!ReconstructGlyf(transformed_buf + table.src_offset,
1008
1.20k
              &table, &checksum, loca_table, &loca_checksum, info, out))) {
1009
1.07k
            return FONT_COMPRESSION_FAILURE();
1010
1.07k
          }
1011
1.20k
        } else if (table.tag == kLocaTableTag) {
1012
          // All the work was done by ReconstructGlyf. We already know checksum.
1013
167
          checksum = loca_checksum;
1014
392
        } else if (table.tag == kHmtxTableTag) {
1015
120
          table.dst_offset = dest_offset;
1016
          // Tables are sorted so all the info we need has been gathered.
1017
120
          if (PREDICT_FALSE(!ReconstructTransformedHmtx(
1018
120
              transformed_buf + table.src_offset, table.src_length,
1019
120
              info->num_glyphs, info->num_hmetrics, info->x_mins, &checksum,
1020
120
              out))) {
1021
65
            return FONT_COMPRESSION_FAILURE();
1022
65
          }
1023
272
        } else {
1024
272
          return FONT_COMPRESSION_FAILURE();  // transform unknown
1025
272
        }
1026
1.76k
      }
1027
12.3k
      metadata->checksums[checksum_key] = checksum;
1028
12.3k
    } else {
1029
2.88k
      checksum = metadata->checksums[checksum_key];
1030
2.88k
    }
1031
15.2k
    font_checksum += checksum;
1032
1033
    // update the table entry with real values.
1034
15.2k
    StoreU32(table_entry, 0, checksum);
1035
15.2k
    StoreU32(table_entry, 4, table.dst_offset);
1036
15.2k
    StoreU32(table_entry, 8, table.dst_length);
1037
15.2k
    if (PREDICT_FALSE(!out->Write(table_entry,
1038
15.2k
        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
15.2k
    font_checksum += ComputeULongSum(table_entry, 12);
1044
1045
15.2k
    if (PREDICT_FALSE(!Pad4(out))) {
1046
0
      return FONT_COMPRESSION_FAILURE();
1047
0
    }
1048
1049
15.2k
    if (PREDICT_FALSE(static_cast<uint64_t>(table.dst_offset + table.dst_length)
1050
15.2k
        > out->Size())) {
1051
49
      return FONT_COMPRESSION_FAILURE();
1052
49
    }
1053
15.1k
    dest_offset = out->Size();
1054
15.1k
  }
1055
1056
  // Update 'head' checkSumAdjustment. We already set it to 0 and summed font.
1057
1.05k
  Table* head_table = FindTable(&tables, kHeadTableTag);
1058
1.05k
  if (head_table) {
1059
178
    if (PREDICT_FALSE(head_table->dst_length < 12)) {
1060
2
      return FONT_COMPRESSION_FAILURE();
1061
2
    }
1062
176
    uint8_t checksum_adjustment[4];
1063
176
    StoreU32(checksum_adjustment, 0, 0xB1B0AFBA - font_checksum);
1064
176
    if (PREDICT_FALSE(!out->Write(checksum_adjustment,
1065
176
                                  head_table->dst_offset + 8, 4))) {
1066
0
      return FONT_COMPRESSION_FAILURE();
1067
0
    }
1068
176
  }
1069
1070
1.05k
  return true;
1071
1.05k
}
1072
1073
13.6k
bool ReadWOFF2Header(const uint8_t* data, size_t length, WOFF2Header* hdr) {
1074
13.6k
  Buffer file(data, length);
1075
1076
13.6k
  uint32_t signature;
1077
13.6k
  if (PREDICT_FALSE(!file.ReadU32(&signature) || signature != kWoff2Signature ||
1078
13.6k
      !file.ReadU32(&hdr->flavor))) {
1079
168
    return FONT_COMPRESSION_FAILURE();
1080
168
  }
1081
1082
  // TODO(user): Should call IsValidVersionTag() here.
1083
1084
13.4k
  uint32_t reported_length;
1085
13.4k
  if (PREDICT_FALSE(
1086
13.4k
      !file.ReadU32(&reported_length) || length != reported_length)) {
1087
147
    return FONT_COMPRESSION_FAILURE();
1088
147
  }
1089
13.3k
  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
13.3k
  if (PREDICT_FALSE(!file.Skip(6))) {
1097
38
    return FONT_COMPRESSION_FAILURE();
1098
38
  }
1099
13.3k
  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
13.2k
  if (PREDICT_FALSE(!file.Skip(2 * 2))) {
1105
6
    return FONT_COMPRESSION_FAILURE();
1106
6
  }
1107
13.2k
  uint32_t meta_offset;
1108
13.2k
  uint32_t meta_length;
1109
13.2k
  uint32_t meta_length_orig;
1110
13.2k
  if (PREDICT_FALSE(!file.ReadU32(&meta_offset) ||
1111
13.2k
      !file.ReadU32(&meta_length) ||
1112
13.2k
      !file.ReadU32(&meta_length_orig))) {
1113
18
    return FONT_COMPRESSION_FAILURE();
1114
18
  }
1115
13.2k
  if (meta_offset) {
1116
622
    if (PREDICT_FALSE(
1117
622
        meta_offset >= length || length - meta_offset < meta_length)) {
1118
220
      return FONT_COMPRESSION_FAILURE();
1119
220
    }
1120
622
  }
1121
13.0k
  uint32_t priv_offset;
1122
13.0k
  uint32_t priv_length;
1123
13.0k
  if (PREDICT_FALSE(!file.ReadU32(&priv_offset) ||
1124
13.0k
      !file.ReadU32(&priv_length))) {
1125
16
    return FONT_COMPRESSION_FAILURE();
1126
16
  }
1127
13.0k
  if (priv_offset) {
1128
472
    if (PREDICT_FALSE(
1129
472
        priv_offset >= length || length - priv_offset < priv_length)) {
1130
198
      return FONT_COMPRESSION_FAILURE();
1131
198
    }
1132
472
  }
1133
12.8k
  hdr->tables.resize(hdr->num_tables);
1134
12.8k
  if (PREDICT_FALSE(!ReadTableDirectory(
1135
12.8k
          &file, &hdr->tables, hdr->num_tables))) {
1136
439
    return FONT_COMPRESSION_FAILURE();
1137
439
  }
1138
1139
  // Before we sort for output the last table end is the uncompressed size.
1140
12.3k
  Table& last_table = hdr->tables.back();
1141
12.3k
  hdr->uncompressed_size = last_table.src_offset + last_table.src_length;
1142
12.3k
  if (PREDICT_FALSE(hdr->uncompressed_size < last_table.src_offset)) {
1143
0
    return FONT_COMPRESSION_FAILURE();
1144
0
  }
1145
1146
12.3k
  hdr->header_version = 0;
1147
1148
12.3k
  if (hdr->flavor == kTtcFontFlavor) {
1149
1.05k
    if (PREDICT_FALSE(!file.ReadU32(&hdr->header_version))) {
1150
26
      return FONT_COMPRESSION_FAILURE();
1151
26
    }
1152
1.02k
    if (PREDICT_FALSE(hdr->header_version != 0x00010000
1153
1.02k
                   && hdr->header_version != 0x00020000)) {
1154
134
      return FONT_COMPRESSION_FAILURE();
1155
134
    }
1156
893
    uint32_t num_fonts;
1157
893
    if (PREDICT_FALSE(!Read255UShort(&file, &num_fonts) || !num_fonts)) {
1158
12
      return FONT_COMPRESSION_FAILURE();
1159
12
    }
1160
881
    hdr->ttc_fonts.resize(num_fonts);
1161
1162
9.40k
    for (uint32_t i = 0; i < num_fonts; i++) {
1163
8.98k
      TtcFont& ttc_font = hdr->ttc_fonts[i];
1164
8.98k
      uint32_t num_tables;
1165
8.98k
      if (PREDICT_FALSE(!Read255UShort(&file, &num_tables) || !num_tables)) {
1166
97
        return FONT_COMPRESSION_FAILURE();
1167
97
      }
1168
8.88k
      if (PREDICT_FALSE(!file.ReadU32(&ttc_font.flavor))) {
1169
58
        return FONT_COMPRESSION_FAILURE();
1170
58
      }
1171
1172
8.82k
      ttc_font.table_indices.resize(num_tables);
1173
1174
1175
8.82k
      unsigned int glyf_idx = 0;
1176
8.82k
      unsigned int loca_idx = 0;
1177
1178
354k
      for (uint32_t j = 0; j < num_tables; j++) {
1179
345k
        unsigned int table_idx;
1180
345k
        if (PREDICT_FALSE(!Read255UShort(&file, &table_idx)) ||
1181
345k
            table_idx >= hdr->tables.size()) {
1182
264
          return FONT_COMPRESSION_FAILURE();
1183
264
        }
1184
345k
        ttc_font.table_indices[j] = table_idx;
1185
1186
345k
        const Table& table = hdr->tables[table_idx];
1187
345k
        if (table.tag == kLocaTableTag) {
1188
2.90k
          loca_idx = table_idx;
1189
2.90k
        }
1190
345k
        if (table.tag == kGlyfTableTag) {
1191
2.49k
          glyf_idx = table_idx;
1192
2.49k
        }
1193
1194
345k
      }
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
8.56k
      if (glyf_idx > 0 || loca_idx > 0) {
1199
580
        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
36
          return FONT_COMPRESSION_FAILURE();
1204
36
        }
1205
580
      }
1206
8.56k
    }
1207
881
  }
1208
1209
11.7k
  const uint64_t first_table_offset = ComputeOffsetToFirstTable(*hdr);
1210
1211
11.7k
  hdr->compressed_offset = file.offset();
1212
11.7k
  if (PREDICT_FALSE(hdr->compressed_offset >
1213
11.7k
                    std::numeric_limits<uint32_t>::max())) {
1214
0
    return FONT_COMPRESSION_FAILURE();
1215
0
  }
1216
11.7k
  uint64_t src_offset = Round4(hdr->compressed_offset + hdr->compressed_length);
1217
11.7k
  uint64_t dst_offset = first_table_offset;
1218
1219
1220
11.7k
  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
261
    return FONT_COMPRESSION_FAILURE();
1227
261
  }
1228
11.5k
  if (meta_offset) {
1229
140
    if (PREDICT_FALSE(src_offset != meta_offset)) {
1230
75
      return FONT_COMPRESSION_FAILURE();
1231
75
    }
1232
65
    src_offset = Round4(meta_offset + meta_length);
1233
65
    if (PREDICT_FALSE(src_offset > std::numeric_limits<uint32_t>::max())) {
1234
0
      return FONT_COMPRESSION_FAILURE();
1235
0
    }
1236
65
  }
1237
1238
11.4k
  if (priv_offset) {
1239
95
    if (PREDICT_FALSE(src_offset != priv_offset)) {
1240
68
      return FONT_COMPRESSION_FAILURE();
1241
68
    }
1242
27
    src_offset = Round4(priv_offset + priv_length);
1243
27
    if (PREDICT_FALSE(src_offset > std::numeric_limits<uint32_t>::max())) {
1244
0
      return FONT_COMPRESSION_FAILURE();
1245
0
    }
1246
27
  }
1247
1248
11.3k
  if (PREDICT_FALSE(src_offset != Round4(length))) {
1249
84
    return FONT_COMPRESSION_FAILURE();
1250
84
  }
1251
1252
11.2k
  return true;
1253
11.3k
}
1254
1255
// Write everything before the actual table data
1256
bool WriteHeaders(const uint8_t* data, size_t length, RebuildMetadata* metadata,
1257
11.2k
                  WOFF2Header* hdr, WOFF2Out* out) {
1258
11.2k
  std::vector<uint8_t> output(ComputeOffsetToFirstTable(*hdr), 0);
1259
1260
  // Re-order tables in output (OTSpec) order
1261
11.2k
  std::vector<Table> sorted_tables(hdr->tables);
1262
11.2k
  if (hdr->header_version) {
1263
    // collection; we have to sort the table offset vector in each font
1264
6.23k
    for (auto& ttc_font : hdr->ttc_fonts) {
1265
6.23k
      std::map<uint32_t, uint16_t> sorted_index_by_tag;
1266
215k
      for (auto table_index : ttc_font.table_indices) {
1267
215k
        sorted_index_by_tag[hdr->tables[table_index].tag] = table_index;
1268
215k
      }
1269
6.23k
      uint16_t index = 0;
1270
51.4k
      for (auto& i : sorted_index_by_tag) {
1271
51.4k
        ttc_font.table_indices[index++] = i.second;
1272
51.4k
      }
1273
6.23k
    }
1274
10.8k
  } else {
1275
    // non-collection; we can just sort the tables
1276
10.8k
    std::sort(sorted_tables.begin(), sorted_tables.end());
1277
10.8k
  }
1278
1279
  // Start building the font
1280
11.2k
  uint8_t* result = &output[0];
1281
11.2k
  size_t offset = 0;
1282
11.2k
  if (hdr->header_version) {
1283
    // TTC header
1284
415
    offset = StoreU32(result, offset, hdr->flavor);  // TAG TTCTag
1285
415
    offset = StoreU32(result, offset, hdr->header_version);  // FIXED Version
1286
415
    offset = StoreU32(result, offset, hdr->ttc_fonts.size());  // ULONG numFonts
1287
    // Space for ULONG OffsetTable[numFonts] (zeroed initially)
1288
415
    size_t offset_table = offset;  // keep start of offset table for later
1289
6.64k
    for (size_t i = 0; i < hdr->ttc_fonts.size(); i++) {
1290
6.23k
      offset = StoreU32(result, offset, 0);  // will fill real values in later
1291
6.23k
    }
1292
    // space for DSIG fields for header v2
1293
415
    if (hdr->header_version == 0x00020000) {
1294
276
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigTag
1295
276
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigLength
1296
276
      offset = StoreU32(result, offset, 0);  // ULONG ulDsigOffset
1297
276
    }
1298
1299
    // write Offset Tables and store the location of each in TTC Header
1300
415
    metadata->font_infos.resize(hdr->ttc_fonts.size());
1301
6.64k
    for (size_t i = 0; i < hdr->ttc_fonts.size(); i++) {
1302
6.23k
      TtcFont& ttc_font = hdr->ttc_fonts[i];
1303
1304
      // write Offset Table location into TTC Header
1305
6.23k
      offset_table = StoreU32(result, offset_table, offset);
1306
1307
      // write the actual offset table so our header doesn't lie
1308
6.23k
      ttc_font.dst_offset = offset;
1309
6.23k
      offset = StoreOffsetTable(result, offset, ttc_font.flavor,
1310
6.23k
                                ttc_font.table_indices.size());
1311
1312
215k
      for (const auto table_index : ttc_font.table_indices) {
1313
215k
        uint32_t tag = hdr->tables[table_index].tag;
1314
215k
        metadata->font_infos[i].table_entry_by_tag[tag] = offset;
1315
215k
        offset = StoreTableEntry(result, offset, tag);
1316
215k
      }
1317
1318
6.23k
      ttc_font.header_checksum = ComputeULongSum(&output[ttc_font.dst_offset],
1319
6.23k
                                                 offset - ttc_font.dst_offset);
1320
6.23k
    }
1321
10.8k
  } else {
1322
10.8k
    metadata->font_infos.resize(1);
1323
10.8k
    offset = StoreOffsetTable(result, offset, hdr->flavor, hdr->num_tables);
1324
1.09M
    for (uint16_t i = 0; i < hdr->num_tables; ++i) {
1325
1.08M
      metadata->font_infos[0].table_entry_by_tag[sorted_tables[i].tag] = offset;
1326
1.08M
      offset = StoreTableEntry(result, offset, sorted_tables[i].tag);
1327
1.08M
    }
1328
10.8k
  }
1329
1330
11.2k
  if (PREDICT_FALSE(!out->Write(&output[0], output.size()))) {
1331
0
    return FONT_COMPRESSION_FAILURE();
1332
0
  }
1333
11.2k
  metadata->header_checksum = ComputeULongSum(&output[0], output.size());
1334
11.2k
  return true;
1335
11.2k
}
1336
1337
}  // namespace
1338
1339
6.45k
size_t ComputeWOFF2FinalSize(const uint8_t* data, size_t length) {
1340
6.45k
  Buffer file(data, length);
1341
6.45k
  uint32_t total_length;
1342
1343
6.45k
  if (!file.Skip(16) ||
1344
6.45k
      !file.ReadU32(&total_length)) {
1345
128
    return 0;
1346
128
  }
1347
6.32k
  return total_length;
1348
6.45k
}
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
13.6k
                       WOFF2Out* out) {
1358
13.6k
  RebuildMetadata metadata;
1359
13.6k
  WOFF2Header hdr;
1360
13.6k
  if (!ReadWOFF2Header(data, length, &hdr)) {
1361
2.37k
    return FONT_COMPRESSION_FAILURE();
1362
2.37k
  }
1363
1364
11.2k
  if (!WriteHeaders(data, length, &metadata, &hdr, out)) {
1365
0
    return FONT_COMPRESSION_FAILURE();
1366
0
  }
1367
1368
11.2k
  const float compression_ratio = (float) hdr.uncompressed_size / length;
1369
11.2k
  if (compression_ratio > kMaxPlausibleCompressionRatio) {
1370
#ifdef FONT_COMPRESSION_BIN
1371
    fprintf(stderr, "Implausible compression ratio %.01f\n", compression_ratio);
1372
#endif
1373
1.60k
    return FONT_COMPRESSION_FAILURE();
1374
1.60k
  }
1375
1376
9.68k
  const uint8_t* src_buf = data + hdr.compressed_offset;
1377
9.68k
  std::vector<uint8_t> uncompressed_buf(hdr.uncompressed_size);
1378
9.68k
  if (PREDICT_FALSE(hdr.uncompressed_size < 1)) {
1379
86
    return FONT_COMPRESSION_FAILURE();
1380
86
  }
1381
9.59k
  if (PREDICT_FALSE(!Woff2Uncompress(&uncompressed_buf[0],
1382
9.59k
                                     hdr.uncompressed_size, src_buf,
1383
9.59k
                                     hdr.compressed_length))) {
1384
7.49k
    return FONT_COMPRESSION_FAILURE();
1385
7.49k
  }
1386
1387
3.15k
  for (size_t i = 0; i < metadata.font_infos.size(); i++) {
1388
2.58k
    if (PREDICT_FALSE(!ReconstructFont(&uncompressed_buf[0],
1389
2.58k
                                       hdr.uncompressed_size,
1390
2.58k
                                       &metadata, &hdr, i, out))) {
1391
1.53k
      return FONT_COMPRESSION_FAILURE();
1392
1.53k
    }
1393
2.58k
  }
1394
1395
568
  return true;
1396
2.10k
}
1397
1398
} // namespace woff2