1 // Copyright (c) 2009-2017 The OTS 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 #include "ots.h"
6 
7 #include <sys/types.h>
8 #include <zlib.h>
9 
10 #include <algorithm>
11 #include <cstdlib>
12 #include <cstring>
13 #include <limits>
14 #include <map>
15 #include <vector>
16 
17 #include <woff2/decode.h>
18 
19 // The OpenType Font File
20 // http://www.microsoft.com/typography/otspec/otff.htm
21 
22 #include "avar.h"
23 #include "cff.h"
24 #include "cmap.h"
25 #include "cvar.h"
26 #include "cvt.h"
27 #include "fpgm.h"
28 #include "fvar.h"
29 #include "gasp.h"
30 #include "gdef.h"
31 #include "glyf.h"
32 #include "gpos.h"
33 #include "gsub.h"
34 #include "gvar.h"
35 #include "hdmx.h"
36 #include "head.h"
37 #include "hhea.h"
38 #include "hmtx.h"
39 #include "hvar.h"
40 #include "kern.h"
41 #include "loca.h"
42 #include "ltsh.h"
43 #include "math_.h"
44 #include "maxp.h"
45 #include "mvar.h"
46 #include "name.h"
47 #include "os2.h"
48 #include "ots.h"
49 #include "post.h"
50 #include "prep.h"
51 #include "stat.h"
52 #include "vdmx.h"
53 #include "vhea.h"
54 #include "vmtx.h"
55 #include "vorg.h"
56 #include "vvar.h"
57 
58 // Graphite tables
59 #ifdef OTS_GRAPHITE
60 #include "feat.h"
61 #include "glat.h"
62 #include "gloc.h"
63 #include "sile.h"
64 #include "silf.h"
65 #include "sill.h"
66 #endif
67 
68 namespace ots {
69 
70 struct Arena {
71  public:
~Arenaots::Arena72   ~Arena() {
73     for (auto& hunk : hunks_) {
74       delete[] hunk;
75     }
76   }
77 
Allocateots::Arena78   uint8_t* Allocate(size_t length) {
79     uint8_t* p = new uint8_t[length];
80     hunks_.push_back(p);
81     return p;
82   }
83 
84  private:
85   std::vector<uint8_t*> hunks_;
86 };
87 
CheckTag(uint32_t tag_value)88 bool CheckTag(uint32_t tag_value) {
89   for (unsigned i = 0; i < 4; ++i) {
90     const uint32_t check = tag_value & 0xff;
91     if (check < 32 || check > 126) {
92       return false;  // non-ASCII character found.
93     }
94     tag_value >>= 8;
95   }
96   return true;
97 }
98 
99 }; // namespace ots
100 
101 namespace {
102 
103 #define OTS_MSG_TAG_(level,otf_,msg_,tag_) \
104   (OTS_MESSAGE_(level,otf_,"%c%c%c%c: %s", OTS_UNTAG(tag_), msg_), false)
105 
106 // Generate a message with or without a table tag, when 'header' is the FontFile pointer
107 #define OTS_FAILURE_MSG_TAG(msg_,tag_) OTS_MSG_TAG_(0, header, msg_, tag_)
108 #define OTS_FAILURE_MSG_HDR(...)       OTS_FAILURE_MSG_(header, __VA_ARGS__)
109 #define OTS_WARNING_MSG_HDR(...)       OTS_WARNING_MSG_(header, __VA_ARGS__)
110 
111 
112 const struct {
113   uint32_t tag;
114   bool required;
115 } supported_tables[] = {
116   { OTS_TAG_MAXP, true },
117   { OTS_TAG_HEAD, true },
118   { OTS_TAG_OS2,  true },
119   { OTS_TAG_CMAP, true },
120   { OTS_TAG_HHEA, true },
121   { OTS_TAG_HMTX, true },
122   { OTS_TAG_NAME, true },
123   { OTS_TAG_POST, true },
124   { OTS_TAG_LOCA, false },
125   { OTS_TAG_GLYF, false },
126   { OTS_TAG_CFF,  false },
127   { OTS_TAG_VDMX, false },
128   { OTS_TAG_HDMX, false },
129   { OTS_TAG_GASP, false },
130   { OTS_TAG_CVT,  false },
131   { OTS_TAG_FPGM, false },
132   { OTS_TAG_PREP, false },
133   { OTS_TAG_LTSH, false },
134   { OTS_TAG_VORG, false },
135   { OTS_TAG_KERN, false },
136   // We need to parse fvar table before other tables that may need to know
137   // the number of variation axes (if any)
138   { OTS_TAG_FVAR, false },
139   { OTS_TAG_AVAR, false },
140   { OTS_TAG_CVAR, false },
141   { OTS_TAG_GVAR, false },
142   { OTS_TAG_HVAR, false },
143   { OTS_TAG_MVAR, false },
144   { OTS_TAG_STAT, false },
145   { OTS_TAG_VVAR, false },
146   { OTS_TAG_CFF2, false },
147   // We need to parse GDEF table in advance of parsing GSUB/GPOS tables
148   // because they could refer GDEF table.
149   { OTS_TAG_GDEF, false },
150   { OTS_TAG_GPOS, false },
151   { OTS_TAG_GSUB, false },
152   { OTS_TAG_VHEA, false },
153   { OTS_TAG_VMTX, false },
154   { OTS_TAG_MATH, false },
155   // Graphite tables
156 #ifdef OTS_GRAPHITE
157   { OTS_TAG_GLOC, false },
158   { OTS_TAG_GLAT, false },
159   { OTS_TAG_FEAT, false },
160   { OTS_TAG_SILF, false },
161   { OTS_TAG_SILE, false },
162   { OTS_TAG_SILL, false },
163 #endif
164   { 0, false },
165 };
166 
ValidateVersionTag(ots::Font * font)167 bool ValidateVersionTag(ots::Font *font) {
168   switch (font->version) {
169     case 0x000010000:
170     case OTS_TAG('O','T','T','O'):
171       return true;
172     case OTS_TAG('t','r','u','e'):
173       font->version = 0x000010000;
174       return true;
175     default:
176       return false;
177   }
178 }
179 
180 bool ProcessGeneric(ots::FontFile *header,
181                     ots::Font *font,
182                     uint32_t signature,
183                     ots::OTSStream *output,
184                     const uint8_t *data, size_t length,
185                     const std::vector<ots::TableEntry>& tables,
186                     ots::Buffer& file);
187 
ProcessTTF(ots::FontFile * header,ots::Font * font,ots::OTSStream * output,const uint8_t * data,size_t length,uint32_t offset=0)188 bool ProcessTTF(ots::FontFile *header,
189                 ots::Font *font,
190                 ots::OTSStream *output, const uint8_t *data, size_t length,
191                 uint32_t offset = 0) {
192   ots::Buffer file(data + offset, length - offset);
193 
194   if (offset > length) {
195     return OTS_FAILURE_MSG_HDR("offset beyond end of file");
196   }
197 
198   // we disallow all files > 1GB in size for sanity.
199   if (length > 1024 * 1024 * 1024) {
200     return OTS_FAILURE_MSG_HDR("file exceeds 1GB");
201   }
202 
203   if (!file.ReadU32(&font->version)) {
204     return OTS_FAILURE_MSG_HDR("error reading sfntVersion");
205   }
206   if (!ValidateVersionTag(font)) {
207     return OTS_FAILURE_MSG_HDR("invalid sfntVersion: %d", font->version);
208   }
209 
210   if (!file.ReadU16(&font->num_tables) ||
211       !file.ReadU16(&font->search_range) ||
212       !file.ReadU16(&font->entry_selector) ||
213       !file.ReadU16(&font->range_shift)) {
214     return OTS_FAILURE_MSG_HDR("error reading table directory search header");
215   }
216 
217   // search_range is (Maximum power of 2 <= numTables) x 16. Thus, to avoid
218   // overflow num_tables is, at most, 2^16 / 16 = 2^12
219   if (font->num_tables >= 4096 || font->num_tables < 1) {
220     return OTS_FAILURE_MSG_HDR("excessive (or zero) number of tables");
221   }
222 
223   unsigned max_pow2 = 0;
224   while (1u << (max_pow2 + 1) <= font->num_tables) {
225     max_pow2++;
226   }
227   const uint16_t expected_search_range = (1u << max_pow2) << 4;
228 
229   // Don't call ots_failure() here since ~25% of fonts (250+ fonts) in
230   // http://www.princexml.com/fonts/ have unexpected search_range value.
231   if (font->search_range != expected_search_range) {
232     OTS_WARNING_MSG_HDR("bad search range");
233     font->search_range = expected_search_range;  // Fix the value.
234   }
235 
236   // entry_selector is Log2(maximum power of 2 <= numTables)
237   if (font->entry_selector != max_pow2) {
238     OTS_WARNING_MSG_HDR("incorrect entrySelector for table directory");
239     font->entry_selector = max_pow2;  // Fix the value.
240   }
241 
242   // range_shift is NumTables x 16-searchRange. We know that 16*num_tables
243   // doesn't over flow because we range checked it above. Also, we know that
244   // it's > font->search_range by construction of search_range.
245   const uint16_t expected_range_shift =
246       16 * font->num_tables - font->search_range;
247   if (font->range_shift != expected_range_shift) {
248     OTS_WARNING_MSG_HDR("bad range shift");
249     font->range_shift = expected_range_shift;  // the same as above.
250   }
251 
252   // Next up is the list of tables.
253   std::vector<ots::TableEntry> tables;
254 
255   for (unsigned i = 0; i < font->num_tables; ++i) {
256     ots::TableEntry table;
257     if (!file.ReadU32(&table.tag) ||
258         !file.ReadU32(&table.chksum) ||
259         !file.ReadU32(&table.offset) ||
260         !file.ReadU32(&table.length)) {
261       return OTS_FAILURE_MSG_HDR("error reading table directory");
262     }
263 
264     table.uncompressed_length = table.length;
265     tables.push_back(table);
266   }
267 
268   return ProcessGeneric(header, font, font->version, output, data, length,
269                         tables, file);
270 }
271 
ProcessTTC(ots::FontFile * header,ots::OTSStream * output,const uint8_t * data,size_t length,uint32_t index)272 bool ProcessTTC(ots::FontFile *header,
273                 ots::OTSStream *output,
274                 const uint8_t *data,
275                 size_t length,
276                 uint32_t index) {
277   ots::Buffer file(data, length);
278 
279   // we disallow all files > 1GB in size for sanity.
280   if (length > 1024 * 1024 * 1024) {
281     return OTS_FAILURE_MSG_HDR("file exceeds 1GB");
282   }
283 
284   uint32_t ttc_tag;
285   if (!file.ReadU32(&ttc_tag)) {
286     return OTS_FAILURE_MSG_HDR("Error reading TTC tag");
287   }
288   if (ttc_tag != OTS_TAG('t','t','c','f')) {
289     return OTS_FAILURE_MSG_HDR("Invalid TTC tag");
290   }
291 
292   uint32_t ttc_version;
293   if (!file.ReadU32(&ttc_version)) {
294     return OTS_FAILURE_MSG_HDR("Error reading TTC version");
295   }
296   if (ttc_version != 0x00010000 && ttc_version != 0x00020000) {
297     return OTS_FAILURE_MSG_HDR("Invalid TTC version");
298   }
299 
300   uint32_t num_fonts;
301   if (!file.ReadU32(&num_fonts)) {
302     return OTS_FAILURE_MSG_HDR("Error reading number of TTC fonts");
303   }
304   // Limit the allowed number of subfonts to have same memory allocation.
305   if (num_fonts > 0x10000) {
306     return OTS_FAILURE_MSG_HDR("Too many fonts in TTC");
307   }
308 
309   std::vector<uint32_t> offsets(num_fonts);
310   for (unsigned i = 0; i < num_fonts; i++) {
311     if (!file.ReadU32(&offsets[i])) {
312       return OTS_FAILURE_MSG_HDR("Error reading offset to OffsetTable");
313     }
314   }
315 
316   if (ttc_version == 0x00020000) {
317     // We don't care about these fields of the header:
318     // uint32_t dsig_tag, dsig_length, dsig_offset
319     if (!file.Skip(3 * 4)) {
320       return OTS_FAILURE_MSG_HDR("Error reading DSIG offset and length in TTC font");
321     }
322   }
323 
324   if (index == static_cast<uint32_t>(-1)) {
325     if (!output->WriteU32(ttc_tag) ||
326         !output->WriteU32(0x00010000) ||
327         !output->WriteU32(num_fonts) ||
328         !output->Seek((3 + num_fonts) * 4)) {
329       return OTS_FAILURE_MSG_HDR("Error writing output");
330     }
331 
332     // Keep references to the fonts processed in the loop below, as we need
333     // them for reused tables.
334     std::vector<ots::Font> fonts(num_fonts, ots::Font(header));
335 
336     for (unsigned i = 0; i < num_fonts; i++) {
337       uint32_t out_offset = output->Tell();
338       if (!output->Seek((3 + i) * 4) ||
339           !output->WriteU32(out_offset) ||
340           !output->Seek(out_offset)) {
341         return OTS_FAILURE_MSG_HDR("Error writing output");
342       }
343       if (!ProcessTTF(header, &fonts[i], output, data, length, offsets[i])) {
344         return false;
345       }
346     }
347 
348     return true;
349   } else {
350     if (index >= num_fonts) {
351       return OTS_FAILURE_MSG_HDR("Requested font index is bigger than the number of fonts in the TTC file");
352     }
353 
354     ots::Font font(header);
355     return ProcessTTF(header, &font, output, data, length, offsets[index]);
356   }
357 }
358 
ProcessWOFF(ots::FontFile * header,ots::Font * font,ots::OTSStream * output,const uint8_t * data,size_t length)359 bool ProcessWOFF(ots::FontFile *header,
360                  ots::Font *font,
361                  ots::OTSStream *output, const uint8_t *data, size_t length) {
362   ots::Buffer file(data, length);
363 
364   // we disallow all files > 1GB in size for sanity.
365   if (length > 1024 * 1024 * 1024) {
366     return OTS_FAILURE_MSG_HDR("file exceeds 1GB");
367   }
368 
369   uint32_t woff_tag;
370   if (!file.ReadU32(&woff_tag)) {
371     return OTS_FAILURE_MSG_HDR("error reading WOFF marker");
372   }
373 
374   if (woff_tag != OTS_TAG('w','O','F','F')) {
375     return OTS_FAILURE_MSG_HDR("invalid WOFF marker");
376   }
377 
378   if (!file.ReadU32(&font->version)) {
379     return OTS_FAILURE_MSG_HDR("error reading sfntVersion");
380   }
381   if (!ValidateVersionTag(font)) {
382     return OTS_FAILURE_MSG_HDR("invalid sfntVersion: %d", font->version);
383   }
384 
385   uint32_t reported_length;
386   if (!file.ReadU32(&reported_length) || length != reported_length) {
387     return OTS_FAILURE_MSG_HDR("incorrect file size in WOFF header");
388   }
389 
390   if (!file.ReadU16(&font->num_tables) || !font->num_tables) {
391     return OTS_FAILURE_MSG_HDR("error reading number of tables");
392   }
393 
394   uint16_t reserved_value;
395   if (!file.ReadU16(&reserved_value) || reserved_value) {
396     return OTS_FAILURE_MSG_HDR("error in reserved field of WOFF header");
397   }
398 
399   uint32_t reported_total_sfnt_size;
400   if (!file.ReadU32(&reported_total_sfnt_size)) {
401     return OTS_FAILURE_MSG_HDR("error reading total sfnt size");
402   }
403 
404   // We don't care about these fields of the header:
405   //   uint16_t major_version, minor_version
406   if (!file.Skip(2 * 2)) {
407     return OTS_FAILURE_MSG_HDR("Failed to read 'majorVersion' or 'minorVersion'");
408   }
409 
410   // Checks metadata block size.
411   uint32_t meta_offset;
412   uint32_t meta_length;
413   uint32_t meta_length_orig;
414   if (!file.ReadU32(&meta_offset) ||
415       !file.ReadU32(&meta_length) ||
416       !file.ReadU32(&meta_length_orig)) {
417     return OTS_FAILURE_MSG_HDR("Failed to read header metadata block fields");
418   }
419   if (meta_offset) {
420     if (meta_offset >= length || length - meta_offset < meta_length) {
421       return OTS_FAILURE_MSG_HDR("Invalid metadata block offset or length");
422     }
423   }
424 
425   // Checks private data block size.
426   uint32_t priv_offset;
427   uint32_t priv_length;
428   if (!file.ReadU32(&priv_offset) ||
429       !file.ReadU32(&priv_length)) {
430     return OTS_FAILURE_MSG_HDR("Failed to read header private block fields");
431   }
432   if (priv_offset) {
433     if (priv_offset >= length || length - priv_offset < priv_length) {
434       return OTS_FAILURE_MSG_HDR("Invalid private block offset or length");
435     }
436   }
437 
438   // Next up is the list of tables.
439   std::vector<ots::TableEntry> tables;
440 
441   uint32_t first_index = 0;
442   uint32_t last_index = 0;
443   // Size of sfnt header plus size of table records.
444   uint64_t total_sfnt_size = 12 + 16 * font->num_tables;
445   for (unsigned i = 0; i < font->num_tables; ++i) {
446     ots::TableEntry table;
447     if (!file.ReadU32(&table.tag) ||
448         !file.ReadU32(&table.offset) ||
449         !file.ReadU32(&table.length) ||
450         !file.ReadU32(&table.uncompressed_length) ||
451         !file.ReadU32(&table.chksum)) {
452       return OTS_FAILURE_MSG_HDR("error reading table directory");
453     }
454 
455     total_sfnt_size += ots::Round4(table.uncompressed_length);
456     if (total_sfnt_size > std::numeric_limits<uint32_t>::max()) {
457       return OTS_FAILURE_MSG_HDR("sfnt size overflow");
458     }
459     tables.push_back(table);
460     if (i == 0 || tables[first_index].offset > table.offset)
461       first_index = i;
462     if (i == 0 || tables[last_index].offset < table.offset)
463       last_index = i;
464   }
465 
466   if (reported_total_sfnt_size != total_sfnt_size) {
467     return OTS_FAILURE_MSG_HDR("uncompressed sfnt size mismatch");
468   }
469 
470   // Table data must follow immediately after the header.
471   if (tables[first_index].offset != ots::Round4(file.offset())) {
472     return OTS_FAILURE_MSG_HDR("junk before tables in WOFF file");
473   }
474 
475   if (tables[last_index].offset >= length ||
476       length - tables[last_index].offset < tables[last_index].length) {
477     return OTS_FAILURE_MSG_HDR("invalid table location/size");
478   }
479   // Blocks must follow immediately after the previous block.
480   // (Except for padding with a maximum of three null bytes)
481   uint64_t block_end = ots::Round4(
482       static_cast<uint64_t>(tables[last_index].offset) +
483       static_cast<uint64_t>(tables[last_index].length));
484   if (block_end > std::numeric_limits<uint32_t>::max()) {
485     return OTS_FAILURE_MSG_HDR("invalid table location/size");
486   }
487   if (meta_offset) {
488     if (block_end != meta_offset) {
489       return OTS_FAILURE_MSG_HDR("Invalid metadata block offset");
490     }
491     block_end = ots::Round4(static_cast<uint64_t>(meta_offset) +
492                             static_cast<uint64_t>(meta_length));
493     if (block_end > std::numeric_limits<uint32_t>::max()) {
494       return OTS_FAILURE_MSG_HDR("Invalid metadata block length");
495     }
496   }
497   if (priv_offset) {
498     if (block_end != priv_offset) {
499       return OTS_FAILURE_MSG_HDR("Invalid private block offset");
500     }
501     block_end = ots::Round4(static_cast<uint64_t>(priv_offset) +
502                             static_cast<uint64_t>(priv_length));
503     if (block_end > std::numeric_limits<uint32_t>::max()) {
504       return OTS_FAILURE_MSG_HDR("Invalid private block length");
505     }
506   }
507   if (block_end != ots::Round4(length)) {
508     return OTS_FAILURE_MSG_HDR("File length mismatch (trailing junk?)");
509   }
510 
511   return ProcessGeneric(header, font, woff_tag, output, data, length, tables, file);
512 }
513 
ProcessWOFF2(ots::FontFile * header,ots::OTSStream * output,const uint8_t * data,size_t length,uint32_t index)514 bool ProcessWOFF2(ots::FontFile *header,
515                   ots::OTSStream *output,
516                   const uint8_t *data,
517                   size_t length,
518                   uint32_t index) {
519   size_t decompressed_size = woff2::ComputeWOFF2FinalSize(data, length);
520 
521   if (decompressed_size < length) {
522     return OTS_FAILURE_MSG_HDR("Size of decompressed WOFF 2.0 is less than compressed size");
523   }
524 
525   if (decompressed_size == 0) {
526     return OTS_FAILURE_MSG_HDR("Size of decompressed WOFF 2.0 is set to 0");
527   }
528   // decompressed font must be <= OTS_MAX_DECOMPRESSED_FILE_SIZE
529   if (decompressed_size > OTS_MAX_DECOMPRESSED_FILE_SIZE) {
530     return OTS_FAILURE_MSG_HDR("Size of decompressed WOFF 2.0 font exceeds %gMB",
531                                OTS_MAX_DECOMPRESSED_FILE_SIZE / (1024.0 * 1024.0));
532   }
533 
534   std::string buf(decompressed_size, 0);
535   woff2::WOFF2StringOut out(&buf);
536   if (!woff2::ConvertWOFF2ToTTF(data, length, &out)) {
537     return OTS_FAILURE_MSG_HDR("Failed to convert WOFF 2.0 font to SFNT");
538   }
539   const uint8_t *decompressed = reinterpret_cast<const uint8_t*>(buf.data());
540 
541   if (data[4] == 't' && data[5] == 't' && data[6] == 'c' && data[7] == 'f') {
542     return ProcessTTC(header, output, decompressed, out.Size(), index);
543   } else {
544     ots::Font font(header);
545     return ProcessTTF(header, &font, output, decompressed, out.Size());
546   }
547 }
548 
GetTableAction(const ots::FontFile * header,uint32_t tag)549 ots::TableAction GetTableAction(const ots::FontFile *header, uint32_t tag) {
550   ots::TableAction action = header->context->GetTableAction(tag);
551 
552   if (action == ots::TABLE_ACTION_DEFAULT) {
553     action = ots::TABLE_ACTION_DROP;
554 
555     for (unsigned i = 0; ; ++i) {
556       if (supported_tables[i].tag == 0) break;
557 
558       if (supported_tables[i].tag == tag) {
559         action = ots::TABLE_ACTION_SANITIZE;
560         break;
561       }
562     }
563   }
564 
565   assert(action != ots::TABLE_ACTION_DEFAULT); // Should never return this.
566   return action;
567 }
568 
GetTableData(const uint8_t * data,const ots::TableEntry & table,ots::Arena & arena,size_t * table_length,const uint8_t ** table_data)569 bool GetTableData(const uint8_t *data,
570                   const ots::TableEntry& table,
571                   ots::Arena &arena,
572                   size_t *table_length,
573                   const uint8_t **table_data) {
574   if (table.uncompressed_length != table.length) {
575     // Compressed table. Need to uncompress into memory first.
576     *table_length = table.uncompressed_length;
577     *table_data = arena.Allocate(*table_length);
578     uLongf dest_len = *table_length;
579     int r = uncompress((Bytef*) *table_data, &dest_len,
580                        data + table.offset, table.length);
581     if (r != Z_OK || dest_len != *table_length) {
582       return false;
583     }
584   } else {
585     // Uncompressed table. We can process directly from memory.
586     *table_data = data + table.offset;
587     *table_length = table.length;
588   }
589 
590   return true;
591 }
592 
ProcessGeneric(ots::FontFile * header,ots::Font * font,uint32_t signature,ots::OTSStream * output,const uint8_t * data,size_t length,const std::vector<ots::TableEntry> & tables,ots::Buffer & file)593 bool ProcessGeneric(ots::FontFile *header,
594                     ots::Font *font,
595                     uint32_t signature,
596                     ots::OTSStream *output,
597                     const uint8_t *data, size_t length,
598                     const std::vector<ots::TableEntry>& tables,
599                     ots::Buffer& file) {
600   const size_t data_offset = file.offset();
601 
602   uint32_t uncompressed_sum = 0;
603 
604   for (unsigned i = 0; i < font->num_tables; ++i) {
605     // the tables must be sorted by tag (when taken as big-endian numbers).
606     // This also remove the possibility of duplicate tables.
607     if (i) {
608       const uint32_t this_tag = tables[i].tag;
609       const uint32_t prev_tag = tables[i - 1].tag;
610       if (this_tag <= prev_tag) {
611         OTS_WARNING_MSG_HDR("Table directory is not correctly ordered");
612       }
613     }
614 
615     // all tag names must be built from printable ASCII characters
616     if (!ots::CheckTag(tables[i].tag)) {
617       OTS_WARNING_MSG_HDR("Invalid table tag: 0x%X", tables[i].tag);
618     }
619 
620     // tables must be 4-byte aligned
621     if (tables[i].offset & 3) {
622       return OTS_FAILURE_MSG_TAG("misaligned table", tables[i].tag);
623     }
624 
625     // and must be within the file
626     if (tables[i].offset < data_offset || tables[i].offset >= length) {
627       return OTS_FAILURE_MSG_TAG("invalid table offset", tables[i].tag);
628     }
629     // disallow all tables with a zero length
630     if (tables[i].length < 1) {
631       // Note: malayalam.ttf has zero length CVT table...
632       return OTS_FAILURE_MSG_TAG("zero-length table", tables[i].tag);
633     }
634     // disallow all tables with a length > 1GB
635     if (tables[i].length > 1024 * 1024 * 1024) {
636       return OTS_FAILURE_MSG_TAG("table length exceeds 1GB", tables[i].tag);
637     }
638     // disallow tables where the uncompressed size is < the compressed size.
639     if (tables[i].uncompressed_length < tables[i].length) {
640       return OTS_FAILURE_MSG_TAG("invalid compressed table", tables[i].tag);
641     }
642     if (tables[i].uncompressed_length > tables[i].length) {
643       // We'll probably be decompressing this table.
644 
645       // disallow all tables which decompress to > OTS_MAX_DECOMPRESSED_TABLE_SIZE
646       if (tables[i].uncompressed_length > OTS_MAX_DECOMPRESSED_TABLE_SIZE) {
647         return OTS_FAILURE_MSG_HDR("%c%c%c%c: decompressed table length exceeds %gMB",
648                                    OTS_UNTAG(tables[i].tag),
649                                    OTS_MAX_DECOMPRESSED_TABLE_SIZE / (1024.0 * 1024.0));
650       }
651       if (uncompressed_sum + tables[i].uncompressed_length < uncompressed_sum) {
652         return OTS_FAILURE_MSG_TAG("overflow of decompressed sum", tables[i].tag);
653       }
654 
655       uncompressed_sum += tables[i].uncompressed_length;
656     }
657     // since we required that the file be < 1GB in length, and that the table
658     // length is < 1GB, the following addtion doesn't overflow
659     uint32_t end_byte = tables[i].offset + tables[i].length;
660     // Tables in the WOFF file must be aligned 4-byte boundary.
661     if (signature == OTS_TAG('w','O','F','F')) {
662         end_byte = ots::Round4(end_byte);
663     }
664     if (!end_byte || end_byte > length) {
665       return OTS_FAILURE_MSG_TAG("table overruns end of file", tables[i].tag);
666     }
667   }
668 
669   // All decompressed tables decompressed must be <= OTS_MAX_DECOMPRESSED_FILE_SIZE.
670   if (uncompressed_sum > OTS_MAX_DECOMPRESSED_FILE_SIZE) {
671     return OTS_FAILURE_MSG_HDR("decompressed sum exceeds %gMB",
672                                OTS_MAX_DECOMPRESSED_FILE_SIZE / (1024.0 * 1024.0));
673   }
674 
675   // check that the tables are not overlapping.
676   std::vector<std::pair<uint32_t, uint8_t> > overlap_checker;
677   for (unsigned i = 0; i < font->num_tables; ++i) {
678     overlap_checker.push_back(
679         std::make_pair(tables[i].offset, static_cast<uint8_t>(1) /* start */));
680     overlap_checker.push_back(
681         std::make_pair(tables[i].offset + tables[i].length,
682                        static_cast<uint8_t>(0) /* end */));
683   }
684   std::sort(overlap_checker.begin(), overlap_checker.end());
685   int overlap_count = 0;
686   for (unsigned i = 0; i < overlap_checker.size(); ++i) {
687     overlap_count += (overlap_checker[i].second ? 1 : -1);
688     if (overlap_count > 1) {
689       return OTS_FAILURE_MSG_HDR("overlapping tables");
690     }
691   }
692 
693   std::map<uint32_t, ots::TableEntry> table_map;
694   for (unsigned i = 0; i < font->num_tables; ++i) {
695     table_map[tables[i].tag] = tables[i];
696   }
697 
698   ots::Arena arena;
699   // Parse known tables first as we need to parse them in specific order.
700   for (unsigned i = 0; ; ++i) {
701     if (supported_tables[i].tag == 0) break;
702 
703     uint32_t tag = supported_tables[i].tag;
704     const auto &it = table_map.find(tag);
705     if (it == table_map.cend()) {
706       if (supported_tables[i].required) {
707         return OTS_FAILURE_MSG_TAG("missing required table", tag);
708       }
709     } else {
710       if (!font->ParseTable(it->second, data, arena)) {
711         return OTS_FAILURE_MSG_TAG("Failed to parse table", tag);
712       }
713     }
714   }
715 
716   // Then parse any tables left.
717   for (const auto &table_entry : tables) {
718     if (!font->GetTable(table_entry.tag)) {
719       if (!font->ParseTable(table_entry, data, arena)) {
720         return OTS_FAILURE_MSG_TAG("Failed to parse table", table_entry.tag);
721       }
722     }
723   }
724 
725   ots::Table *glyf = font->GetTable(OTS_TAG_GLYF);
726   ots::Table *loca = font->GetTable(OTS_TAG_LOCA);
727   ots::Table *cff  = font->GetTable(OTS_TAG_CFF);
728   ots::Table *cff2 = font->GetTable(OTS_TAG_CFF2);
729 
730   if (glyf && loca) {
731     if (font->version != 0x000010000) {
732       OTS_WARNING_MSG_HDR("wrong sfntVersion for glyph data");
733       font->version = 0x000010000;
734     }
735     if (cff)
736        cff->Drop("font contains both CFF and glyf/loca tables");
737     if (cff2)
738        cff2->Drop("font contains both CFF and glyf/loca tables");
739   } else if (cff || cff2) {
740     if (font->version != OTS_TAG('O','T','T','O')) {
741       OTS_WARNING_MSG_HDR("wrong sfntVersion for glyph data");
742       font->version = OTS_TAG('O','T','T','O');
743     }
744     if (glyf)
745        glyf->Drop("font contains both CFF and glyf tables");
746     if (loca)
747        loca->Drop("font contains both CFF and loca tables");
748   } else if (font->GetTable(OTS_TAG('C','B','D','T')) &&
749              font->GetTable(OTS_TAG('C','B','L','C'))) {
750       // We don't sanitize bitmap tables, but don’t reject bitmap-only fonts if
751       // we are asked to pass them thru.
752   } else {
753       return OTS_FAILURE_MSG_HDR("no supported glyph data table(s) present");
754   }
755 
756   uint16_t num_output_tables = 0;
757   for (const auto &it : table_map) {
758     ots::Table *table = font->GetTable(it.first);
759     if (table)
760       num_output_tables++;
761   }
762 
763   uint16_t max_pow2 = 0;
764   while (1u << (max_pow2 + 1) <= num_output_tables) {
765     max_pow2++;
766   }
767   const uint16_t output_search_range = (1u << max_pow2) << 4;
768 
769   // most of the errors here are highly unlikely - they'd only occur if the
770   // output stream returns a failure, e.g. lack of space to write
771   output->ResetChecksum();
772   if (!output->WriteU32(font->version) ||
773       !output->WriteU16(num_output_tables) ||
774       !output->WriteU16(output_search_range) ||
775       !output->WriteU16(max_pow2) ||
776       !output->WriteU16((num_output_tables << 4) - output_search_range)) {
777     return OTS_FAILURE_MSG_HDR("error writing output");
778   }
779   const uint32_t offset_table_chksum = output->chksum();
780 
781   const size_t table_record_offset = output->Tell();
782   if (!output->Pad(16 * num_output_tables)) {
783     return OTS_FAILURE_MSG_HDR("error writing output");
784   }
785 
786   std::vector<ots::TableEntry> out_tables;
787 
788   size_t head_table_offset = 0;
789   for (const auto &it : table_map) {
790     uint32_t input_offset = it.second.offset;
791     const auto &ot = header->table_entries.find(input_offset);
792     if (ot != header->table_entries.end()) {
793       ots::TableEntry out = ot->second;
794       if (out.tag == OTS_TAG('h','e','a','d')) {
795         head_table_offset = out.offset;
796       }
797       out_tables.push_back(out);
798     } else {
799       ots::TableEntry out;
800       out.tag = it.first;
801       out.offset = output->Tell();
802 
803       if (out.tag == OTS_TAG('h','e','a','d')) {
804         head_table_offset = out.offset;
805       }
806 
807       ots::Table *table = font->GetTable(out.tag);
808       if (table) {
809         output->ResetChecksum();
810         if (!table->Serialize(output)) {
811           return OTS_FAILURE_MSG_TAG("Failed to serialize table", out.tag);
812         }
813 
814         const size_t end_offset = output->Tell();
815         if (end_offset <= out.offset) {
816           // paranoid check. |end_offset| is supposed to be greater than the offset,
817           // as long as the Tell() interface is implemented correctly.
818           return OTS_FAILURE_MSG_TAG("Table is empty or have -ve size", out.tag);
819         }
820         out.length = end_offset - out.offset;
821 
822         // align tables to four bytes
823         if (!output->Pad((4 - (end_offset & 3)) % 4)) {
824           return OTS_FAILURE_MSG_TAG("Failed to pad table to 4 bytes", out.tag);
825         }
826         out.chksum = output->chksum();
827         out_tables.push_back(out);
828         header->table_entries[input_offset] = out;
829       }
830     }
831   }
832 
833   const size_t end_of_file = output->Tell();
834 
835   // Need to sort the output tables for inclusion in the file
836   std::sort(out_tables.begin(), out_tables.end());
837   if (!output->Seek(table_record_offset)) {
838     return OTS_FAILURE_MSG_HDR("error writing output");
839   }
840 
841   output->ResetChecksum();
842   uint32_t tables_chksum = 0;
843   for (unsigned i = 0; i < out_tables.size(); ++i) {
844     if (!output->WriteU32(out_tables[i].tag) ||
845         !output->WriteU32(out_tables[i].chksum) ||
846         !output->WriteU32(out_tables[i].offset) ||
847         !output->WriteU32(out_tables[i].length)) {
848       return OTS_FAILURE_MSG_HDR("error writing output");
849     }
850     tables_chksum += out_tables[i].chksum;
851   }
852   const uint32_t table_record_chksum = output->chksum();
853 
854   // http://www.microsoft.com/typography/otspec/otff.htm
855   const uint32_t file_chksum
856       = offset_table_chksum + tables_chksum + table_record_chksum;
857   const uint32_t chksum_magic = static_cast<uint32_t>(0xb1b0afba) - file_chksum;
858 
859   // seek into the 'head' table and write in the checksum magic value
860   if (!head_table_offset) {
861     return OTS_FAILURE_MSG_HDR("internal error!");
862   }
863   if (!output->Seek(head_table_offset + 8)) {
864     return OTS_FAILURE_MSG_HDR("error writing output");
865   }
866   if (!output->WriteU32(chksum_magic)) {
867     return OTS_FAILURE_MSG_HDR("error writing output");
868   }
869 
870   if (!output->Seek(end_of_file)) {
871     return OTS_FAILURE_MSG_HDR("error writing output");
872   }
873 
874   return true;
875 }
876 
877 }  // namespace
878 
879 namespace ots {
880 
~FontFile()881 FontFile::~FontFile() {
882   for (const auto& it : tables) {
883     delete it.second;
884   }
885   tables.clear();
886 }
887 
ParseTable(const TableEntry & table_entry,const uint8_t * data,Arena & arena)888 bool Font::ParseTable(const TableEntry& table_entry, const uint8_t* data,
889                       Arena &arena) {
890   uint32_t tag = table_entry.tag;
891   TableAction action = GetTableAction(file, tag);
892   if (action == TABLE_ACTION_DROP) {
893     return true;
894   }
895 
896   const auto &it = file->tables.find(table_entry);
897   if (it != file->tables.end()) {
898     m_tables[tag] = it->second;
899     return true;
900   }
901 
902   Table *table = NULL;
903   bool ret = false;
904 
905   if (action == TABLE_ACTION_PASSTHRU) {
906     table = new TablePassthru(this, tag);
907   } else {
908     switch (tag) {
909       case OTS_TAG_AVAR: table = new OpenTypeAVAR(this, tag); break;
910       case OTS_TAG_CFF:  table = new OpenTypeCFF(this,  tag); break;
911       case OTS_TAG_CFF2: table = new OpenTypeCFF2(this, tag); break;
912       case OTS_TAG_CMAP: table = new OpenTypeCMAP(this, tag); break;
913       case OTS_TAG_CVAR: table = new OpenTypeCVAR(this, tag); break;
914       case OTS_TAG_CVT:  table = new OpenTypeCVT(this,  tag); break;
915       case OTS_TAG_FPGM: table = new OpenTypeFPGM(this, tag); break;
916       case OTS_TAG_FVAR: table = new OpenTypeFVAR(this, tag); break;
917       case OTS_TAG_GASP: table = new OpenTypeGASP(this, tag); break;
918       case OTS_TAG_GDEF: table = new OpenTypeGDEF(this, tag); break;
919       case OTS_TAG_GLYF: table = new OpenTypeGLYF(this, tag); break;
920       case OTS_TAG_GPOS: table = new OpenTypeGPOS(this, tag); break;
921       case OTS_TAG_GSUB: table = new OpenTypeGSUB(this, tag); break;
922       case OTS_TAG_GVAR: table = new OpenTypeGVAR(this, tag); break;
923       case OTS_TAG_HDMX: table = new OpenTypeHDMX(this, tag); break;
924       case OTS_TAG_HEAD: table = new OpenTypeHEAD(this, tag); break;
925       case OTS_TAG_HHEA: table = new OpenTypeHHEA(this, tag); break;
926       case OTS_TAG_HMTX: table = new OpenTypeHMTX(this, tag); break;
927       case OTS_TAG_HVAR: table = new OpenTypeHVAR(this, tag); break;
928       case OTS_TAG_KERN: table = new OpenTypeKERN(this, tag); break;
929       case OTS_TAG_LOCA: table = new OpenTypeLOCA(this, tag); break;
930       case OTS_TAG_LTSH: table = new OpenTypeLTSH(this, tag); break;
931       case OTS_TAG_MATH: table = new OpenTypeMATH(this, tag); break;
932       case OTS_TAG_MAXP: table = new OpenTypeMAXP(this, tag); break;
933       case OTS_TAG_MVAR: table = new OpenTypeMVAR(this, tag); break;
934       case OTS_TAG_NAME: table = new OpenTypeNAME(this, tag); break;
935       case OTS_TAG_OS2:  table = new OpenTypeOS2(this,  tag); break;
936       case OTS_TAG_POST: table = new OpenTypePOST(this, tag); break;
937       case OTS_TAG_PREP: table = new OpenTypePREP(this, tag); break;
938       case OTS_TAG_STAT: table = new OpenTypeSTAT(this, tag); break;
939       case OTS_TAG_VDMX: table = new OpenTypeVDMX(this, tag); break;
940       case OTS_TAG_VHEA: table = new OpenTypeVHEA(this, tag); break;
941       case OTS_TAG_VMTX: table = new OpenTypeVMTX(this, tag); break;
942       case OTS_TAG_VORG: table = new OpenTypeVORG(this, tag); break;
943       case OTS_TAG_VVAR: table = new OpenTypeVVAR(this, tag); break;
944       // Graphite tables
945 #ifdef OTS_GRAPHITE
946       case OTS_TAG_FEAT: table = new OpenTypeFEAT(this, tag); break;
947       case OTS_TAG_GLAT: table = new OpenTypeGLAT(this, tag); break;
948       case OTS_TAG_GLOC: table = new OpenTypeGLOC(this, tag); break;
949       case OTS_TAG_SILE: table = new OpenTypeSILE(this, tag); break;
950       case OTS_TAG_SILF: table = new OpenTypeSILF(this, tag); break;
951       case OTS_TAG_SILL: table = new OpenTypeSILL(this, tag); break;
952 #endif
953       default: break;
954     }
955   }
956 
957   if (table) {
958     const uint8_t* table_data;
959     size_t table_length;
960 
961     ret = GetTableData(data, table_entry, arena, &table_length, &table_data);
962     if (ret) {
963       // FIXME: Parsing some tables will fail if the table is not added to
964       // m_tables first.
965       m_tables[tag] = table;
966       ret = table->Parse(table_data, table_length);
967       if (ret)
968         file->tables[table_entry] = table;
969       else
970         m_tables.erase(tag);
971     }
972   }
973 
974   if (!ret)
975     delete table;
976 
977   return ret;
978 }
979 
GetTable(uint32_t tag) const980 Table* Font::GetTable(uint32_t tag) const {
981   const auto &it = m_tables.find(tag);
982   if (it != m_tables.end() && it->second && it->second->ShouldSerialize())
983     return it->second;
984   return NULL;
985 }
986 
GetTypedTable(uint32_t tag) const987 Table* Font::GetTypedTable(uint32_t tag) const {
988   Table* t = GetTable(tag);
989   if (t && t->Type() == tag)
990     return t;
991   return NULL;
992 }
993 
DropGraphite()994 void Font::DropGraphite() {
995   file->context->Message(0, "Dropping all Graphite tables");
996   for (const std::pair<uint32_t, Table*> entry : m_tables) {
997     if (entry.first == OTS_TAG_FEAT ||
998         entry.first == OTS_TAG_GLAT ||
999         entry.first == OTS_TAG_GLOC ||
1000         entry.first == OTS_TAG_SILE ||
1001         entry.first == OTS_TAG_SILF ||
1002         entry.first == OTS_TAG_SILL) {
1003       entry.second->Drop("Discarding Graphite table");
1004     }
1005   }
1006 }
1007 
DropVariations()1008 void Font::DropVariations() {
1009   file->context->Message(0, "Dropping all Variation tables");
1010   for (const std::pair<uint32_t, Table*> entry : m_tables) {
1011     if (entry.first == OTS_TAG_AVAR ||
1012         entry.first == OTS_TAG_CVAR ||
1013         entry.first == OTS_TAG_FVAR ||
1014         entry.first == OTS_TAG_GVAR ||
1015         entry.first == OTS_TAG_HVAR ||
1016         entry.first == OTS_TAG_MVAR ||
1017         entry.first == OTS_TAG_STAT ||
1018         entry.first == OTS_TAG_VVAR) {
1019       entry.second->Drop("Discarding Variations table");
1020     }
1021   }
1022 }
1023 
ShouldSerialize()1024 bool Table::ShouldSerialize() {
1025   return m_shouldSerialize;
1026 }
1027 
Message(int level,const char * format,va_list va)1028 void Table::Message(int level, const char *format, va_list va) {
1029   char msg[206] = { OTS_UNTAG(m_tag), ':', ' ' };
1030   std::vsnprintf(msg + 6, 200, format, va);
1031   m_font->file->context->Message(level, msg);
1032 }
1033 
Error(const char * format,...)1034 bool Table::Error(const char *format, ...) {
1035   va_list va;
1036   va_start(va, format);
1037   Message(0, format, va);
1038   va_end(va);
1039 
1040   return false;
1041 }
1042 
Warning(const char * format,...)1043 bool Table::Warning(const char *format, ...) {
1044   va_list va;
1045   va_start(va, format);
1046   Message(1, format, va);
1047   va_end(va);
1048 
1049   return true;
1050 }
1051 
Drop(const char * format,...)1052 bool Table::Drop(const char *format, ...) {
1053   m_shouldSerialize = false;
1054 
1055   va_list va;
1056   va_start(va, format);
1057   Message(0, format, va);
1058   m_font->file->context->Message(0, "Table discarded");
1059   va_end(va);
1060 
1061   return true;
1062 }
1063 
DropGraphite(const char * format,...)1064 bool Table::DropGraphite(const char *format, ...) {
1065   va_list va;
1066   va_start(va, format);
1067   Message(0, format, va);
1068   va_end(va);
1069 
1070   m_font->DropGraphite();
1071   return true;
1072 }
1073 
DropVariations(const char * format,...)1074 bool Table::DropVariations(const char *format, ...) {
1075   va_list va;
1076   va_start(va, format);
1077   Message(0, format, va);
1078   va_end(va);
1079 
1080   m_font->DropVariations();
1081   return true;
1082 }
1083 
Parse(const uint8_t * data,size_t length)1084 bool TablePassthru::Parse(const uint8_t *data, size_t length) {
1085   m_data = data;
1086   m_length = length;
1087   return true;
1088 }
1089 
Serialize(OTSStream * out)1090 bool TablePassthru::Serialize(OTSStream *out) {
1091     if (!out->Write(m_data, m_length)) {
1092     return Error("Failed to write table");
1093   }
1094 
1095   return true;
1096 }
1097 
Process(OTSStream * output,const uint8_t * data,size_t length,uint32_t index)1098 bool OTSContext::Process(OTSStream *output,
1099                          const uint8_t *data,
1100                          size_t length,
1101                          uint32_t index) {
1102   FontFile header;
1103   Font font(&header);
1104   header.context = this;
1105 
1106   if (length < 4) {
1107     return OTS_FAILURE_MSG_(&header, "file less than 4 bytes");
1108   }
1109 
1110   bool result;
1111   if (data[0] == 'w' && data[1] == 'O' && data[2] == 'F' && data[3] == 'F') {
1112     result = ProcessWOFF(&header, &font, output, data, length);
1113   } else if (data[0] == 'w' && data[1] == 'O' && data[2] == 'F' && data[3] == '2') {
1114     result = ProcessWOFF2(&header, output, data, length, index);
1115   } else if (data[0] == 't' && data[1] == 't' && data[2] == 'c' && data[3] == 'f') {
1116     result = ProcessTTC(&header, output, data, length, index);
1117   } else {
1118     result = ProcessTTF(&header, &font, output, data, length);
1119   }
1120 
1121   return result;
1122 }
1123 
1124 }  // namespace ots
1125