Home | History | Annotate | Download | only in src
      1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 // This is the implementation of decompression of the proposed WOFF Ultra
      6 // Condensed file format.
      7 
      8 #include <cassert>
      9 #include <cstdlib>
     10 #include <vector>
     11 
     12 #include <zlib.h>
     13 
     14 #include "third_party/brotli/src/brotli/dec/decode.h"
     15 
     16 #include "opentype-sanitiser.h"
     17 #include "ots-memory-stream.h"
     18 #include "ots.h"
     19 #include "woff2.h"
     20 
     21 namespace {
     22 
     23 // simple glyph flags
     24 const int kGlyfOnCurve = 1 << 0;
     25 const int kGlyfXShort = 1 << 1;
     26 const int kGlyfYShort = 1 << 2;
     27 const int kGlyfRepeat = 1 << 3;
     28 const int kGlyfThisXIsSame = 1 << 4;
     29 const int kGlyfThisYIsSame = 1 << 5;
     30 
     31 // composite glyph flags
     32 const int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;
     33 const int FLAG_WE_HAVE_A_SCALE = 1 << 3;
     34 const int FLAG_MORE_COMPONENTS = 1 << 5;
     35 const int FLAG_WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6;
     36 const int FLAG_WE_HAVE_A_TWO_BY_TWO = 1 << 7;
     37 const int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;
     38 
     39 const size_t kSfntHeaderSize = 12;
     40 const size_t kSfntEntrySize = 16;
     41 const size_t kCheckSumAdjustmentOffset = 8;
     42 
     43 const size_t kEndPtsOfContoursOffset = 10;
     44 const size_t kCompositeGlyphBegin = 10;
     45 
     46 // Note that the byte order is big-endian, not the same as ots.cc
     47 #define TAG(a, b, c, d) ((a << 24) | (b << 16) | (c << 8) | d)
     48 
     49 const unsigned int kWoff2FlagsContinueStream = 1 << 4;
     50 const unsigned int kWoff2FlagsTransform = 1 << 5;
     51 
     52 // Compression type values common to both short and long formats
     53 const uint32_t kCompressionTypeMask = 0xf;
     54 const uint32_t kCompressionTypeNone = 0;
     55 const uint32_t kCompressionTypeGzip = 1;
     56 const uint32_t kCompressionTypeBrotli = 2;
     57 
     58 const uint32_t kKnownTags[] = {
     59   TAG('c', 'm', 'a', 'p'),  // 0
     60   TAG('h', 'e', 'a', 'd'),  // 1
     61   TAG('h', 'h', 'e', 'a'),  // 2
     62   TAG('h', 'm', 't', 'x'),  // 3
     63   TAG('m', 'a', 'x', 'p'),  // 4
     64   TAG('n', 'a', 'm', 'e'),  // 5
     65   TAG('O', 'S', '/', '2'),  // 6
     66   TAG('p', 'o', 's', 't'),  // 7
     67   TAG('c', 'v', 't', ' '),  // 8
     68   TAG('f', 'p', 'g', 'm'),  // 9
     69   TAG('g', 'l', 'y', 'f'),  // 10
     70   TAG('l', 'o', 'c', 'a'),  // 11
     71   TAG('p', 'r', 'e', 'p'),  // 12
     72   TAG('C', 'F', 'F', ' '),  // 13
     73   TAG('V', 'O', 'R', 'G'),  // 14
     74   TAG('E', 'B', 'D', 'T'),  // 15
     75   TAG('E', 'B', 'L', 'C'),  // 16
     76   TAG('g', 'a', 's', 'p'),  // 17
     77   TAG('h', 'd', 'm', 'x'),  // 18
     78   TAG('k', 'e', 'r', 'n'),  // 19
     79   TAG('L', 'T', 'S', 'H'),  // 20
     80   TAG('P', 'C', 'L', 'T'),  // 21
     81   TAG('V', 'D', 'M', 'X'),  // 22
     82   TAG('v', 'h', 'e', 'a'),  // 23
     83   TAG('v', 'm', 't', 'x'),  // 24
     84   TAG('B', 'A', 'S', 'E'),  // 25
     85   TAG('G', 'D', 'E', 'F'),  // 26
     86   TAG('G', 'P', 'O', 'S'),  // 27
     87   TAG('G', 'S', 'U', 'B'),  // 28
     88   TAG('E', 'B', 'S', 'C'),  // 29
     89   TAG('J', 'S', 'T', 'F'),  // 30
     90   TAG('M', 'A', 'T', 'H'),  // 31
     91   TAG('C', 'B', 'D', 'T'),  // 32
     92   TAG('C', 'B', 'L', 'C'),  // 33
     93   TAG('C', 'O', 'L', 'R'),  // 34
     94   TAG('C', 'P', 'A', 'L'),  // 35
     95   TAG('S', 'V', 'G', ' '),  // 36
     96   TAG('s', 'b', 'i', 'x'),  // 37
     97   TAG('a', 'c', 'n', 't'),  // 38
     98   TAG('a', 'v', 'a', 'r'),  // 39
     99   TAG('b', 'd', 'a', 't'),  // 40
    100   TAG('b', 'l', 'o', 'c'),  // 41
    101   TAG('b', 's', 'l', 'n'),  // 42
    102   TAG('c', 'v', 'a', 'r'),  // 43
    103   TAG('f', 'd', 's', 'c'),  // 44
    104   TAG('f', 'e', 'a', 't'),  // 45
    105   TAG('f', 'm', 't', 'x'),  // 46
    106   TAG('f', 'v', 'a', 'r'),  // 47
    107   TAG('g', 'v', 'a', 'r'),  // 48
    108   TAG('h', 's', 't', 'y'),  // 49
    109   TAG('j', 'u', 's', 't'),  // 50
    110   TAG('l', 'c', 'a', 'r'),  // 51
    111   TAG('m', 'o', 'r', 't'),  // 52
    112   TAG('m', 'o', 'r', 'x'),  // 53
    113   TAG('o', 'p', 'b', 'd'),  // 54
    114   TAG('p', 'r', 'o', 'p'),  // 55
    115   TAG('t', 'r', 'a', 'k'),  // 56
    116   TAG('Z', 'a', 'p', 'f'),  // 57
    117   TAG('S', 'i', 'l', 'f'),  // 58
    118   TAG('G', 'l', 'a', 't'),  // 59
    119   TAG('G', 'l', 'o', 'c'),  // 60
    120   TAG('F', 'e', 'a', 't'),  // 61
    121   TAG('S', 'i', 'l', 'l'),  // 62
    122 };
    123 
    124 struct Point {
    125   int x;
    126   int y;
    127   bool on_curve;
    128 };
    129 
    130 struct Table {
    131   uint32_t tag;
    132   uint32_t flags;
    133   uint32_t src_offset;
    134   uint32_t src_length;
    135 
    136   uint32_t transform_length;
    137 
    138   uint32_t dst_offset;
    139   uint32_t dst_length;
    140 
    141   Table()
    142       : tag(0),
    143         flags(0),
    144         src_offset(0),
    145         src_length(0),
    146         transform_length(0),
    147         dst_offset(0),
    148         dst_length(0) {}
    149 };
    150 
    151 // Based on section 6.1.1 of MicroType Express draft spec
    152 bool Read255UShort(ots::Buffer* buf, unsigned int* value) {
    153   static const int kWordCode = 253;
    154   static const int kOneMoreByteCode2 = 254;
    155   static const int kOneMoreByteCode1 = 255;
    156   static const int kLowestUCode = 253;
    157   uint8_t code = 0;
    158   if (!buf->ReadU8(&code)) {
    159     return OTS_FAILURE();
    160   }
    161   if (code == kWordCode) {
    162     uint16_t result = 0;
    163     if (!buf->ReadU16(&result)) {
    164       return OTS_FAILURE();
    165     }
    166     *value = result;
    167     return true;
    168   } else if (code == kOneMoreByteCode1) {
    169     uint8_t result = 0;
    170     if (!buf->ReadU8(&result)) {
    171       return OTS_FAILURE();
    172     }
    173     *value = result + kLowestUCode;
    174     return true;
    175   } else if (code == kOneMoreByteCode2) {
    176     uint8_t result = 0;
    177     if (!buf->ReadU8(&result)) {
    178       return OTS_FAILURE();
    179     }
    180     *value = result + kLowestUCode * 2;
    181     return true;
    182   } else {
    183     *value = code;
    184     return true;
    185   }
    186 }
    187 
    188 bool ReadBase128(ots::Buffer* buf, uint32_t* value) {
    189   uint32_t result = 0;
    190   for (size_t i = 0; i < 5; ++i) {
    191     uint8_t code = 0;
    192     if (!buf->ReadU8(&code)) {
    193       return OTS_FAILURE();
    194     }
    195     // If any of the top seven bits are set then we're about to overflow.
    196     if (result & 0xe0000000U) {
    197       return OTS_FAILURE();
    198     }
    199     result = (result << 7) | (code & 0x7f);
    200     if ((code & 0x80) == 0) {
    201       *value = result;
    202       return true;
    203     }
    204   }
    205   // Make sure not to exceed the size bound
    206   return OTS_FAILURE();
    207 }
    208 
    209 // Caller must ensure that buffer overrun won't happen.
    210 // TODO(ksakamaoto): Consider creating 'writer' version of the Buffer class
    211 // and use it across the code.
    212 size_t StoreU32(uint8_t* dst, size_t offset, uint32_t x) {
    213   dst[offset] = x >> 24;
    214   dst[offset + 1] = x >> 16;
    215   dst[offset + 2] = x >> 8;
    216   dst[offset + 3] = x;
    217   return offset + 4;
    218 }
    219 
    220 size_t Store16(uint8_t* dst, size_t offset, int x) {
    221   dst[offset] = x >> 8;
    222   dst[offset + 1] = x;
    223   return offset + 2;
    224 }
    225 
    226 int WithSign(int flag, int baseval) {
    227   assert(0 <= baseval && baseval < 65536);
    228   return (flag & 1) ? baseval : -baseval;
    229 }
    230 
    231 bool TripletDecode(const uint8_t* flags_in, const uint8_t* in, size_t in_size,
    232     unsigned int n_points, std::vector<Point>* result,
    233     size_t* in_bytes_consumed) {
    234   int x = 0;
    235   int y = 0;
    236 
    237   // Early return if |in| buffer is too small. Each point consumes 1-4 bytes.
    238   if (n_points > in_size) {
    239     return OTS_FAILURE();
    240   }
    241   unsigned int triplet_index = 0;
    242 
    243   for (unsigned int i = 0; i < n_points; ++i) {
    244     uint8_t flag = flags_in[i];
    245     bool on_curve = !(flag >> 7);
    246     flag &= 0x7f;
    247     unsigned int n_data_bytes;
    248     if (flag < 84) {
    249       n_data_bytes = 1;
    250     } else if (flag < 120) {
    251       n_data_bytes = 2;
    252     } else if (flag < 124) {
    253       n_data_bytes = 3;
    254     } else {
    255       n_data_bytes = 4;
    256     }
    257     if (triplet_index + n_data_bytes > in_size ||
    258         triplet_index + n_data_bytes < triplet_index) {
    259       return OTS_FAILURE();
    260     }
    261     int dx, dy;
    262     if (flag < 10) {
    263       dx = 0;
    264       dy = WithSign(flag, ((flag & 14) << 7) + in[triplet_index]);
    265     } else if (flag < 20) {
    266       dx = WithSign(flag, (((flag - 10) & 14) << 7) + in[triplet_index]);
    267       dy = 0;
    268     } else if (flag < 84) {
    269       int b0 = flag - 20;
    270       int b1 = in[triplet_index];
    271       dx = WithSign(flag, 1 + (b0 & 0x30) + (b1 >> 4));
    272       dy = WithSign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f));
    273     } else if (flag < 120) {
    274       int b0 = flag - 84;
    275       dx = WithSign(flag, 1 + ((b0 / 12) << 8) + in[triplet_index]);
    276       dy = WithSign(flag >> 1,
    277                     1 + (((b0 % 12) >> 2) << 8) + in[triplet_index + 1]);
    278     } else if (flag < 124) {
    279       int b2 = in[triplet_index + 1];
    280       dx = WithSign(flag, (in[triplet_index] << 4) + (b2 >> 4));
    281       dy = WithSign(flag >> 1, ((b2 & 0x0f) << 8) + in[triplet_index + 2]);
    282     } else {
    283       dx = WithSign(flag, (in[triplet_index] << 8) + in[triplet_index + 1]);
    284       dy = WithSign(flag >> 1,
    285           (in[triplet_index + 2] << 8) + in[triplet_index + 3]);
    286     }
    287     triplet_index += n_data_bytes;
    288     // Possible overflow but coordinate values are not security sensitive
    289     x += dx;
    290     y += dy;
    291     result->push_back(Point());
    292     Point& back = result->back();
    293     back.x = x;
    294     back.y = y;
    295     back.on_curve = on_curve;
    296   }
    297   *in_bytes_consumed = triplet_index;
    298   return true;
    299 }
    300 
    301 // This function stores just the point data. On entry, dst points to the
    302 // beginning of a simple glyph. Returns true on success.
    303 bool StorePoints(const std::vector<Point>& points,
    304     unsigned int n_contours, unsigned int instruction_length,
    305     uint8_t* dst, size_t dst_size, size_t* glyph_size) {
    306   // I believe that n_contours < 65536, in which case this is safe. However, a
    307   // comment and/or an assert would be good.
    308   unsigned int flag_offset = kEndPtsOfContoursOffset + 2 * n_contours + 2 +
    309     instruction_length;
    310   int last_flag = -1;
    311   int repeat_count = 0;
    312   int last_x = 0;
    313   int last_y = 0;
    314   unsigned int x_bytes = 0;
    315   unsigned int y_bytes = 0;
    316 
    317   for (size_t i = 0; i < points.size(); ++i) {
    318     const Point& point = points.at(i);
    319     int flag = point.on_curve ? kGlyfOnCurve : 0;
    320     int dx = point.x - last_x;
    321     int dy = point.y - last_y;
    322     if (dx == 0) {
    323       flag |= kGlyfThisXIsSame;
    324     } else if (dx > -256 && dx < 256) {
    325       flag |= kGlyfXShort | (dx > 0 ? kGlyfThisXIsSame : 0);
    326       x_bytes += 1;
    327     } else {
    328       x_bytes += 2;
    329     }
    330     if (dy == 0) {
    331       flag |= kGlyfThisYIsSame;
    332     } else if (dy > -256 && dy < 256) {
    333       flag |= kGlyfYShort | (dy > 0 ? kGlyfThisYIsSame : 0);
    334       y_bytes += 1;
    335     } else {
    336       y_bytes += 2;
    337     }
    338 
    339     if (flag == last_flag && repeat_count != 255) {
    340       dst[flag_offset - 1] |= kGlyfRepeat;
    341       repeat_count++;
    342     } else {
    343       if (repeat_count != 0) {
    344         if (flag_offset >= dst_size) {
    345           return OTS_FAILURE();
    346         }
    347         dst[flag_offset++] = repeat_count;
    348       }
    349       if (flag_offset >= dst_size) {
    350         return OTS_FAILURE();
    351       }
    352       dst[flag_offset++] = flag;
    353       repeat_count = 0;
    354     }
    355     last_x = point.x;
    356     last_y = point.y;
    357     last_flag = flag;
    358   }
    359 
    360   if (repeat_count != 0) {
    361     if (flag_offset >= dst_size) {
    362       return OTS_FAILURE();
    363     }
    364     dst[flag_offset++] = repeat_count;
    365   }
    366   unsigned int xy_bytes = x_bytes + y_bytes;
    367   if (xy_bytes < x_bytes ||
    368       flag_offset + xy_bytes < flag_offset ||
    369       flag_offset + xy_bytes > dst_size) {
    370     return OTS_FAILURE();
    371   }
    372 
    373   int x_offset = flag_offset;
    374   int y_offset = flag_offset + x_bytes;
    375   last_x = 0;
    376   last_y = 0;
    377   for (size_t i = 0; i < points.size(); ++i) {
    378     int dx = points.at(i).x - last_x;
    379     if (dx == 0) {
    380       // pass
    381     } else if (dx > -256 && dx < 256) {
    382       dst[x_offset++] = std::abs(dx);
    383     } else {
    384       // will always fit for valid input, but overflow is harmless
    385       x_offset = Store16(dst, x_offset, dx);
    386     }
    387     last_x += dx;
    388     int dy = points.at(i).y - last_y;
    389     if (dy == 0) {
    390       // pass
    391     } else if (dy > -256 && dy < 256) {
    392       dst[y_offset++] = std::abs(dy);
    393     } else {
    394       y_offset = Store16(dst, y_offset, dy);
    395     }
    396     last_y += dy;
    397   }
    398   *glyph_size = y_offset;
    399   return true;
    400 }
    401 
    402 // Compute the bounding box of the coordinates, and store into a glyf buffer.
    403 // A precondition is that there are at least 10 bytes available.
    404 void ComputeBbox(const std::vector<Point>& points, uint8_t* dst) {
    405   int x_min = 0;
    406   int y_min = 0;
    407   int x_max = 0;
    408   int y_max = 0;
    409 
    410   for (size_t i = 0; i < points.size(); ++i) {
    411     int x = points.at(i).x;
    412     int y = points.at(i).y;
    413     if (i == 0 || x < x_min) x_min = x;
    414     if (i == 0 || x > x_max) x_max = x;
    415     if (i == 0 || y < y_min) y_min = y;
    416     if (i == 0 || y > y_max) y_max = y;
    417   }
    418   size_t offset = 2;
    419   offset = Store16(dst, offset, x_min);
    420   offset = Store16(dst, offset, y_min);
    421   offset = Store16(dst, offset, x_max);
    422   offset = Store16(dst, offset, y_max);
    423 }
    424 
    425 // Process entire bbox stream. This is done as a separate pass to allow for
    426 // composite bbox computations (an optional more aggressive transform).
    427 bool ProcessBboxStream(ots::Buffer* bbox_stream, unsigned int n_glyphs,
    428     const std::vector<uint32_t>& loca_values, uint8_t* glyf_buf,
    429     size_t glyf_buf_length) {
    430   const uint8_t* buf = bbox_stream->buffer();
    431   if (n_glyphs >= 65536 || loca_values.size() != n_glyphs + 1) {
    432     return OTS_FAILURE();
    433   }
    434   // Safe because n_glyphs is bounded
    435   unsigned int bitmap_length = ((n_glyphs + 31) >> 5) << 2;
    436   if (!bbox_stream->Skip(bitmap_length)) {
    437     return OTS_FAILURE();
    438   }
    439   for (unsigned int i = 0; i < n_glyphs; ++i) {
    440     if (buf[i >> 3] & (0x80 >> (i & 7))) {
    441       uint32_t loca_offset = loca_values.at(i);
    442       if (loca_values.at(i + 1) - loca_offset < kEndPtsOfContoursOffset) {
    443         return OTS_FAILURE();
    444       }
    445       if (glyf_buf_length < 2 + 10 ||
    446           loca_offset > glyf_buf_length - 2 - 10) {
    447         return OTS_FAILURE();
    448       }
    449       if (!bbox_stream->Read(glyf_buf + loca_offset + 2, 8)) {
    450         return OTS_FAILURE();
    451       }
    452     }
    453   }
    454   return true;
    455 }
    456 
    457 bool ProcessComposite(ots::Buffer* composite_stream, uint8_t* dst,
    458     size_t dst_size, size_t* glyph_size, bool* have_instructions) {
    459   size_t start_offset = composite_stream->offset();
    460   bool we_have_instructions = false;
    461 
    462   uint16_t flags = FLAG_MORE_COMPONENTS;
    463   while (flags & FLAG_MORE_COMPONENTS) {
    464     if (!composite_stream->ReadU16(&flags)) {
    465       return OTS_FAILURE();
    466     }
    467     we_have_instructions |= (flags & FLAG_WE_HAVE_INSTRUCTIONS) != 0;
    468     size_t arg_size = 2;  // glyph index
    469     if (flags & FLAG_ARG_1_AND_2_ARE_WORDS) {
    470       arg_size += 4;
    471     } else {
    472       arg_size += 2;
    473     }
    474     if (flags & FLAG_WE_HAVE_A_SCALE) {
    475       arg_size += 2;
    476     } else if (flags & FLAG_WE_HAVE_AN_X_AND_Y_SCALE) {
    477       arg_size += 4;
    478     } else if (flags & FLAG_WE_HAVE_A_TWO_BY_TWO) {
    479       arg_size += 8;
    480     }
    481     if (!composite_stream->Skip(arg_size)) {
    482       return OTS_FAILURE();
    483     }
    484   }
    485   size_t composite_glyph_size = composite_stream->offset() - start_offset;
    486   if (composite_glyph_size + kCompositeGlyphBegin > dst_size) {
    487     return OTS_FAILURE();
    488   }
    489   Store16(dst, 0, 0xffff);  // nContours = -1 for composite glyph
    490   std::memcpy(dst + kCompositeGlyphBegin,
    491       composite_stream->buffer() + start_offset,
    492       composite_glyph_size);
    493   *glyph_size = kCompositeGlyphBegin + composite_glyph_size;
    494   *have_instructions = we_have_instructions;
    495   return true;
    496 }
    497 
    498 // Build TrueType loca table
    499 bool StoreLoca(const std::vector<uint32_t>& loca_values, int index_format,
    500     uint8_t* dst, size_t dst_size) {
    501   const uint64_t loca_size = loca_values.size();
    502   const uint64_t offset_size = index_format ? 4 : 2;
    503   if ((loca_size << 2) >> 2 != loca_size) {
    504     return OTS_FAILURE();
    505   }
    506   // No integer overflow here (loca_size <= 2^16).
    507   if (offset_size * loca_size > dst_size) {
    508     return OTS_FAILURE();
    509   }
    510   size_t offset = 0;
    511   for (size_t i = 0; i < loca_values.size(); ++i) {
    512     uint32_t value = loca_values.at(i);
    513     if (index_format) {
    514       offset = StoreU32(dst, offset, value);
    515     } else {
    516       offset = Store16(dst, offset, value >> 1);
    517     }
    518   }
    519   return true;
    520 }
    521 
    522 // Reconstruct entire glyf table based on transformed original
    523 bool ReconstructGlyf(const uint8_t* data, size_t data_size,
    524     uint8_t* dst, size_t dst_size,
    525     uint8_t* loca_buf, size_t loca_size) {
    526   static const int kNumSubStreams = 7;
    527   ots::Buffer file(data, data_size);
    528   uint32_t version;
    529   std::vector<std::pair<const uint8_t*, size_t> > substreams(kNumSubStreams);
    530 
    531   if (!file.ReadU32(&version)) {
    532     return OTS_FAILURE();
    533   }
    534   uint16_t num_glyphs;
    535   uint16_t index_format;
    536   if (!file.ReadU16(&num_glyphs) ||
    537       !file.ReadU16(&index_format)) {
    538     return OTS_FAILURE();
    539   }
    540   unsigned int offset = (2 + kNumSubStreams) * 4;
    541   if (offset > data_size) {
    542     return OTS_FAILURE();
    543   }
    544   // Invariant from here on: data_size >= offset
    545   for (int i = 0; i < kNumSubStreams; ++i) {
    546     uint32_t substream_size;
    547     if (!file.ReadU32(&substream_size)) {
    548       return OTS_FAILURE();
    549     }
    550     if (substream_size > data_size - offset) {
    551       return OTS_FAILURE();
    552     }
    553     substreams.at(i) = std::make_pair(data + offset, substream_size);
    554     offset += substream_size;
    555   }
    556   ots::Buffer n_contour_stream(substreams.at(0).first, substreams.at(0).second);
    557   ots::Buffer n_points_stream(substreams.at(1).first, substreams.at(1).second);
    558   ots::Buffer flag_stream(substreams.at(2).first, substreams.at(2).second);
    559   ots::Buffer glyph_stream(substreams.at(3).first, substreams.at(3).second);
    560   ots::Buffer composite_stream(substreams.at(4).first, substreams.at(4).second);
    561   ots::Buffer bbox_stream(substreams.at(5).first, substreams.at(5).second);
    562   ots::Buffer instruction_stream(substreams.at(6).first,
    563                                  substreams.at(6).second);
    564 
    565   std::vector<uint32_t> loca_values;
    566   loca_values.reserve(num_glyphs + 1);
    567   std::vector<unsigned int> n_points_vec;
    568   std::vector<Point> points;
    569   uint32_t loca_offset = 0;
    570   for (unsigned int i = 0; i < num_glyphs; ++i) {
    571     size_t glyph_size = 0;
    572     uint16_t n_contours = 0;
    573     if (!n_contour_stream.ReadU16(&n_contours)) {
    574       return OTS_FAILURE();
    575     }
    576     uint8_t* glyf_dst = dst + loca_offset;
    577     size_t glyf_dst_size = dst_size - loca_offset;
    578     if (n_contours == 0xffff) {
    579       // composite glyph
    580       bool have_instructions = false;
    581       unsigned int instruction_size = 0;
    582       if (!ProcessComposite(&composite_stream, glyf_dst, glyf_dst_size,
    583             &glyph_size, &have_instructions)) {
    584         return OTS_FAILURE();
    585       }
    586       if (have_instructions) {
    587         if (!Read255UShort(&glyph_stream, &instruction_size)) {
    588           return OTS_FAILURE();
    589         }
    590         // No integer overflow here (instruction_size < 2^16).
    591         if (instruction_size + 2 > glyf_dst_size - glyph_size) {
    592           return OTS_FAILURE();
    593         }
    594         Store16(glyf_dst, glyph_size, instruction_size);
    595         if (!instruction_stream.Read(glyf_dst + glyph_size + 2,
    596               instruction_size)) {
    597           return OTS_FAILURE();
    598         }
    599         glyph_size += instruction_size + 2;
    600       }
    601     } else if (n_contours > 0) {
    602       // simple glyph
    603       n_points_vec.clear();
    604       points.clear();
    605       unsigned int total_n_points = 0;
    606       unsigned int n_points_contour;
    607       for (unsigned int j = 0; j < n_contours; ++j) {
    608         if (!Read255UShort(&n_points_stream, &n_points_contour)) {
    609           return OTS_FAILURE();
    610         }
    611         n_points_vec.push_back(n_points_contour);
    612         if (total_n_points + n_points_contour < total_n_points) {
    613           return OTS_FAILURE();
    614         }
    615         total_n_points += n_points_contour;
    616       }
    617       unsigned int flag_size = total_n_points;
    618       if (flag_size > flag_stream.length() - flag_stream.offset()) {
    619         return OTS_FAILURE();
    620       }
    621       const uint8_t* flags_buf = flag_stream.buffer() + flag_stream.offset();
    622       const uint8_t* triplet_buf = glyph_stream.buffer() +
    623         glyph_stream.offset();
    624       size_t triplet_size = glyph_stream.length() - glyph_stream.offset();
    625       size_t triplet_bytes_consumed = 0;
    626       if (!TripletDecode(flags_buf, triplet_buf, triplet_size, total_n_points,
    627             &points, &triplet_bytes_consumed)) {
    628         return OTS_FAILURE();
    629       }
    630       const uint32_t header_and_endpts_contours_size =
    631           kEndPtsOfContoursOffset + 2 * n_contours;
    632       if (glyf_dst_size < header_and_endpts_contours_size) {
    633         return OTS_FAILURE();
    634       }
    635       Store16(glyf_dst, 0, n_contours);
    636       ComputeBbox(points, glyf_dst);
    637       size_t offset = kEndPtsOfContoursOffset;
    638       int end_point = -1;
    639       for (unsigned int contour_ix = 0; contour_ix < n_contours; ++contour_ix) {
    640         end_point += n_points_vec.at(contour_ix);
    641         if (end_point >= 65536) {
    642           return OTS_FAILURE();
    643         }
    644         offset = Store16(glyf_dst, offset, end_point);
    645       }
    646       if (!flag_stream.Skip(flag_size)) {
    647         return OTS_FAILURE();
    648       }
    649       if (!glyph_stream.Skip(triplet_bytes_consumed)) {
    650         return OTS_FAILURE();
    651       }
    652       unsigned int instruction_size;
    653       if (!Read255UShort(&glyph_stream, &instruction_size)) {
    654         return OTS_FAILURE();
    655       }
    656       // No integer overflow here (instruction_size < 2^16).
    657       if (glyf_dst_size - header_and_endpts_contours_size <
    658           instruction_size + 2) {
    659         return OTS_FAILURE();
    660       }
    661       uint8_t* instruction_dst = glyf_dst + header_and_endpts_contours_size;
    662       Store16(instruction_dst, 0, instruction_size);
    663       if (!instruction_stream.Read(instruction_dst + 2, instruction_size)) {
    664         return OTS_FAILURE();
    665       }
    666       if (!StorePoints(points, n_contours, instruction_size,
    667             glyf_dst, glyf_dst_size, &glyph_size)) {
    668         return OTS_FAILURE();
    669       }
    670     } else {
    671       glyph_size = 0;
    672     }
    673     loca_values.push_back(loca_offset);
    674     if (glyph_size + 3 < glyph_size) {
    675       return OTS_FAILURE();
    676     }
    677     glyph_size = ots::Round2(glyph_size);
    678     if (glyph_size > dst_size - loca_offset) {
    679       // This shouldn't happen, but this test defensively maintains the
    680       // invariant that loca_offset <= dst_size.
    681       return OTS_FAILURE();
    682     }
    683     loca_offset += glyph_size;
    684   }
    685   loca_values.push_back(loca_offset);
    686   assert(loca_values.size() == static_cast<size_t>(num_glyphs + 1));
    687   if (!ProcessBboxStream(&bbox_stream, num_glyphs, loca_values,
    688           dst, dst_size)) {
    689     return OTS_FAILURE();
    690   }
    691   return StoreLoca(loca_values, index_format, loca_buf, loca_size);
    692 }
    693 
    694 // This is linear search, but could be changed to binary because we
    695 // do have a guarantee that the tables are sorted by tag. But the total
    696 // cpu time is expected to be very small in any case.
    697 const Table* FindTable(const std::vector<Table>& tables, uint32_t tag) {
    698   size_t n_tables = tables.size();
    699   for (size_t i = 0; i < n_tables; ++i) {
    700     if (tables.at(i).tag == tag) {
    701       return &tables.at(i);
    702     }
    703   }
    704   return NULL;
    705 }
    706 
    707 bool ReconstructTransformed(const std::vector<Table>& tables, uint32_t tag,
    708     const uint8_t* transformed_buf, size_t transformed_size,
    709     uint8_t* dst, size_t dst_length) {
    710   if (tag == TAG('g', 'l', 'y', 'f')) {
    711     const Table* glyf_table = FindTable(tables, tag);
    712     const Table* loca_table = FindTable(tables, TAG('l', 'o', 'c', 'a'));
    713     if (glyf_table == NULL || loca_table == NULL) {
    714       return OTS_FAILURE();
    715     }
    716     if (static_cast<uint64_t>(glyf_table->dst_offset) + glyf_table->dst_length >
    717         dst_length) {
    718       return OTS_FAILURE();
    719     }
    720     if (static_cast<uint64_t>(loca_table->dst_offset) + loca_table->dst_length >
    721         dst_length) {
    722       return OTS_FAILURE();
    723     }
    724     return ReconstructGlyf(transformed_buf, transformed_size,
    725         dst + glyf_table->dst_offset, glyf_table->dst_length,
    726         dst + loca_table->dst_offset, loca_table->dst_length);
    727   } else if (tag == TAG('l', 'o', 'c', 'a')) {
    728     // processing was already done by glyf table, but validate
    729     if (!FindTable(tables, TAG('g', 'l', 'y', 'f'))) {
    730       return OTS_FAILURE();
    731     }
    732   } else {
    733     // transform for the tag is not known
    734     return OTS_FAILURE();
    735   }
    736   return true;
    737 }
    738 
    739 uint32_t ComputeChecksum(const uint8_t* buf, size_t size) {
    740   uint32_t checksum = 0;
    741   for (size_t i = 0; i < size; i += 4) {
    742     // We assume the addition is mod 2^32, which is valid because unsigned
    743     checksum += (buf[i] << 24) | (buf[i + 1] << 16) |
    744       (buf[i + 2] << 8) | buf[i + 3];
    745   }
    746   return checksum;
    747 }
    748 
    749 bool FixChecksums(const std::vector<Table>& tables, uint8_t* dst) {
    750   const Table* head_table = FindTable(tables, TAG('h', 'e', 'a', 'd'));
    751   if (head_table == NULL ||
    752       head_table->dst_length < kCheckSumAdjustmentOffset + 4) {
    753     return OTS_FAILURE();
    754   }
    755   size_t adjustment_offset = head_table->dst_offset + kCheckSumAdjustmentOffset;
    756   if (adjustment_offset < head_table->dst_offset) {
    757     return OTS_FAILURE();
    758   }
    759   StoreU32(dst, adjustment_offset, 0);
    760   size_t n_tables = tables.size();
    761   uint32_t file_checksum = 0;
    762   for (size_t i = 0; i < n_tables; ++i) {
    763     const Table* table = &tables.at(i);
    764     size_t table_length = table->dst_length;
    765     uint8_t* table_data = dst + table->dst_offset;
    766     uint32_t checksum = ComputeChecksum(table_data, table_length);
    767     StoreU32(dst, kSfntHeaderSize + i * kSfntEntrySize + 4, checksum);
    768     file_checksum += checksum;  // The addition is mod 2^32
    769   }
    770   file_checksum += ComputeChecksum(dst,
    771       kSfntHeaderSize + kSfntEntrySize * n_tables);
    772   uint32_t checksum_adjustment = 0xb1b0afba - file_checksum;
    773   StoreU32(dst, adjustment_offset, checksum_adjustment);
    774   return true;
    775 }
    776 
    777 bool Woff2Uncompress(uint8_t* dst_buf, size_t dst_size,
    778     const uint8_t* src_buf, size_t src_size, uint32_t compression_type) {
    779   if (compression_type == kCompressionTypeGzip) {
    780     uLongf uncompressed_length = dst_size;
    781     int r = uncompress(reinterpret_cast<Bytef *>(dst_buf), &uncompressed_length,
    782         src_buf, src_size);
    783     if (r != Z_OK || uncompressed_length != dst_size) {
    784       return OTS_FAILURE();
    785     }
    786     return true;
    787   } else if (compression_type == kCompressionTypeBrotli) {
    788     size_t uncompressed_size = dst_size;
    789     int ok = BrotliDecompressBuffer(src_size, src_buf,
    790                                     &uncompressed_size, dst_buf);
    791     if (!ok || uncompressed_size != dst_size) {
    792       return OTS_FAILURE();
    793     }
    794     return true;
    795   }
    796   // Unknown compression type
    797   return OTS_FAILURE();
    798 }
    799 
    800 bool ReadShortDirectory(ots::Buffer* file, std::vector<Table>* tables,
    801     size_t num_tables) {
    802   for (size_t i = 0; i < num_tables; ++i) {
    803     Table* table = &tables->at(i);
    804     uint8_t flag_byte;
    805     if (!file->ReadU8(&flag_byte)) {
    806       return OTS_FAILURE();
    807     }
    808     uint32_t tag;
    809     if ((flag_byte & 0x3f) == 0x3f) {
    810       if (!file->ReadU32(&tag)) {
    811         return OTS_FAILURE();
    812       }
    813     } else {
    814       tag = kKnownTags[flag_byte & 0x3f];
    815     }
    816     // Bits 6 and 7 are reserved and must be 0.
    817     if ((flag_byte & 0xc0) != 0) {
    818       return OTS_FAILURE();
    819     }
    820     uint32_t flags = kCompressionTypeBrotli;
    821     if (i > 0) {
    822       flags |= kWoff2FlagsContinueStream;
    823     }
    824     // Always transform the glyf and loca tables
    825     if (tag == TAG('g', 'l', 'y', 'f') ||
    826         tag == TAG('l', 'o', 'c', 'a')) {
    827       flags |= kWoff2FlagsTransform;
    828     }
    829     uint32_t dst_length;
    830     if (!ReadBase128(file, &dst_length)) {
    831       return OTS_FAILURE();
    832     }
    833     uint32_t transform_length = dst_length;
    834     if ((flags & kWoff2FlagsTransform) != 0) {
    835       if (!ReadBase128(file, &transform_length)) {
    836         return OTS_FAILURE();
    837       }
    838     }
    839     // Disallow huge numbers (> 1GB) for sanity.
    840     if (transform_length > 1024 * 1024 * 1024 ||
    841         dst_length > 1024 * 1024 * 1024) {
    842       return OTS_FAILURE();
    843     }
    844     table->tag = tag;
    845     table->flags = flags;
    846     table->transform_length = transform_length;
    847     table->dst_length = dst_length;
    848   }
    849   return true;
    850 }
    851 
    852 }  // namespace
    853 
    854 namespace ots {
    855 
    856 size_t ComputeWOFF2FinalSize(const uint8_t* data, size_t length) {
    857   ots::Buffer file(data, length);
    858   uint32_t total_length;
    859 
    860   if (!file.Skip(16) ||
    861       !file.ReadU32(&total_length)) {
    862     return 0;
    863   }
    864   return total_length;
    865 }
    866 
    867 bool ConvertWOFF2ToTTF(uint8_t* result, size_t result_length,
    868                        const uint8_t* data, size_t length) {
    869   static const uint32_t kWoff2Signature = 0x774f4632;  // "wOF2"
    870   ots::Buffer file(data, length);
    871 
    872   uint32_t signature;
    873   uint32_t flavor;
    874   if (!file.ReadU32(&signature) || signature != kWoff2Signature ||
    875       !file.ReadU32(&flavor)) {
    876     return OTS_FAILURE();
    877   }
    878 
    879   if (!IsValidVersionTag(ntohl(flavor))) {
    880     return OTS_FAILURE();
    881   }
    882 
    883   uint32_t reported_length;
    884   if (!file.ReadU32(&reported_length) || length != reported_length) {
    885     return OTS_FAILURE();
    886   }
    887   uint16_t num_tables;
    888   if (!file.ReadU16(&num_tables) || !num_tables) {
    889     return OTS_FAILURE();
    890   }
    891   // We don't care about these fields of the header:
    892   //   uint16_t reserved
    893   //   uint32_t total_sfnt_size
    894   if (!file.Skip(6)) {
    895     return OTS_FAILURE();
    896   }
    897   uint32_t compressed_length;
    898   if (!file.ReadU32(&compressed_length)) {
    899     return OTS_FAILURE();
    900   }
    901   // We don't care about these fields of the header:
    902   //   uint16_t major_version, minor_version
    903   //   uint32_t meta_offset, meta_length, meta_orig_length
    904   //   uint32_t priv_offset, priv_length
    905   if (!file.Skip(24)) {
    906     return OTS_FAILURE();
    907   }
    908   std::vector<Table> tables(num_tables);
    909   if (!ReadShortDirectory(&file, &tables, num_tables)) {
    910     return OTS_FAILURE();
    911   }
    912   uint64_t src_offset = file.offset();
    913   uint64_t dst_offset = kSfntHeaderSize +
    914       kSfntEntrySize * static_cast<uint64_t>(num_tables);
    915   uint64_t uncompressed_sum = 0;
    916   for (uint16_t i = 0; i < num_tables; ++i) {
    917     Table* table = &tables.at(i);
    918     table->src_offset = src_offset;
    919     table->src_length = (i == 0 ? compressed_length : 0);
    920     src_offset += table->src_length;
    921     if (src_offset > std::numeric_limits<uint32_t>::max()) {
    922       return OTS_FAILURE();
    923     }
    924     src_offset = ots::Round4(src_offset);
    925     table->dst_offset = dst_offset;
    926     dst_offset += table->dst_length;
    927     if (dst_offset > std::numeric_limits<uint32_t>::max()) {
    928       return OTS_FAILURE();
    929     }
    930     dst_offset = ots::Round4(dst_offset);
    931     if ((table->flags & kCompressionTypeMask) != kCompressionTypeNone) {
    932       uncompressed_sum += table->src_length;
    933       if (uncompressed_sum > std::numeric_limits<uint32_t>::max()) {
    934         return OTS_FAILURE();
    935       }
    936     }
    937   }
    938   // Enforce same 30M limit on uncompressed tables as OTS
    939   if (uncompressed_sum > 30 * 1024 * 1024) {
    940     return OTS_FAILURE();
    941   }
    942   if (src_offset > length || dst_offset > result_length) {
    943     return OTS_FAILURE();
    944   }
    945 
    946   const uint32_t sfnt_header_and_table_directory_size = 12 + 16 * num_tables;
    947   if (sfnt_header_and_table_directory_size > result_length) {
    948     return OTS_FAILURE();
    949   }
    950 
    951   // Start building the font
    952   size_t offset = 0;
    953   offset = StoreU32(result, offset, flavor);
    954   offset = Store16(result, offset, num_tables);
    955   unsigned max_pow2 = 0;
    956   while (1u << (max_pow2 + 1) <= num_tables) {
    957     max_pow2++;
    958   }
    959   const uint16_t output_search_range = (1u << max_pow2) << 4;
    960   offset = Store16(result, offset, output_search_range);
    961   offset = Store16(result, offset, max_pow2);
    962   offset = Store16(result, offset, (num_tables << 4) - output_search_range);
    963   for (uint16_t i = 0; i < num_tables; ++i) {
    964     const Table* table = &tables.at(i);
    965     offset = StoreU32(result, offset, table->tag);
    966     offset = StoreU32(result, offset, 0);  // checksum, to fill in later
    967     offset = StoreU32(result, offset, table->dst_offset);
    968     offset = StoreU32(result, offset, table->dst_length);
    969   }
    970   std::vector<uint8_t> uncompressed_buf;
    971   bool continue_valid = false;
    972   const uint8_t* transform_buf = NULL;
    973   for (uint16_t i = 0; i < num_tables; ++i) {
    974     const Table* table = &tables.at(i);
    975     uint32_t flags = table->flags;
    976     const uint8_t* src_buf = data + table->src_offset;
    977     uint32_t compression_type = flags & kCompressionTypeMask;
    978     size_t transform_length = table->transform_length;
    979     if ((flags & kWoff2FlagsContinueStream) != 0) {
    980       if (!continue_valid) {
    981         return OTS_FAILURE();
    982       }
    983     } else if (compression_type == kCompressionTypeNone) {
    984       if (transform_length != table->src_length) {
    985         return OTS_FAILURE();
    986       }
    987       transform_buf = src_buf;
    988       continue_valid = false;
    989     } else if ((flags & kWoff2FlagsContinueStream) == 0) {
    990       uint64_t total_size = transform_length;
    991       for (uint16_t j = i + 1; j < num_tables; ++j) {
    992         if ((tables.at(j).flags & kWoff2FlagsContinueStream) == 0) {
    993           break;
    994         }
    995         total_size += tables.at(j).transform_length;
    996         if (total_size > std::numeric_limits<uint32_t>::max()) {
    997           return OTS_FAILURE();
    998         }
    999       }
   1000       // Enforce same 30M limit on uncompressed tables as OTS
   1001       if (total_size > 30 * 1024 * 1024) {
   1002         return OTS_FAILURE();
   1003       }
   1004       uncompressed_buf.resize(total_size);
   1005       if (!Woff2Uncompress(&uncompressed_buf[0], total_size,
   1006           src_buf, compressed_length, compression_type)) {
   1007         return OTS_FAILURE();
   1008       }
   1009       transform_buf = &uncompressed_buf[0];
   1010       continue_valid = true;
   1011     } else {
   1012       return OTS_FAILURE();
   1013     }
   1014 
   1015     if ((flags & kWoff2FlagsTransform) == 0) {
   1016       if (transform_length != table->dst_length) {
   1017         return OTS_FAILURE();
   1018       }
   1019       if (static_cast<uint64_t>(table->dst_offset) + transform_length >
   1020           result_length) {
   1021         return OTS_FAILURE();
   1022       }
   1023       std::memcpy(result + table->dst_offset, transform_buf,
   1024           transform_length);
   1025     } else {
   1026       if (!ReconstructTransformed(tables, table->tag,
   1027             transform_buf, transform_length, result, result_length)) {
   1028         return OTS_FAILURE();
   1029       }
   1030     }
   1031     if (continue_valid) {
   1032       transform_buf += transform_length;
   1033       if (transform_buf > &uncompressed_buf[0] + uncompressed_buf.size()) {
   1034         return OTS_FAILURE();
   1035       }
   1036     }
   1037   }
   1038 
   1039   return FixChecksums(tables, result);
   1040 }
   1041 
   1042 }  // namespace ots
   1043