*** empty log message ***
[m17n/libotf.git] / src / otfopen.c
1 /* otfopen.c -- OpenType font reader.
2
3 Copyright (C) 2003, 2004, 2005, 2006
4   National Institute of Advanced Industrial Science and Technology (AIST)
5   Registration Number H15PRO167
6
7 This file is part of libotf.
8
9 Libotf is free software; you can redistribute it and/or modify it
10 under the terms of the GNU Lesser General Public License as published
11 by the Free Software Foundation; either version 2.1 of the License, or
12 (at your option) any later version.
13
14 Libotf is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17 License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library, in a file named COPYING; if not,
21 write to the Free Software Foundation, Inc., 59 Temple Place, Suite
22 330, Boston, MA 02111-1307, USA.  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <config.h>
28
29 #include "otf.h"
30 #include "otferror.h"
31
32 #include FT_TRUETYPE_TABLES_H
33
34 /***
35     Table of contents (almost parallel to otf.h):
36
37     (0) Stream handler
38
39     (1) Readers for OTF Layout tables and OTF itself
40     (1-1) Basic types and functions
41     (1-2) "head" table
42     (1-3) "name" table
43     (1-4) "cmap" table
44     (1-5) Structures common to GDEF, GSUB, and GPOS
45     (1-6) "GDEF" table
46     (1-7) Structures for ScriptList, FeatureList, and LookupList
47     (1-8) Structures common to GSUB and GPOS
48     (1-9) "GSUB" table
49     (1-10) "GPOS" table
50     (1-11) Structure for OTF
51
52     (2) API for reading OTF
53     (2-1) OTF_open()
54     (2-2) OTF_close()
55     (2-3) OTF_get_table()
56     (2-4) OTF_check_table()
57
58     (5) API miscellaneous
59 */
60 \f
61 /* (0) Stream handler
62
63    Example of typical usage of OTF_Stream.
64
65     {
66       OTF_Stream *stream;
67       OTF_StreamState state;
68       int offset, nbytes;
69
70       OPEN_STREAM (_FILE_NAME_, stream);
71       if (! stream)
72         _ERROR_;
73       SETUP_STREAM (stream, fp, 0, 256, _NAME_);
74       offset = READ_OFFSET (stream);
75       nbytes = READ_ULONG (stream);
76       SETUP_STREAM (stream, fp, offset, nbytes, _NAME2_);
77       ...;
78       CLOSE_STREAM (stream);
79     }
80
81 */
82
83 typedef struct
84 {
85   const char *name;
86   long pos;
87   long bufsize;
88   long allocated;
89   unsigned char *buf;
90 } OTF_Stream;
91
92 typedef long OTF_StreamState;
93
94 OTF_Stream *
95 make_stream (const char *name)
96 {
97   OTF_Stream *stream;
98   char *errfmt = "stream creation%s";
99   void *errret = NULL;
100
101   stream = calloc (1, sizeof (OTF_Stream));
102   if (! stream)
103     OTF_ERROR (OTF_ERROR_MEMORY, "");
104   stream->name = name;
105   return stream;
106 }
107
108 int
109 setup_stream (OTF_Stream *stream, FILE *fp, long offset, int nbytes)
110 {
111   char *errfmt = "stream setup for %s";
112   int errret = -1;
113
114   stream->pos = 0;
115   if (stream->allocated < nbytes)
116     {
117       unsigned char *buf = malloc (nbytes);
118
119       if (! buf)
120         OTF_ERROR (OTF_ERROR_MEMORY, stream->name);
121       if (stream->buf)
122         free (stream->buf);
123       stream->buf = buf;
124       stream->allocated = nbytes;
125     }
126   stream->bufsize = nbytes;
127   if (fseek (fp, offset, SEEK_SET) < 0)
128     OTF_ERROR (OTF_ERROR_FILE, stream->name);
129   if (fread (stream->buf, 1, nbytes, fp) != nbytes)
130     OTF_ERROR (OTF_ERROR_FILE, stream->name);
131   return 0;
132 }
133
134 OTF_Stream *
135 make_stream_from_ft_face (FT_Face face, const char *name)
136 {
137   char *errfmt = "FT_Face stream creation for %s";
138   void *errret = NULL;
139   FT_ULong nbytes = 0;
140   unsigned char *buf;
141   OTF_Stream *stream;
142   FT_ULong tag = FT_MAKE_TAG (name[0], name[1], name[2], name[3]);
143
144   if (FT_Load_Sfnt_Table (face, tag, 0, NULL, &nbytes))
145     return NULL;
146   buf = malloc (nbytes);
147   if (! buf)
148     OTF_ERROR (OTF_ERROR_MEMORY, name);
149   if (FT_Load_Sfnt_Table (face, tag, 0, buf, &nbytes))
150     {
151       free (buf);
152       OTF_ERROR (OTF_ERROR_FT_FACE, name);
153     }
154   stream = make_stream (name);
155   if (! stream)
156     return NULL;
157   stream->pos = 0;
158   stream->buf = buf;
159   stream->allocated = nbytes;
160   stream->bufsize = nbytes;
161   return stream;
162 }
163
164 void
165 free_stream (OTF_Stream *stream)
166 {
167   free (stream->buf);
168   free (stream);
169 }
170
171 #define SAVE_STREAM(stream, state) ((state) = (stream)->pos)
172 #define RESTORE_STREAM(stream, state) ((stream)->pos = (state))
173 #define SEEK_STREAM(stream, offset) ((stream)->pos = (offset))
174
175 #define STREAM_CHECK_SIZE(stream, size)                 \
176   if ((stream)->pos + (size) > (stream)->bufsize)       \
177     {                                                   \
178       char *errfmt = "buffer overrun in %s";            \
179                                                         \
180       OTF_ERROR (OTF_ERROR_TABLE, (stream)->name);      \
181       return errret;                                    \
182     }                                                   \
183   else
184
185
186 #define READ_USHORT(stream, var)                        \
187   do {                                                  \
188     STREAM_CHECK_SIZE ((stream), 2);                    \
189     (var) = (((stream)->buf[(stream)->pos] << 8)        \
190              | (stream)->buf[(stream)->pos + 1]);       \
191     (stream)->pos += 2;                                 \
192   } while (0)
193
194 #define READ_SHORT(stream, var)                                 \
195   do {                                                          \
196     STREAM_CHECK_SIZE ((stream), 2);                            \
197     (var) = (short) (((stream)->buf[(stream)->pos] << 8)        \
198                      | (stream)->buf[(stream)->pos + 1]);       \
199     (stream)->pos += 2;                                         \
200   } while (0)
201
202 #define READ_ULONG(stream, var)                         \
203   do {                                                  \
204     STREAM_CHECK_SIZE ((stream), 4);                    \
205     (var) = (((stream)->buf[(stream)->pos] << 24)       \
206              | ((stream)->buf[(stream)->pos + 1] << 16) \
207              | ((stream)->buf[(stream)->pos + 2] << 8)  \
208              | (stream)->buf[(stream)->pos + 3]);       \
209     (stream)->pos += 4;                                 \
210   } while (0)
211
212 #define READ_LONG(stream, var)                                  \
213   do {                                                          \
214     STREAM_CHECK_SIZE ((stream), 4);                            \
215     (var) = (int) (((stream)->buf[(stream)->pos] << 24)         \
216                    | ((stream)->buf[(stream)->pos + 1] << 16)   \
217                    | ((stream)->buf[(stream)->pos + 2] << 8)    \
218                    | (stream)->buf[(stream)->pos + 3]);         \
219     (stream)->pos += 4;                                         \
220   } while (0)
221
222
223 #define READ_FIXED(stream, fixed)               \
224   do {                                          \
225     READ_USHORT ((stream), (fixed).high);       \
226     READ_USHORT ((stream), (fixed).low);        \
227   } while (0)
228
229
230 #define READ_BYTES(stream, p, nbytes)                           \
231   do {                                                          \
232     STREAM_CHECK_SIZE ((stream), (nbytes));                     \
233     memcpy ((p), (stream)->buf + (stream)->pos, (nbytes));      \
234     (stream)->pos += (nbytes);                                  \
235   } while (0)
236
237
238 #define READ_TAG READ_ULONG
239 #define READ_OFFSET READ_USHORT
240 #define READ_UINT16 READ_USHORT
241 #define READ_INT16 READ_SHORT
242 #define READ_GLYPHID READ_USHORT
243
244 \f
245 /*** (1) Structures for OTF Layout tables and OTF itself */
246
247 /*** (1-1) Basic types and functions */
248
249 enum OTF_TableType
250   {
251     OTF_TABLE_TYPE_HEAD,
252     OTF_TABLE_TYPE_NAME,
253     OTF_TABLE_TYPE_CMAP,
254     OTF_TABLE_TYPE_GDEF,
255     OTF_TABLE_TYPE_GSUB,
256     OTF_TABLE_TYPE_GPOS,
257     OTF_TABLE_TYPE_MAX
258   };
259
260 #define OTF_MEMORY_RECORD_SIZE 1024
261
262 struct OTF_MemoryRecord
263 {
264   int used;
265   void *memory[OTF_MEMORY_RECORD_SIZE];
266   struct OTF_MemoryRecord *next;
267 };
268
269 typedef struct OTF_MemoryRecord OTF_MemoryRecord;
270
271 enum OTF_ReaderFlag
272   {
273     OTF_READ_FULL,
274     OTF_READ_SCRIPTS,
275     OTF_READ_FEATURES,
276     OTF_READ_MAX
277   };
278
279 struct _OTF_TableInfo;
280 typedef struct _OTF_TableInfo OTF_TableInfo;
281
282 struct _OTF_TableInfo
283 {
284   /* Points to one of OTF->head, OTF->name, etc.  */
285   void **address;
286   /* Function to read one of OTF tables.  */
287   void *(*reader) (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag);
288   /* Stream given to <reader>.  */
289   OTF_Stream *stream;
290 };
291
292 struct OTF_InternalData
293 {
294   /* Information about each OTF table.  */
295   OTF_TableInfo table_info[OTF_TABLE_TYPE_MAX];
296
297   /* Stream used to read the header part of OTF.  */
298   OTF_Stream *header_stream;
299
300   /* Records of allocated memories.  */
301   OTF_MemoryRecord *memory_record;
302 };
303
304
305 static OTF_MemoryRecord *
306 allocate_memory_record (OTF *otf)
307 {
308   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
309   OTF_MemoryRecord *memrec = malloc (sizeof (OTF_MemoryRecord));
310
311   if (! memrec)
312     return NULL;
313   memrec->used = 0;
314   memrec->next = internal_data->memory_record;
315   internal_data->memory_record = memrec;
316   return memrec;
317 }
318
319 /* Memory allocation macros.  */
320
321 #define OTF_MALLOC(p, size, arg)                                        \
322   do {                                                                  \
323     if (size == 0)                                                      \
324       (p) = NULL;                                                       \
325     else                                                                \
326       {                                                                 \
327         OTF_MemoryRecord *memrec                                        \
328           = ((OTF_InternalData *) otf->internal_data)->memory_record;   \
329         (p) = malloc (sizeof (*(p)) * (size));                          \
330         if (! (p)                                                       \
331             || (memrec->used >= OTF_MEMORY_RECORD_SIZE                  \
332                 && ! (memrec = allocate_memory_record (otf))))          \
333           OTF_ERROR (OTF_ERROR_MEMORY, (arg));                          \
334         memrec->memory[memrec->used++] = (p);                           \
335       }                                                                 \
336   } while (0)
337
338
339 #define OTF_CALLOC(p, size, arg)                                        \
340   do {                                                                  \
341     if (size == 0)                                                      \
342       (p) = NULL;                                                       \
343     else                                                                \
344       {                                                                 \
345         OTF_MemoryRecord *memrec                                        \
346           = ((OTF_InternalData *) otf->internal_data)->memory_record;   \
347         (p) = calloc ((size), sizeof (*(p)));                           \
348         if (! (p)                                                       \
349             || (memrec->used >= OTF_MEMORY_RECORD_SIZE                  \
350                 && ! (memrec = allocate_memory_record (otf))))          \
351           OTF_ERROR (OTF_ERROR_MEMORY, (arg));                          \
352         memrec->memory[memrec->used++] = (p);                           \
353       }                                                                 \
354   } while (0)
355
356 \f
357 /*** (1-2) "head" table */
358
359 static void *
360 read_head_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
361 {
362   OTF_Stream *stream = table->stream;
363   char *errfmt = "head%s";
364   void *errret = NULL;
365   OTF_head *head;
366
367   OTF_CALLOC (head, 1, "");
368   READ_FIXED (stream, head->TableVersionNumber);
369   READ_FIXED (stream, head->fontRevision);
370   READ_ULONG (stream, head->checkSumAdjustment);
371   READ_ULONG (stream, head->magicNumber);
372   READ_USHORT (stream, head->flags);
373   READ_USHORT (stream, head->unitsPerEm);
374
375   *table->address = head;
376   return head;
377 }
378
379 \f
380 /*** (1-3) "name" table */
381
382 static int
383 read_name (OTF *otf, OTF_Stream *stream, OTF_NameRecord *rec)
384 {
385   char *errfmt = "nameID (%d)";
386   int errret = -1;
387   OTF_StreamState state;
388   int ucs = 0;
389   int ascii = 0;
390   int i;
391
392   if (rec->platformID == 0)
393     ucs = (rec->encodingID <= 3) ? 2 : 4;
394   else if (rec->platformID == 1 && rec->encodingID == 0)
395     ascii = 1;
396   else if (rec->platformID == 3)
397     ucs = (rec->encodingID == 1  ? 2
398            : rec->encodingID == 10 ? 4
399            : 0);
400
401   OTF_MALLOC (rec->name, rec->length + 1, (void *) rec->nameID);
402   SAVE_STREAM (stream, state);
403   SEEK_STREAM (stream, stream->pos + rec->offset);
404   READ_BYTES (stream, rec->name, rec->length);
405   RESTORE_STREAM (stream, state);
406   rec->name[rec->length] = 0;
407
408   if (ascii)
409     {
410       rec->ascii = 1;
411     }
412   else if (ucs == 2)
413     {
414       rec->ascii = 1;
415       for (i = 0; i < rec->length / 2; i++)
416         {
417           if (rec->name[i * 2] > 0
418               || rec->name[i * 2 + 1] >= 128)
419             {
420               rec->ascii = 0;
421               break;
422             }
423         }
424       if (rec->ascii)
425         for (i = 0; i < rec->length / 2; i++)
426           rec->name[i] = rec->name[i * 2 + 1];
427       rec->name[i] = 0;
428     }
429   else if (ucs == 4)
430     {
431       rec->ascii = 1;
432       for (i = 0; i < rec->length / 4; i++)
433         {
434           if (rec->name[i * 4] > 0
435               || rec->name[i * 4 + 1] > 0
436               || rec->name[i * 4 + 2] > 0
437               || rec->name[i * 2 + 3] >= 128)
438             {
439               rec->ascii = 0;
440               break;
441             }
442         }
443       if (rec->ascii)
444         for (i = 0; i < rec->length / 4; i++)
445           rec->name[i] = rec->name[i * 4 + 3];
446       rec->name[i] = 0;
447     }
448
449   return 0;
450 }
451
452 static void *
453 read_name_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
454 {
455   OTF_Stream *stream = table->stream;
456   char *errfmt = "name%s";
457   void *errret = NULL;
458   OTF_name *name;
459   int i;
460
461   OTF_CALLOC (name, 1, "");
462   READ_USHORT (stream, name->format);
463   READ_USHORT (stream, name->count);
464   READ_USHORT (stream, name->stringOffset);
465   OTF_MALLOC (name->nameRecord, name->count, "");
466   for (i = 0; i < name->count; i++)
467     {
468       OTF_NameRecord *rec = name->nameRecord + i;
469
470       READ_USHORT (stream, rec->platformID);
471       READ_USHORT (stream, rec->encodingID);
472       READ_USHORT (stream, rec->languageID);
473       READ_USHORT (stream, rec->nameID);
474       READ_USHORT (stream, rec->length);
475       READ_USHORT (stream, rec->offset);
476     }
477   for (i = 0; i < name->count; i++)
478     {
479       OTF_NameRecord *rec = name->nameRecord + i;
480       int nameID = rec->nameID;
481
482       read_name (otf, stream, rec);
483
484       if (nameID >= OTF_max_nameID)
485         continue;
486       if (! name->name[nameID]
487           && rec->ascii)
488         name->name[nameID] = (char *) rec->name;
489     }
490
491   *table->address = name;
492   return name;
493 }
494
495 \f
496 /*** (1-4) "cmap" table */
497
498 static void *
499 read_cmap_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
500 {
501   OTF_Stream *stream = table->stream;
502   char *errfmt = "cmap%s";
503   void *errret = NULL;
504   OTF_cmap *cmap;
505   int unicode_bmp_index = -1, unicode_full_index = -1;
506   int i;
507
508   OTF_CALLOC (cmap, 1, "");
509   READ_USHORT (stream, cmap->version);
510   READ_USHORT (stream, cmap->numTables);
511   OTF_MALLOC (cmap->EncodingRecord, cmap->numTables, "");
512   for (i = 0; i < cmap->numTables; i++)
513     {
514       unsigned platformID, encodingID;
515
516       READ_USHORT (stream, platformID);
517       cmap->EncodingRecord[i].platformID = platformID;
518       READ_USHORT (stream, encodingID);
519       cmap->EncodingRecord[i].encodingID = encodingID;
520       READ_ULONG (stream, cmap->EncodingRecord[i].offset);
521       if (platformID == 0)
522         {
523           if (encodingID <= 3)
524             unicode_bmp_index = i;
525           else
526             unicode_full_index = i;
527         }
528       else if (platformID == 3)
529         {
530           if (encodingID == 1)
531             unicode_bmp_index = i;
532           else if (encodingID == 10)
533             unicode_full_index = i;
534         }
535     }
536   for (i = 0; i < cmap->numTables; i++)
537     {
538       unsigned format;
539
540       SEEK_STREAM (stream, cmap->EncodingRecord[i].offset);
541       READ_USHORT (stream, format);
542       cmap->EncodingRecord[i].subtable.format = format;
543       READ_USHORT (stream, cmap->EncodingRecord[i].subtable.length);
544       if (format == 8 || format == 10 || format == 12)
545         {
546           READ_ULONG (stream, cmap->EncodingRecord[i].subtable.length);
547           READ_ULONG (stream, cmap->EncodingRecord[i].subtable.language);
548         }
549       else
550         {
551           READ_USHORT (stream, cmap->EncodingRecord[i].subtable.language);
552         }
553       switch (format)
554         {
555         case 0:
556           {
557             OTF_MALLOC (cmap->EncodingRecord[i].subtable.f.f0, 1,
558                         " (EncodingRecord)");
559             READ_BYTES (stream,
560                         cmap->EncodingRecord[i].subtable.f.f0->glyphIdArray,
561                         256);
562           }
563           break;
564
565         case 2:
566           {
567             OTF_EncodingSubtable2 *sub2;
568             int j, max_key;
569
570             OTF_MALLOC (sub2, 1, " (EncodingSubtable2)");
571             cmap->EncodingRecord[i].subtable.f.f2 = sub2;
572             for (j = 0, max_key = 0; j < 256; j++)
573               {
574                 READ_USHORT (stream, sub2->subHeaderKeys[j]);
575                 if (max_key < sub2->subHeaderKeys[j])
576                   max_key = sub2->subHeaderKeys[j];
577               }
578             max_key += 8;
579             sub2->subHeaderCount = max_key / 8;
580             OTF_MALLOC (sub2->subHeaders, max_key / 8, " (subHeaders)");
581             for (j = 0; j < sub2->subHeaderCount; j++)
582               {
583                 READ_USHORT (stream, sub2->subHeaders[j].firstCode);
584                 READ_USHORT (stream, sub2->subHeaders[j].entryCount);
585                 READ_SHORT (stream, sub2->subHeaders[j].idDelta);
586                 READ_USHORT (stream, sub2->subHeaders[j].idRangeOffset);
587                 /* Make it offset from sub2->glyphIndexArray.  */
588                 sub2->subHeaders[j].idRangeOffset -= max_key - (j * 8 + 6);
589               }
590             sub2->glyphIndexCount = (cmap->EncodingRecord[i].subtable.length
591                                      - 262 - max_key);
592             OTF_MALLOC (sub2->glyphIndexArray, sub2->glyphIndexCount,
593                         " (glyphIndexArray)");
594             READ_BYTES (stream, sub2->glyphIndexArray, sub2->glyphIndexCount);
595           }
596           break;
597
598         case 4:
599           {
600             OTF_EncodingSubtable4 *sub4;
601             int segCount;
602             int j;
603             unsigned dummy;
604
605             OTF_MALLOC (sub4, 1, " (EncodingSubtable4)");
606             cmap->EncodingRecord[i].subtable.f.f4 = sub4;
607             READ_USHORT (stream, sub4->segCountX2);
608             segCount = sub4->segCountX2 / 2;
609             READ_USHORT (stream, sub4->searchRange);
610             READ_USHORT (stream, sub4->entrySelector);
611             READ_USHORT (stream, sub4->rangeShift);
612             OTF_MALLOC (sub4->segments, segCount, " (segCount)");
613             for (j = 0; j < segCount; j++)
614               READ_USHORT (stream, sub4->segments[j].endCount);
615             READ_USHORT (stream, dummy);
616             for (j = 0; j < segCount; j++)
617               READ_USHORT (stream, sub4->segments[j].startCount);
618             for (j = 0; j < segCount; j++)
619               READ_SHORT (stream, sub4->segments[j].idDelta);
620             for (j = 0; j < segCount; j++)
621               {
622                 unsigned off;
623                 unsigned rest = 2 * (segCount - j);
624                 
625                 READ_USHORT (stream, off);
626                 if (off == 0)
627                   sub4->segments[j].idRangeOffset = 0xFFFF;
628                 else
629                   sub4->segments[j].idRangeOffset = (off - rest) / 2;
630               }
631             j = (cmap->EncodingRecord[i].subtable.length
632                  - (14 + 2 * (segCount * 4 + 1)));
633             sub4->GlyphCount = j / 2;
634             OTF_MALLOC (sub4->glyphIdArray, sub4->GlyphCount, " (GlyphCount)");
635             for (j = 0; j < sub4->GlyphCount; j++)
636               READ_USHORT (stream, sub4->glyphIdArray[j]);
637           }
638           break;
639
640         case 6:
641           {
642             OTF_EncodingSubtable6 *sub6;
643             int j;
644
645             OTF_MALLOC (sub6, 1, " (EncodingSubtable6)");
646             cmap->EncodingRecord[i].subtable.f.f6 = sub6;
647             READ_USHORT (stream, sub6->firstCode);
648             READ_USHORT (stream, sub6->entryCount);
649             OTF_MALLOC (sub6->glyphIdArray, sub6->entryCount, " (GlyphCount)");
650             for (j = 0; j < sub6->entryCount; j++)
651               READ_USHORT (stream, sub6->glyphIdArray[j]);
652           }
653           break;
654
655         case 8:
656           {
657             OTF_EncodingSubtable8 *sub8;
658             int j;
659
660             OTF_MALLOC (sub8, 1, " (EncodingSubtable8)");
661             cmap->EncodingRecord[i].subtable.f.f8 = sub8;
662             for (j = 0; j < 8192; j++)
663               READ_BYTES (stream, sub8->is32, 8192);
664             READ_ULONG (stream, sub8->nGroups);
665             OTF_MALLOC (sub8->Groups, sub8->nGroups, " (Groups)");
666             for (j = 0; j < sub8->nGroups; j++)
667               {
668                 READ_ULONG (stream, sub8->Groups[i].startCharCode);
669                 READ_ULONG (stream, sub8->Groups[i].endCharCode);
670                 READ_ULONG (stream, sub8->Groups[i].startGlyphID);
671               }
672           }
673           break;
674
675         case 10:
676           {
677             OTF_EncodingSubtable10 *sub10;
678             int j;
679
680             OTF_MALLOC (sub10, 1, " (EncodingSubtable10)");
681             cmap->EncodingRecord[i].subtable.f.f10 = sub10;
682             READ_ULONG (stream, sub10->startCharCode);
683             READ_ULONG (stream, sub10->numChars);
684             OTF_MALLOC (sub10->glyphs, sub10->numChars, " (GlyphCount)");
685             for (j = 0; j < sub10->numChars; j++)
686               READ_USHORT (stream, sub10->glyphs[j]);
687           }
688           break;
689
690         case 12:
691           {
692             OTF_EncodingSubtable12 *sub12;
693             int j;
694
695             OTF_MALLOC (sub12, 1, " (EncodingSubtable12)");
696             cmap->EncodingRecord[i].subtable.f.f12 = sub12;
697             READ_ULONG (stream, sub12->nGroups);
698             OTF_MALLOC (sub12->Groups, sub12->nGroups, " (Groups)");
699             for (j = 0; j < sub12->nGroups; j++)
700               {
701                 READ_ULONG (stream, sub12->Groups[j].startCharCode);
702                 READ_ULONG (stream, sub12->Groups[j].endCharCode);
703                 READ_ULONG (stream, sub12->Groups[j].startGlyphID);
704               }
705           }
706           break;
707
708         default:
709           OTF_ERROR (OTF_ERROR_TABLE, " (invalid Subtable format)");
710         }
711     }
712
713   if (unicode_bmp_index >= 0)
714     {
715       OTF_EncodingRecord *rec = cmap->EncodingRecord + unicode_bmp_index;
716       OTF_GlyphID glyph_id, max_glyph_id = 0;
717
718       OTF_CALLOC (cmap->unicode_table, 0x10000, "");
719       switch (rec->subtable.format)
720         {
721         case 4:
722           {
723             OTF_EncodingSubtable4 *sub4 = rec->subtable.f.f4;
724             int segCount = sub4->segCountX2 / 2;
725
726             for (i = 0; i < segCount; i++)
727               {
728                 OTF_cmapSegument *seg = sub4->segments + i;
729                 int c;
730
731                 if (seg->idRangeOffset == 0xFFFF)
732                   for (c = seg->startCount; c <= seg->endCount; c++)
733                     {
734                       glyph_id = c + seg->idDelta;
735                       cmap->unicode_table[c] = glyph_id;
736                       if (glyph_id > max_glyph_id)
737                         max_glyph_id = glyph_id;
738                     }
739                 else
740                   for (c = seg->startCount; c <= seg->endCount && c != 0xFFFF;
741                        c++)
742                     {
743                       glyph_id = sub4->glyphIdArray[seg->idRangeOffset
744                                                     + (c - seg->startCount)];
745                       cmap->unicode_table[c] = glyph_id;
746                       if (glyph_id > max_glyph_id)
747                         max_glyph_id = glyph_id;
748                     }
749               }
750           }
751         }
752
753       OTF_CALLOC (cmap->decode_table, max_glyph_id + 1, "");
754       for (i = 0; i < 0x10000; i++)
755         if (cmap->unicode_table[i])
756           cmap->decode_table[cmap->unicode_table[i]] = i;
757       cmap->max_glyph_id = max_glyph_id;
758     }
759
760   *table->address = cmap;
761   return cmap;
762 }
763
764 \f
765 /*** (1-5) Structures common to GDEF, GSUB, and GPOS */
766
767 /* Read Glyph-IDs from STREAM.  Allocate memory for IDS, and store the
768    Glyph-IDs there.  If COUNT is negative, read the number of
769    Glyphs-IDs at first.  MINUS if nozero is how few the actual
770    Glyph-IDs are in STREAM than COUNT.  */
771
772 static int
773 read_glyph_ids (OTF *otf, OTF_Stream *stream, OTF_GlyphID **ids,
774                 int minus, int count)
775 {
776   char *errfmt = "GlyphID List%s";
777   int errret = -1;
778   int i;
779
780   if (count < 0)
781     READ_UINT16 (stream, count);
782   if (! count)
783     return 0;
784   OTF_MALLOC (*ids, count, "");
785   for (i = 0; i < count + minus; i++)
786     READ_GLYPHID (stream, (*ids)[i]);
787   return count;
788 }
789
790 static unsigned
791 read_range_records (OTF *otf, OTF_Stream *stream, OTF_RangeRecord **record)
792 {
793   char *errfmt = "RangeRecord%s";
794   unsigned errret = 0;
795   unsigned count;
796   int i;
797
798   READ_UINT16 (stream, count);
799   if (! count)
800     return 0;
801   OTF_MALLOC (*record, count, "");
802   for (i = 0; i < count; i++)
803     {
804       READ_GLYPHID (stream, (*record)[i].Start);
805       READ_GLYPHID (stream, (*record)[i].End);
806       READ_UINT16 (stream, (*record)[i].StartCoverageIndex);
807     }
808   return count;
809 }
810
811
812 static int
813 read_coverage (OTF *otf, OTF_Stream *stream, long offset,
814                OTF_Coverage *coverage)
815 {
816   char *errfmt = "Coverage%s";
817   int errret = -1;
818   OTF_StreamState state;
819   int count;
820
821   READ_OFFSET (stream, coverage->offset);
822   SAVE_STREAM (stream, state);
823   SEEK_STREAM (stream, offset + coverage->offset);
824   READ_UINT16 (stream, coverage->CoverageFormat);
825   if (coverage->CoverageFormat == 1)
826     count = read_glyph_ids (otf, stream, &coverage->table.GlyphArray, 0, -1);
827   else if (coverage->CoverageFormat == 2)
828     count = read_range_records (otf, stream, &coverage->table.RangeRecord);
829   else
830     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid Format)");
831   if (count < 0)
832     return -1;
833   coverage->Count = (unsigned) count;
834   RESTORE_STREAM (stream, state);
835   return 0;
836 }
837
838 /* Read list of Coverages from STREAM.  Allocate memory for COVERAGE,
839    and store the Coverages there.  If COUNT is negative, read the
840    number of Coverages at first.  */
841
842 static int
843 read_coverage_list (OTF *otf, OTF_Stream *stream, long offset,
844                     OTF_Coverage **coverage, int count)
845 {
846   char *errfmt = "Coverage List%s";
847   int errret = -1;
848   int i;
849
850   if (count < 0)
851     READ_UINT16 (stream, count);
852   if (! count)
853     return 0;
854   OTF_MALLOC (*coverage, count, "");
855   for (i = 0; i < count; i++)
856     if (read_coverage (otf, stream, offset, (*coverage) + i) < 0)
857       return -1;
858   return count;
859 }
860
861
862 static int
863 read_class_def_without_offset (OTF *otf, OTF_Stream *stream,
864                                OTF_ClassDef *class)
865 {
866   char *errfmt = "ClassDef%s";
867   int errret = -1;
868
869   SEEK_STREAM (stream, class->offset);
870   READ_UINT16 (stream, class->ClassFormat);
871   if (class->ClassFormat == 1)
872     {
873       READ_GLYPHID (stream, class->f.f1.StartGlyph);
874       class->f.f1.GlyphCount
875         = (read_glyph_ids
876            (otf, stream, (OTF_GlyphID **) &class->f.f1.ClassValueArray, 0, -1));
877       if (! class->f.f1.GlyphCount)
878         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
879     }
880   else if (class->ClassFormat == 2)
881     {
882       class->f.f2.ClassRangeCount
883         = (read_range_records
884            (otf, stream, (OTF_RangeRecord **) &class->f.f2.ClassRangeRecord));
885       if (! class->f.f2.ClassRangeCount)
886         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
887     }
888   else
889     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
890   return 0;
891 }
892
893
894 static int
895 read_class_def (OTF *otf, OTF_Stream *stream, long offset, OTF_ClassDef *class)
896 {
897   char *errfmt = "ClassDef%s";
898   int errret = -1;
899   OTF_StreamState state;
900
901   READ_OFFSET (stream, class->offset);
902   if (! class->offset)
903     return 0;
904   SAVE_STREAM (stream, state);
905   SEEK_STREAM (stream, offset + class->offset);
906   READ_UINT16 (stream, class->ClassFormat);
907   if (class->ClassFormat == 1)
908     {
909       READ_GLYPHID (stream, class->f.f1.StartGlyph);
910       class->f.f1.GlyphCount
911         = read_glyph_ids (otf, stream,
912                           (OTF_GlyphID **) &class->f.f1.ClassValueArray,
913                           0, -1);
914       if (! class->f.f1.GlyphCount)
915         return -1;
916     }
917   else if (class->ClassFormat == 2)
918     {
919       class->f.f2.ClassRangeCount
920         = read_range_records (otf, stream,
921                               (OTF_RangeRecord **)
922                               &class->f.f2.ClassRangeRecord);
923       if (! class->f.f2.ClassRangeCount)
924         return -1;
925     }
926   else
927     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
928
929   RESTORE_STREAM (stream, state);
930   return 0;
931 }
932
933
934 static int
935 read_device_table (OTF *otf, OTF_Stream *stream, long offset,
936                    OTF_DeviceTable *table)
937 {
938   char *errfmt = "Device Table%s";
939   int errret = -1;
940
941   int num, i;
942   unsigned val;
943   struct {
944     int int2 : 2;
945     int int4 : 4;
946     int int8 : 8;
947   } intval;
948
949   SEEK_STREAM (stream, offset + table->offset);
950   READ_UINT16 (stream, table->StartSize);
951   READ_UINT16 (stream, table->EndSize);
952   READ_UINT16 (stream, table->DeltaFormat);
953   num = table->EndSize - table->StartSize + 1;
954   OTF_MALLOC (table->DeltaValue, num, "");
955
956   if (table->DeltaFormat == 1)
957     for (i = 0; i < num; i++)
958       {
959         if ((i % 8) == 0)
960           READ_UINT16 (stream, val);
961         intval.int2 = (val >> (14 - (i % 8) * 2)) & 0x03;
962         table->DeltaValue[i] = intval.int2;
963       }
964   else if (table->DeltaFormat == 2)
965     for (i = 0; i < num; i++)
966       {
967         if ((i % 4) == 0)
968           READ_UINT16 (stream, val);
969         intval.int4 = (val >> (12 - (i % 4) * 4)) & 0x0F;
970         table->DeltaValue[i] = intval.int4;
971       }
972   else if (table->DeltaFormat == 3)
973     for (i = 0; i < num; i++)
974       {
975         if ((i % 2) == 0)
976           {
977             READ_UINT16 (stream, val);
978             intval.int8 = val >> 8;
979             table->DeltaValue[i] = intval.int8;
980           }
981         else
982           {
983             intval.int8 = val >> 8;
984             table->DeltaValue[i] = intval.int8;
985           }
986       }
987   else
988     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
989   return 0;
990 }
991
992 \f
993 /*** (1-6) "GDEF" table */
994
995 static int
996 read_attach_list (OTF *otf, OTF_Stream *stream, long offset,
997                   OTF_AttachList *list)
998 {
999   char *errfmt = "AttachList%s";
1000   int errret = -1;
1001   int i, j;
1002
1003   if (read_coverage (otf, stream, offset, &list->Coverage) < 0)
1004     return -1;
1005   READ_UINT16 (stream, list->GlyphCount);
1006   OTF_MALLOC (list->AttachPoint, list->GlyphCount, "");
1007   for (i = 0; i < list->GlyphCount; i++)
1008     READ_OFFSET (stream, list->AttachPoint[i].offset);
1009   for (i = 0; i < list->GlyphCount; i++)
1010     {
1011       int count;
1012
1013       SEEK_STREAM (stream, offset + list->AttachPoint[i].offset);
1014       READ_UINT16 (stream, count);
1015       list->AttachPoint[i].PointCount = count;
1016       OTF_MALLOC (list->AttachPoint[i].PointIndex, count, " (PointIndex)");
1017       for (j = 0; j < count; j++)
1018         READ_UINT16 (stream, list->AttachPoint[i].PointIndex[j]);
1019     }
1020   return 0;
1021 }
1022
1023 static int
1024 read_caret_value (OTF *otf, OTF_Stream *stream, long offset,
1025                   OTF_CaretValue *caret)
1026 {
1027   char *errfmt = "CaretValue%s";
1028   int errret = -1;
1029
1030   SEEK_STREAM (stream, offset + caret->offset);
1031   READ_UINT16 (stream, caret->CaretValueFormat);
1032   if (caret->CaretValueFormat == 1)
1033     READ_INT16 (stream, caret->f.f1.Coordinate);
1034   else if (caret->CaretValueFormat == 2)
1035     READ_UINT16 (stream, caret->f.f2.CaretValuePoint);
1036   else if (caret->CaretValueFormat == 3)
1037     {
1038       READ_INT16 (stream, caret->f.f3.Coordinate);
1039       if (read_device_table (otf, stream, offset + caret->offset,
1040                              &caret->f.f3.DeviceTable) < 0)
1041         return -1;
1042     }
1043   else
1044     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
1045   return 0;
1046 }
1047
1048 static int
1049 read_lig_caret_list (OTF *otf, OTF_Stream *stream, long offset,
1050                      OTF_LigCaretList *list)
1051 {
1052   char *errfmt = "LigCaretList%s";
1053   int errret = -1;
1054   int i, j;
1055
1056   if (read_coverage (otf, stream, offset, &list->Coverage) < 0)
1057     return -1;
1058   READ_UINT16 (stream, list->LigGlyphCount);
1059   OTF_MALLOC (list->LigGlyph, list->LigGlyphCount, "");
1060   for (i = 0; i < list->LigGlyphCount; i++)
1061     READ_OFFSET (stream, list->LigGlyph[i].offset);
1062   for (i = 0; i < list->LigGlyphCount; i++)
1063     {
1064       int count;
1065
1066       SEEK_STREAM (stream, offset + list->LigGlyph[i].offset);
1067       READ_UINT16 (stream, count);
1068       list->LigGlyph[i].CaretCount = count;
1069       OTF_MALLOC (list->LigGlyph[i].CaretValue, count, " (CaretValue)");
1070       for (j = 0; j < count; j++)
1071         READ_OFFSET (stream, list->LigGlyph[i].CaretValue[j].offset);
1072       for (j = 0; j < count; j++)
1073         if (read_caret_value (otf, stream, offset + list->LigGlyph[i].offset,
1074                               &list->LigGlyph[i].CaretValue[j]) < 0)
1075           return -1;
1076     }
1077   return 0;
1078 }
1079
1080 static int
1081 read_gdef_header (OTF_Stream *stream, OTF_GDEFHeader *header)
1082 {
1083   int errret = -1;
1084
1085   READ_FIXED (stream, header->Version);
1086   READ_OFFSET (stream, header->GlyphClassDef);
1087   READ_OFFSET (stream, header->AttachList);
1088   READ_OFFSET (stream, header->LigCaretList);
1089   READ_OFFSET (stream, header->MarkAttachClassDef);
1090   return 0;
1091 }
1092
1093 static void *
1094 read_gdef_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
1095 {
1096   OTF_Stream *stream = table->stream;
1097   char *errfmt = "GDEF%s";
1098   void *errret = NULL;
1099   OTF_GDEF *gdef;
1100
1101   OTF_CALLOC (gdef, 1, "");
1102   read_gdef_header (stream, (OTF_GDEFHeader *) &gdef->header);
1103   if (gdef->header.GlyphClassDef)
1104     {
1105       gdef->glyph_class_def.offset = gdef->header.GlyphClassDef;
1106       read_class_def_without_offset (otf, stream, &gdef->glyph_class_def);
1107     }
1108   if (gdef->header.AttachList)
1109     read_attach_list (otf, stream, gdef->header.AttachList,
1110                       &gdef->attach_list);
1111   if (gdef->header.LigCaretList)
1112     read_lig_caret_list (otf, stream, gdef->header.LigCaretList,
1113                          &gdef->lig_caret_list);
1114   if (gdef->header.MarkAttachClassDef)
1115     {
1116       gdef->mark_attach_class_def.offset = gdef->header.MarkAttachClassDef;
1117       read_class_def_without_offset (otf, stream, &gdef->mark_attach_class_def);
1118     }
1119
1120   *table->address = gdef;
1121   return gdef;
1122 }
1123
1124 \f
1125 /*** (1-7) Structures for ScriptList, FeatureList, and LookupList */
1126
1127 static int
1128 read_script_list (OTF *otf, OTF_Stream *stream, long offset,
1129                   OTF_ScriptList *list)
1130 {
1131   char *errfmt = "Script List%s";
1132   int errret = -1;
1133   int i, j, k;
1134
1135   SEEK_STREAM (stream, offset);
1136   READ_USHORT (stream, list->ScriptCount);
1137   OTF_CALLOC (list->Script, list->ScriptCount, "");
1138
1139   for (i = 0; i < list->ScriptCount; i++)
1140     {
1141       READ_TAG (stream, list->Script[i].ScriptTag);
1142       READ_OFFSET (stream, list->Script[i].offset);
1143     }
1144   for (i = 0;  i < list->ScriptCount; i++)
1145     {
1146       OTF_Script *script = list->Script + i;
1147       long script_offset = offset + script->offset;
1148
1149       SEEK_STREAM (stream, script_offset);
1150       READ_OFFSET (stream, script->DefaultLangSysOffset);
1151       READ_USHORT (stream, script->LangSysCount);
1152       OTF_MALLOC (script->LangSysRecord, script->LangSysCount, " (LangSys)");
1153       OTF_CALLOC (script->LangSys, script->LangSysCount, " (LangSys)");
1154       for (j = 0; j < script->LangSysCount; j++)
1155         {
1156           READ_TAG (stream, script->LangSysRecord[j].LangSysTag);
1157           READ_OFFSET (stream, script->LangSysRecord[j].LangSys);
1158         }
1159
1160       if (script->DefaultLangSysOffset)
1161         {
1162           OTF_LangSys *langsys = &script->DefaultLangSys;
1163
1164           SEEK_STREAM (stream, script_offset + script->DefaultLangSysOffset);
1165           READ_OFFSET (stream, langsys->LookupOrder);
1166           READ_USHORT (stream, langsys->ReqFeatureIndex);
1167           READ_USHORT (stream, langsys->FeatureCount);
1168           OTF_MALLOC (langsys->FeatureIndex, langsys->FeatureCount,
1169                       " (FeatureIndex)");
1170           for (k = 0; k < langsys->FeatureCount; k++)
1171             READ_USHORT (stream, langsys->FeatureIndex[k]);
1172         }
1173
1174       for (j = 0; j < script->LangSysCount; j++)
1175         {
1176           OTF_LangSys *langsys = script->LangSys + j;
1177
1178           SEEK_STREAM (stream,
1179                        script_offset + script->LangSysRecord[j].LangSys);
1180           READ_OFFSET (stream, langsys->LookupOrder);
1181           READ_USHORT (stream, langsys->ReqFeatureIndex);
1182           READ_USHORT (stream, langsys->FeatureCount);
1183           OTF_MALLOC (langsys->FeatureIndex, langsys->FeatureCount,
1184                       " (FeatureIndex)");
1185           for (k = 0; k < langsys->FeatureCount; k++)
1186             READ_USHORT (stream, langsys->FeatureIndex[k]);
1187         }
1188     }
1189
1190   return 0;
1191 }
1192
1193 static int
1194 read_feature_list (OTF *otf, OTF_Stream *stream, long offset,
1195                    OTF_FeatureList *list)
1196 {
1197   char *errfmt = "Feature List%s";
1198   int errret = -1;
1199   int i, j;
1200
1201   SEEK_STREAM (stream, offset);
1202   READ_UINT16 (stream, list->FeatureCount);
1203   OTF_CALLOC (list->Feature, list->FeatureCount, "");
1204   for (i = 0; i < list->FeatureCount; i++)
1205     {
1206       READ_TAG (stream, list->Feature[i].FeatureTag);
1207       READ_OFFSET (stream, list->Feature[i].offset);
1208     }
1209   for (i = 0; i < list->FeatureCount; i++)
1210     {
1211       OTF_Feature *feature = list->Feature + i;
1212
1213       SEEK_STREAM (stream, offset + feature->offset);
1214       READ_OFFSET (stream, feature->FeatureParams);
1215       READ_UINT16 (stream, feature->LookupCount);
1216       OTF_MALLOC (feature->LookupListIndex, feature->LookupCount,
1217                   " (LookupListIndex)");
1218       for (j = 0; j < feature->LookupCount; j++)
1219         READ_UINT16 (stream, feature->LookupListIndex[j]);
1220     }
1221
1222   return 0;
1223 }
1224
1225 static int read_lookup_subtable_gsub (OTF *otf, OTF_Stream *stream,
1226                                       long offset, unsigned type,
1227                                       OTF_LookupSubTableGSUB *subtable);
1228 static int read_lookup_subtable_gpos (OTF *otf, OTF_Stream *stream,
1229                                       long offset, unsigned type,
1230                                       OTF_LookupSubTableGPOS *subtable);
1231
1232 static int
1233 read_lookup_list (OTF *otf, OTF_Stream *stream, long offset,
1234                   OTF_LookupList *list, int gsubp)
1235 {
1236   char *errfmt = "Lookup List%s";
1237   int errret = -1;
1238   int i, j;
1239
1240   SEEK_STREAM (stream, offset);
1241   READ_UINT16 (stream, list->LookupCount);
1242   OTF_CALLOC (list->Lookup, list->LookupCount, "");
1243
1244   for (i = 0; i < list->LookupCount; i++)
1245     READ_OFFSET (stream, list->Lookup[i].offset);
1246   for (i = 0; i < list->LookupCount; i++)
1247     {
1248       OTF_Lookup *lookup = list->Lookup + i;
1249
1250       SEEK_STREAM (stream, offset + lookup->offset);
1251       READ_UINT16 (stream, lookup->LookupType);
1252       READ_UINT16 (stream, lookup->LookupFlag);
1253       READ_UINT16 (stream, lookup->SubTableCount);
1254       OTF_MALLOC (lookup->SubTableOffset, lookup->SubTableCount,
1255                   " (SubTableOffset)");
1256       if (gsubp)
1257         OTF_CALLOC (lookup->SubTable.gsub, lookup->SubTableCount,
1258                     " (SubTable)");
1259       else
1260         OTF_CALLOC (lookup->SubTable.gpos, lookup->SubTableCount,
1261                     " (SubTable)");
1262       for (j = 0; j < lookup->SubTableCount; j++)
1263         READ_OFFSET (stream, lookup->SubTableOffset[j]);
1264       for (j = 0; j < lookup->SubTableCount; j++)
1265         {
1266           long this_offset
1267             = offset + lookup->offset + lookup->SubTableOffset[j];
1268
1269           if (gsubp
1270               ? read_lookup_subtable_gsub (otf, stream, this_offset,
1271                                            lookup->LookupType,
1272                                            lookup->SubTable.gsub + j) < 0
1273               : read_lookup_subtable_gpos (otf, stream, this_offset,
1274                                            lookup->LookupType,
1275                                            lookup->SubTable.gpos + j) < 0)
1276             return errret;
1277         }
1278     }
1279
1280   return 0;
1281 }
1282
1283 \f
1284 /*** (1-8) Structures common to GSUB and GPOS */
1285
1286 static unsigned
1287 read_lookup_record_list (OTF *otf, OTF_Stream *stream,
1288                          OTF_LookupRecord **record, int count)
1289 {
1290   char *errfmt = "LookupRecord%s";
1291   unsigned errret = 0;
1292   int i;
1293
1294   if (count < 0)
1295     READ_UINT16 (stream, count);
1296   if (! count)
1297     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1298   OTF_MALLOC (*record, count, "");
1299   for (i = 0; i < count; i++)
1300     {
1301       READ_UINT16 (stream, (*record)[i].SequenceIndex);
1302       READ_UINT16 (stream, (*record)[i].LookupListIndex);
1303     }
1304   return count;
1305 }
1306
1307 static unsigned
1308 read_rule_list (OTF *otf, OTF_Stream *stream, long offset, OTF_Rule **rule)
1309 {
1310   char *errfmt = "List of Rule%s";
1311   unsigned errret = 0;
1312   OTF_StreamState state;
1313   unsigned count;
1314   int i;
1315
1316   READ_UINT16 (stream, count);
1317   if (! count)
1318     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1319   OTF_MALLOC (*rule, count, "");
1320   for (i = 0; i < count; i++)
1321     {
1322       READ_OFFSET (stream, (*rule)[i].offset);
1323       if (! (*rule)[i].offset)
1324         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1325     }
1326   SAVE_STREAM (stream, state);
1327   for (i = 0; i < count; i++)
1328     {
1329       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1330       READ_UINT16 (stream, (*rule)[i].GlyphCount);
1331       if ((*rule)[i].GlyphCount == 0)
1332         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1333       READ_UINT16 (stream, (*rule)[i].LookupCount);
1334       if (read_glyph_ids (otf, stream, &(*rule)[i].Input, 0,
1335                           (*rule)[i].GlyphCount) < 0)
1336         return errret;
1337       if (read_lookup_record_list (otf, stream, &(*rule)[i].LookupRecord,
1338                                    (*rule)[i].LookupCount) == 0)
1339         return errret;
1340     }
1341   RESTORE_STREAM (stream, state);
1342   return count;
1343 }
1344
1345
1346 static unsigned
1347 read_rule_set_list (OTF *otf, OTF_Stream *stream, long offset,
1348                     OTF_RuleSet **set)
1349 {
1350   char *errfmt = "List of RuleSet%s";
1351   unsigned errret = 0;
1352   OTF_StreamState state;
1353   unsigned count;
1354   int i;
1355
1356   READ_UINT16 (stream, count);
1357   if (! count)
1358     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1359   OTF_MALLOC (*set, count, "");
1360   for (i = 0; i < count; i++)
1361     {
1362       READ_OFFSET (stream, (*set)[i].offset);
1363       if (! (*set)[i].offset)
1364         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1365     }
1366   SAVE_STREAM (stream, state);
1367   for (i = 0; i < count; i++)
1368     {
1369       SEEK_STREAM (stream, offset + (*set)[i].offset);
1370       (*set)[i].RuleCount
1371         = read_rule_list (otf, stream, offset + (*set)[i].offset,
1372                           &(*set)[i].Rule);
1373       if (! (*set)[i].RuleCount)
1374         return errret;
1375     }
1376   RESTORE_STREAM (stream, state);
1377   return count;
1378 }
1379
1380 static unsigned
1381 read_class_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1382                       OTF_ClassRule **rule)
1383 {
1384   char *errfmt = "ClassRule%s";
1385   unsigned errret = 0;
1386   OTF_StreamState state;
1387   unsigned count;
1388   int i;
1389
1390   READ_UINT16 (stream, count);
1391   if (! count)
1392     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1393   OTF_MALLOC (*rule, count, "");
1394   for (i = 0; i < count; i++)
1395     {
1396       READ_OFFSET (stream, (*rule)[i].offset);
1397       if (! (*rule)[i].offset)
1398         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1399     }
1400   SAVE_STREAM (stream, state);
1401   for (i = 0; i < count; i++)
1402     {
1403       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1404       READ_USHORT (stream, (*rule)[i].GlyphCount);
1405       if (! (*rule)[i].GlyphCount)
1406         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1407       READ_USHORT (stream, (*rule)[i].LookupCount);
1408       if (read_glyph_ids (otf, stream, (OTF_GlyphID **) &(*rule)[i].Class,
1409                           0, (*rule)[i].GlyphCount - 1) < 0)
1410         return errret;
1411       if (read_lookup_record_list (otf, stream, &(*rule)[i].LookupRecord,
1412                                    (*rule)[i].LookupCount) == 0)
1413         return errret;
1414     }
1415   RESTORE_STREAM (stream, state);
1416   return count;
1417 }
1418
1419 static unsigned
1420 read_class_set_list (OTF *otf, OTF_Stream *stream, long offset,
1421                      OTF_ClassSet **set)
1422 {
1423   char *errfmt = "ClassSet%s";
1424   unsigned errret = 0;
1425   OTF_StreamState state;
1426   unsigned count;
1427   int i;
1428
1429   READ_UINT16 (stream, count);
1430   if (! count)
1431     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1432   OTF_CALLOC (*set, count, "");
1433   for (i = 0; i < count; i++)
1434     /* Offset can be zero.  */
1435     READ_OFFSET (stream, (*set)[i].offset);
1436   SAVE_STREAM (stream, state);
1437   for (i = 0; i < count; i++)
1438     if ((*set)[i].offset)
1439       {
1440         SEEK_STREAM (stream, offset + (*set)[i].offset);
1441         (*set)[i].ClassRuleCnt
1442           = read_class_rule_list (otf, stream, offset + (*set)[i].offset,
1443                                   &(*set)[i].ClassRule);
1444         if (! (*set)[i].ClassRuleCnt)
1445           return errret;
1446       }
1447   RESTORE_STREAM (stream, state);
1448   return count;
1449 }
1450
1451 static unsigned
1452 read_chain_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1453                       OTF_ChainRule **rule)
1454 {
1455   char *errfmt = "ChainRule%s";
1456   unsigned errret = 0;
1457   unsigned count;
1458   int i;
1459
1460   READ_UINT16 (stream, count);
1461   if (! count)
1462     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1463   OTF_MALLOC (*rule, count, "");
1464   for (i = 0; i < count; i++)
1465     READ_OFFSET (stream, (*rule)[i].offset);
1466   for (i = 0; i < count; i++)
1467     {
1468       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1469       (*rule)[i].BacktrackGlyphCount
1470         = read_glyph_ids (otf, stream, &(*rule)[i].Backtrack, 0, -1);
1471       (*rule)[i].InputGlyphCount
1472         = read_glyph_ids (otf, stream, &(*rule)[i].Input, -1, -1);
1473       if (! (*rule)[i].InputGlyphCount)
1474         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1475       (*rule)[i].LookaheadGlyphCount
1476         = read_glyph_ids (otf, stream, &(*rule)[i].LookAhead, 0, -1);
1477       (*rule)[i].LookupCount
1478         = read_lookup_record_list (otf, stream,
1479                                    &(*rule)[i].LookupRecord, -1);
1480       if (! (*rule)[i].LookupCount)
1481         return errret;
1482     }
1483   return count;
1484 }
1485
1486
1487 static unsigned
1488 read_chain_rule_set_list (OTF *otf, OTF_Stream *stream, long offset,
1489                      OTF_ChainRuleSet **set)
1490 {
1491   char *errfmt = "ChainRuleSet%s";
1492   unsigned errret = 0;
1493   OTF_StreamState state;
1494   unsigned count;
1495   int i;
1496
1497   READ_UINT16 (stream, count);
1498   if (! count)
1499     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1500   OTF_MALLOC (*set, count, "");
1501   for (i = 0; i < count; i++)
1502     {
1503       READ_OFFSET (stream, (*set)[i].offset);
1504       if (! (*set)[i].offset)
1505         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1506     }
1507   SAVE_STREAM (stream, state);
1508   for (i = 0; i < count; i++)
1509     {
1510       SEEK_STREAM (stream, offset + (*set)[i].offset);
1511       (*set)[i].ChainRuleCount
1512         = read_chain_rule_list (otf, stream, offset + (*set)[i].offset,
1513                                 &(*set)[i].ChainRule);
1514       if (! (*set)[i].ChainRuleCount)
1515         return errret;
1516     }
1517   RESTORE_STREAM (stream, state);
1518   return count;
1519 }
1520
1521 static unsigned
1522 read_chain_class_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1523                             OTF_ChainClassRule **rule)
1524 {
1525   char *errfmt = "ChainClassRule%s";
1526   unsigned errret = 0;
1527   unsigned count;
1528   int i;
1529
1530   READ_UINT16 (stream, count);
1531   if (! count)
1532     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1533   OTF_MALLOC (*rule, count, "");
1534   for (i = 0; i < count; i++)
1535     {
1536       READ_OFFSET (stream, (*rule)[i].offset);
1537       if (! (*rule)[i].offset)
1538         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1539     }
1540   for (i = 0; i < count; i++)
1541     {
1542       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1543       (*rule)[i].BacktrackGlyphCount
1544         = read_glyph_ids (otf, stream,
1545                           (OTF_GlyphID **) &(*rule)[i].Backtrack, 0, -1);
1546       (*rule)[i].InputGlyphCount
1547         = read_glyph_ids (otf, stream,
1548                           (OTF_GlyphID **) &(*rule)[i].Input, -1, -1);
1549       if (! (*rule)[i].InputGlyphCount)
1550         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1551       (*rule)[i].LookaheadGlyphCount
1552         = read_glyph_ids (otf, stream,
1553                           (OTF_GlyphID **) &(*rule)[i].LookAhead, 0, -1);
1554       (*rule)[i].LookupCount
1555         = read_lookup_record_list (otf, stream,
1556                                    &(*rule)[i].LookupRecord, -1);
1557       if (! (*rule)[i].LookupCount)
1558         return errret;
1559     }
1560   return count;
1561 }
1562
1563 static unsigned
1564 read_chain_class_set_list (OTF *otf, OTF_Stream *stream, long offset,
1565                            OTF_ChainClassSet **set)
1566 {
1567   char *errfmt = "ChainClassSet%s";
1568   unsigned errret = 0;
1569   OTF_StreamState state;
1570   unsigned count;
1571   int i;
1572
1573   READ_UINT16 (stream, count);
1574   if (! count)
1575     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1576   OTF_MALLOC (*set, count, "");
1577   for (i = 0; i < count; i++)
1578     /* Offset may be zero.  */
1579     READ_OFFSET (stream, (*set)[i].offset);
1580   SAVE_STREAM (stream, state);
1581   for (i = 0; i < count; i++)
1582     if ((*set)[i].offset)
1583       {
1584         SEEK_STREAM (stream, offset + (*set)[i].offset);
1585         (*set)[i].ChainClassRuleCnt
1586           = read_chain_class_rule_list (otf, stream, offset + (*set)[i].offset,
1587                                         &(*set)[i].ChainClassRule);
1588         if (! (*set)[i].ChainClassRuleCnt)
1589           return errret;
1590       }
1591   RESTORE_STREAM (stream, state);
1592   return count;
1593 }
1594
1595 static int
1596 read_context1 (OTF *otf, OTF_Stream *stream, long offset,
1597                OTF_Coverage *coverage,OTF_Context1 *context1)
1598 {
1599   if (read_coverage (otf, stream, offset, coverage) < 0)
1600     return -1;
1601   context1->RuleSetCount
1602     = read_rule_set_list (otf, stream, offset, &context1->RuleSet);
1603   if (! context1->RuleSetCount)
1604     return -1;
1605   return 0;
1606 }
1607
1608 static int
1609 read_context2 (OTF *otf, OTF_Stream *stream, long offset,
1610                OTF_Coverage *coverage,OTF_Context2 *context2)
1611 {
1612   if (read_coverage (otf, stream, offset, coverage) < 0
1613       || read_class_def (otf, stream, offset, &context2->ClassDef) < 0)
1614     return -1;
1615   context2->ClassSetCnt
1616     = read_class_set_list (otf, stream, offset, &context2->ClassSet);
1617   if (! context2->ClassSetCnt)
1618     return -1;
1619   return 0;
1620 }
1621
1622 static int
1623 read_context3 (OTF *otf, OTF_Stream *stream, long offset,
1624                OTF_Coverage *coverage,OTF_Context3 *context3)
1625 {
1626   char *errfmt = "Context1%s";
1627   int errret = -1;
1628
1629   READ_USHORT (stream, context3->GlyphCount);
1630   if (context3->GlyphCount < 0)
1631     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1632   READ_USHORT (stream, context3->LookupCount);
1633   if (read_coverage_list (otf, stream, offset, &context3->Coverage,
1634                           context3->GlyphCount) < 0)
1635     return errret;
1636   if (read_lookup_record_list (otf, stream, &context3->LookupRecord,
1637                                context3->LookupCount) < 0)
1638     return errret;
1639   return 0;
1640 }
1641
1642 static int
1643 read_chain_context1 (OTF *otf, OTF_Stream *stream, long offset,
1644                      OTF_Coverage *coverage, OTF_ChainContext1 *chain_context1)
1645 {
1646   if (read_coverage (otf, stream, offset, coverage) < 0)
1647     return -1;
1648   chain_context1->ChainRuleSetCount
1649     = read_chain_rule_set_list (otf, stream, offset,
1650                                 &chain_context1->ChainRuleSet);
1651   if (! chain_context1->ChainRuleSetCount)
1652     return -1;
1653   return 0;
1654 }
1655
1656 static int
1657 read_chain_context2 (OTF *otf, OTF_Stream *stream, long offset,
1658                      OTF_Coverage *coverage, OTF_ChainContext2 *chain_context2)
1659 {
1660   if (read_coverage (otf, stream, offset, coverage) < 0
1661       || read_class_def (otf, stream, offset,
1662                          &chain_context2->BacktrackClassDef) < 0
1663       || read_class_def (otf, stream, offset,
1664                          &chain_context2->InputClassDef) < 0
1665       || read_class_def (otf, stream, offset,
1666                          &chain_context2->LookaheadClassDef) < 0)
1667     return -1;
1668   chain_context2->ChainClassSetCnt
1669     = read_chain_class_set_list (otf, stream, offset,
1670                                  &chain_context2->ChainClassSet);
1671   if (! chain_context2->ChainClassSetCnt)
1672     return -1;
1673   return 0;
1674 }
1675
1676 static int
1677 read_chain_context3 (OTF *otf, OTF_Stream *stream, long offset,
1678                      OTF_Coverage *coverage, OTF_ChainContext3 *chain_context3)
1679 {
1680   int count;
1681
1682   count = read_coverage_list (otf, stream, offset,
1683                               &chain_context3->Backtrack, -1);
1684   if (count < 0)
1685     return -1;
1686   chain_context3->BacktrackGlyphCount = (unsigned) count;
1687   count = read_coverage_list (otf, stream, offset,
1688                               &chain_context3->Input, -1);
1689   if (count <= 0)
1690     return -1;
1691   chain_context3->InputGlyphCount = (unsigned) count;
1692   *coverage = chain_context3->Input[0];
1693   count = read_coverage_list (otf, stream, offset,
1694                               &chain_context3->LookAhead, -1);
1695   chain_context3->LookaheadGlyphCount = (unsigned) count;
1696   chain_context3->LookupCount
1697     = read_lookup_record_list (otf, stream,
1698                                &chain_context3->LookupRecord, -1);
1699   return 0;
1700 }
1701
1702 static void *
1703 read_gsub_gpos_table (OTF *otf, OTF_TableInfo *table, int gsubp,
1704                       enum OTF_ReaderFlag flag)
1705 {
1706   OTF_Stream *stream = table->stream;
1707   char *errfmt = gsubp ? "GSUB%s" : "GPOS%s";
1708   void *errret = NULL;
1709   OTF_GSUB_GPOS *gsub_gpos = *table->address;
1710
1711   if (gsub_gpos)
1712     SEEK_STREAM (stream, 10);
1713   else
1714     {
1715       SEEK_STREAM (stream, 0);
1716       OTF_CALLOC (gsub_gpos, 1, "");
1717       READ_FIXED (stream, gsub_gpos->Version);
1718       READ_OFFSET (stream, gsub_gpos->ScriptList.offset);
1719       READ_OFFSET (stream, gsub_gpos->FeatureList.offset);
1720       READ_OFFSET (stream, gsub_gpos->LookupList.offset);
1721       *table->address = gsub_gpos;
1722     }
1723
1724   if (! gsub_gpos->ScriptList.Script
1725       && read_script_list (otf, stream, gsub_gpos->ScriptList.offset,
1726                            &gsub_gpos->ScriptList) < 0)
1727     return NULL;
1728   if (flag != OTF_READ_SCRIPTS)
1729     {
1730       if (! gsub_gpos->FeatureList.Feature
1731           && read_feature_list (otf, stream, gsub_gpos->FeatureList.offset,
1732                                 &gsub_gpos->FeatureList) < 0)
1733         return NULL;
1734       if (flag != OTF_READ_FEATURES)
1735         {
1736           if (! gsub_gpos->LookupList.Lookup
1737               && read_lookup_list (otf, stream, gsub_gpos->LookupList.offset,
1738                                    &gsub_gpos->LookupList, gsubp) < 0)
1739             return NULL;
1740         }
1741     }
1742
1743   return gsub_gpos;
1744 }
1745
1746 \f
1747 /* (1-9) "GSUB" table */
1748
1749 static unsigned
1750 read_sequence (OTF *otf, OTF_Stream *stream, long offset, OTF_Sequence **seq)
1751 {
1752   char *errfmt = "Sequence%s";
1753   unsigned errret = 0;
1754   unsigned count;
1755   int i;
1756
1757   READ_UINT16 (stream, count);
1758   if (! count)
1759     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1760   OTF_MALLOC (*seq, count, "");
1761   for (i = 0; i < count; i++)
1762     READ_OFFSET (stream, (*seq)[i].offset);
1763   for (i = 0; i < count; i++)
1764     {
1765       SEEK_STREAM (stream, offset + (*seq)[i].offset);
1766       (*seq)[i].GlyphCount = read_glyph_ids (otf, stream,
1767                                              &(*seq)[i].Substitute, 0, -1);
1768       if (! (*seq)[i].GlyphCount)
1769         return 0;
1770     }
1771   return count;
1772 }
1773
1774 static int
1775 read_ligature (OTF *otf, OTF_Stream *stream, long offset,
1776                OTF_Ligature **ligature)
1777 {
1778   char *errfmt = "Ligature%s";
1779   int errret = -1;
1780   int count;
1781   int i;
1782
1783   READ_UINT16 (stream, count);
1784   if (! count)
1785     return 0;
1786   OTF_MALLOC (*ligature, count, "");
1787   for (i = 0; i < count; i++)
1788     READ_OFFSET (stream, (*ligature)[i].offset);
1789   for (i = 0; i < count; i++)
1790     {
1791       SEEK_STREAM (stream, offset + (*ligature)[i].offset);
1792       READ_GLYPHID (stream, (*ligature)[i].LigGlyph);
1793       (*ligature)[i].CompCount
1794         = read_glyph_ids (otf, stream, &(*ligature)[i].Component, -1, -1);
1795       if (! (*ligature)[i].CompCount)
1796         return -1;
1797     }
1798   return count;
1799 }
1800
1801 static unsigned
1802 read_ligature_set_list (OTF *otf, OTF_Stream *stream, long offset,
1803                         OTF_LigatureSet **ligset)
1804 {
1805   char *errfmt = "LigatureSet%s";
1806   int errret = 0;
1807   int count;
1808   int i;
1809
1810   READ_UINT16 (stream, count);
1811   if (! count)
1812     return errret;
1813   OTF_MALLOC (*ligset, count, "");
1814   for (i = 0; i < count; i++)
1815     READ_OFFSET (stream, (*ligset)[i].offset);
1816   for (i = 0; i < count; i++)
1817     {
1818       int lig_count;
1819
1820       SEEK_STREAM (stream, offset + (*ligset)[i].offset);
1821       lig_count = read_ligature (otf, stream, offset + (*ligset)[i].offset,
1822                                  &(*ligset)[i].Ligature);
1823       if (lig_count < 0)
1824         return errret;
1825       (*ligset)[i].LigatureCount = (unsigned) lig_count;
1826     }
1827   return count;
1828 }
1829
1830 static unsigned
1831 read_alternate_set_list (OTF *otf, OTF_Stream *stream, long offset,
1832                          OTF_AlternateSet **altset)
1833 {
1834   char *errfmt = "AlternateSet%s";
1835   int errret = 0;
1836   unsigned count;
1837   int i;
1838
1839   READ_UINT16 (stream, count);
1840   if (! count)
1841     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1842   OTF_MALLOC (*altset, count, "");
1843   for (i = 0; i < count; i++)
1844     READ_OFFSET (stream, (*altset)[i].offset);
1845   for (i = 0; i < count; i++)
1846     {
1847       int alt_count;
1848
1849       SEEK_STREAM (stream, offset + (*altset)[i].offset);
1850       alt_count = read_glyph_ids (otf, stream, &(*altset)[i].Alternate, 0, -1);
1851       if (alt_count < 0)
1852         return errret;
1853       (*altset)[i].GlyphCount = (unsigned) alt_count;
1854     }
1855   return count;
1856 }
1857
1858 static int
1859 read_reverse_chain1 (OTF *otf, OTF_Stream *stream, long offset,
1860                      OTF_Coverage *coverage,
1861                      OTF_GSUB_ReverseChain1 *reverse_chain)
1862 {
1863   int count;
1864
1865   if (read_coverage (otf, stream, offset, coverage) < 0)
1866     return -1;
1867   count = read_coverage_list (otf, stream, offset,
1868                               &reverse_chain->Backtrack, -1);
1869   if (count < 0)
1870     return -1;
1871   reverse_chain->BacktrackGlyphCount = (unsigned) count;
1872   count = read_coverage_list (otf, stream, offset,
1873                               &reverse_chain->LookAhead, -1);
1874   if (count <= 0)
1875     return -1;
1876   reverse_chain->LookaheadGlyphCount = (unsigned) count;
1877   count = read_glyph_ids (otf, stream, &reverse_chain->Substitute, 0, -1);
1878   if (count <= 0)
1879     return -1;
1880   reverse_chain->GlyphCount = count;  
1881   return 0;
1882 }
1883
1884 static int
1885 read_lookup_subtable_gsub (OTF *otf, OTF_Stream *stream, long offset,
1886                            unsigned type, OTF_LookupSubTableGSUB *subtable)
1887 {
1888   char errfmt[256];
1889   int errret = -1;
1890
1891   SEEK_STREAM (stream, offset);
1892   READ_USHORT (stream, subtable->Format);
1893   sprintf (errfmt, "GSUB Lookup %d-%d%%s", type, subtable->Format);
1894   switch (type)
1895     {
1896     case 1:
1897       if (subtable->Format == 1)
1898         {
1899           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1900             return -1;
1901           READ_INT16 (stream, subtable->u.single1.DeltaGlyphID);
1902         }
1903       else if (subtable->Format == 2)
1904         {
1905           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1906             return -1;
1907           subtable->u.single2.GlyphCount
1908             = read_glyph_ids (otf, stream, &subtable->u.single2.Substitute,
1909                               0, -1);
1910           if (! subtable->u.single2.GlyphCount)
1911             return -1;
1912         }
1913       else
1914         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1915       break;
1916
1917     case 2:
1918       if (subtable->Format == 1)
1919         {
1920           read_coverage (otf, stream, offset, &subtable->Coverage);
1921           subtable->u.multiple1.SequenceCount
1922             = read_sequence (otf, stream, offset,
1923                              &subtable->u.multiple1.Sequence);
1924         }
1925       else
1926         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1927       break;
1928
1929     case 3:
1930       if (subtable->Format == 1)
1931         {
1932           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1933             return -1;
1934           subtable->u.alternate1.AlternateSetCount
1935             = read_alternate_set_list (otf, stream, offset,
1936                                        &subtable->u.alternate1.AlternateSet);
1937           if (! subtable->u.alternate1.AlternateSetCount)
1938             return -1;
1939         }
1940       else
1941         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1942       break;
1943
1944     case 4:
1945       if (subtable->Format == 1)
1946         {
1947           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1948             return -1;
1949           subtable->u.ligature1.LigSetCount
1950             = read_ligature_set_list (otf, stream, offset,
1951                                       &subtable->u.ligature1.LigatureSet);
1952           if (! subtable->u.ligature1.LigSetCount)
1953             return -1;
1954         }
1955       else
1956         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1957       break;
1958
1959     case 5:
1960       if (subtable->Format == 1)
1961         {
1962           if (read_context1 (otf, stream, offset, &subtable->Coverage,
1963                              &subtable->u.context1) < 0)
1964             return errret;
1965         }
1966       else if (subtable->Format == 2)
1967         {
1968           if (read_context2 (otf, stream, offset, &subtable->Coverage,
1969                              &subtable->u.context2) < 0)
1970             return errret;
1971         }
1972       else if (subtable->Format == 3)
1973         {
1974           if (read_context3 (otf, stream, offset, &subtable->Coverage,
1975                              &subtable->u.context3) < 0)
1976             return errret;
1977         }
1978       else
1979         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1980       break;
1981
1982     case 6:
1983       if (subtable->Format == 1)
1984         {
1985           if (read_chain_context1 (otf, stream, offset, &subtable->Coverage,
1986                                    &subtable->u.chain_context1) < 0)
1987             return errret;
1988         }
1989       else if (subtable->Format == 2)
1990         {
1991           if (read_chain_context2 (otf, stream, offset, &subtable->Coverage,
1992                                    &subtable->u.chain_context2) < 0)
1993             return errret;
1994         }
1995       else if (subtable->Format == 3)
1996         {
1997           if (read_chain_context3 (otf, stream, offset, &subtable->Coverage,
1998                                    &subtable->u.chain_context3) < 0)
1999             return errret;
2000         }
2001       else
2002         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2003       break;
2004
2005     case 7:
2006       if (subtable->Format == 1)
2007         {
2008           unsigned ex_type;
2009           long ex_offset;
2010           OTF_LookupSubTableGSUB *ex_subtable;
2011
2012           READ_USHORT (stream, ex_type);
2013           READ_ULONG (stream, ex_offset);
2014           OTF_CALLOC (ex_subtable, 1, " (SubTable)");
2015           if (read_lookup_subtable_gsub (otf, stream, offset + ex_offset,
2016                                          ex_type, ex_subtable) < 0)
2017             return errret;
2018           subtable->u.extension1.ExtensionLookupType = ex_type;
2019           subtable->u.extension1.ExtensionOffset = ex_offset;
2020           subtable->u.extension1.ExtensionSubtable = ex_subtable;
2021         }
2022       else
2023         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2024       break;
2025
2026     case 8:
2027       if (subtable->Format == 1)
2028         {
2029           if (read_reverse_chain1 (otf, stream, offset, &subtable->Coverage,
2030                                    &subtable->u.reverse_chain1) < 0)
2031             return errret;
2032         }
2033       else
2034         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2035       break;
2036
2037     default:
2038       OTF_ERROR (OTF_ERROR_TABLE, " (Invalid LookupType)");
2039     }
2040   return 0;
2041 }
2042
2043 static void *
2044 read_gsub_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
2045 {
2046   return read_gsub_gpos_table (otf, table, 1, flag);
2047 }
2048
2049 \f
2050 /* (1-10) "GPOS" table */
2051
2052 static int
2053 read_value_record (OTF *otf, OTF_Stream *stream, long offset,
2054                    enum OTF_ValueFormat bit, OTF_ValueRecord *value_record)
2055 {
2056   int errret = -1;
2057   OTF_StreamState state;
2058   int size, i;
2059
2060   memset (value_record, 0, sizeof (OTF_ValueRecord));
2061   if (! bit)
2062     return 0;
2063   for (i = 0, size = 0; i < 8; i++)
2064     if (bit & (1 << i))
2065       size += 2;
2066
2067   if (bit & OTF_XPlacement)
2068     READ_INT16 (stream, value_record->XPlacement);
2069   if (bit & OTF_YPlacement)
2070     READ_INT16 (stream, value_record->YPlacement);
2071   if (bit & OTF_XAdvance)
2072     READ_INT16 (stream, value_record->XAdvance);
2073   if (bit & OTF_YAdvance)
2074     READ_INT16 (stream, value_record->YAdvance);
2075   if (bit & OTF_XPlaDevice)
2076     READ_OFFSET (stream, value_record->XPlaDevice.offset);
2077   if (bit & OTF_YPlaDevice)
2078     READ_OFFSET (stream, value_record->YPlaDevice.offset);
2079   if (bit & OTF_XAdvDevice)
2080     READ_OFFSET (stream, value_record->XAdvDevice.offset);
2081   if (bit & OTF_YAdvDevice)
2082     READ_OFFSET (stream, value_record->YAdvDevice.offset);
2083   SAVE_STREAM (stream, state);
2084   if (value_record->XPlaDevice.offset)
2085     {
2086       if (read_device_table (otf, stream, offset, &value_record->XPlaDevice) < 0)
2087         return -1;
2088     }
2089   if (value_record->YPlaDevice.offset)
2090     {
2091       if (read_device_table (otf, stream, offset, &value_record->YPlaDevice) < 0)
2092         return -1;
2093     }
2094   if (value_record->XAdvDevice.offset)
2095     {
2096       if (read_device_table (otf, stream, offset, &value_record->XAdvDevice) < 0)
2097         return -1;
2098     }
2099   if (value_record->YAdvDevice.offset)
2100     {
2101       if (read_device_table (otf, stream, offset, &value_record->YAdvDevice) < 0)
2102         return -1;
2103     }
2104   RESTORE_STREAM (stream, state);
2105   return 0;
2106 }
2107
2108
2109 static int
2110 read_anchor (OTF *otf, OTF_Stream *stream, long offset, OTF_Anchor *anchor)
2111 {
2112   char *errfmt = "Anchor%s";
2113   int errret = -1;
2114
2115   SEEK_STREAM (stream, offset + anchor->offset);
2116   READ_UINT16 (stream, anchor->AnchorFormat);
2117   READ_INT16 (stream, anchor->XCoordinate);
2118   READ_INT16 (stream, anchor->YCoordinate);
2119   if (anchor->AnchorFormat == 1)
2120     ;
2121   else if (anchor->AnchorFormat == 2)
2122     {
2123       READ_UINT16 (stream, anchor->f.f1.AnchorPoint);
2124     }
2125   else if (anchor->AnchorFormat == 3)
2126     {
2127       READ_OFFSET (stream, anchor->f.f2.XDeviceTable.offset);
2128       READ_OFFSET (stream, anchor->f.f2.YDeviceTable.offset);
2129       if (anchor->f.f2.XDeviceTable.offset)
2130         {
2131           if (read_device_table (otf, stream, offset + anchor->offset,
2132                                  &anchor->f.f2.XDeviceTable) < 0)
2133             return -1;
2134         }
2135       if (anchor->f.f2.YDeviceTable.offset)
2136         {
2137           if (read_device_table (otf, stream, offset + anchor->offset,
2138                                  &anchor->f.f2.YDeviceTable) < 0)
2139             return -1;
2140         }
2141     }
2142   else
2143     OTF_ERROR (OTF_ERROR_TABLE, " (invalid format)");
2144
2145   return 0;
2146 }
2147
2148 static int
2149 read_mark_array (OTF *otf, OTF_Stream *stream, long offset,
2150                  OTF_MarkArray *array)
2151 {
2152   char *errfmt = "MarkArray%s";
2153   int errret = -1;
2154   OTF_StreamState state;
2155   int i;
2156
2157   READ_OFFSET (stream, array->offset);
2158   SAVE_STREAM (stream, state);
2159   SEEK_STREAM (stream, offset + array->offset);
2160   READ_UINT16 (stream, array->MarkCount);
2161   OTF_MALLOC (array->MarkRecord, array->MarkCount, "");
2162   for (i = 0; i < array->MarkCount; i++)
2163     {
2164       READ_UINT16 (stream, array->MarkRecord[i].Class);
2165       READ_OFFSET (stream, array->MarkRecord[i].MarkAnchor.offset);
2166     }
2167   for (i = 0; i < array->MarkCount; i++)
2168     if (read_anchor (otf, stream, offset + array->offset,
2169                      &array->MarkRecord[i].MarkAnchor) < 0)
2170       return -1;;
2171   RESTORE_STREAM (stream, state);
2172   return 0;
2173 }
2174
2175 static int
2176 read_anchor_array (OTF *otf, OTF_Stream *stream, long offset,
2177                    unsigned ClassCount, OTF_AnchorArray *array)
2178 {
2179   char *errfmt = "AnchorArray%s";
2180   int errret = -1;
2181   OTF_StreamState state;
2182   int i, j;
2183
2184   READ_OFFSET (stream, array->offset);
2185   SAVE_STREAM (stream, state);
2186   SEEK_STREAM (stream, offset + array->offset);
2187   READ_UINT16 (stream, array->Count);
2188   OTF_MALLOC (array->AnchorRecord, array->Count, "");
2189   for (i = 0; i < array->Count; i++)
2190     {
2191       OTF_MALLOC (array->AnchorRecord[i].Anchor, ClassCount,
2192                   " (AnchorRecord)");
2193       for (j = 0; j < ClassCount; j++)
2194         READ_OFFSET (stream, array->AnchorRecord[i].Anchor[j].offset);
2195     }
2196   for (i = 0; i < array->Count; i++)
2197     for (j = 0; j < ClassCount; j++)
2198       if (read_anchor (otf, stream, offset + array->offset,
2199                        &array->AnchorRecord[i].Anchor[j]) < 0)
2200         return -1;
2201   RESTORE_STREAM (stream, state);
2202   return 0;
2203 }
2204
2205 static OTF_PairSet *
2206 read_pair_set_list (OTF *otf, OTF_Stream *stream, long offset, unsigned num,
2207                     enum OTF_ValueFormat bit1, enum OTF_ValueFormat bit2)
2208 {
2209   char *errfmt = "PairSet%s";
2210   void *errret = NULL;
2211   OTF_StreamState state;
2212   OTF_PairSet *set;
2213   int i, j;
2214
2215   OTF_MALLOC (set, num, "");
2216   for (i = 0; i < num; i++)
2217     READ_OFFSET (stream, set[i].offset);
2218   SAVE_STREAM (stream, state);
2219   for (i = 0; i < num; i++)
2220     {
2221       SEEK_STREAM (stream, offset + set[i].offset);
2222       READ_UINT16 (stream, set[i].PairValueCount);
2223       OTF_MALLOC (set[i].PairValueRecord, set[i].PairValueCount, "");
2224       for (j = 0; j < set[i].PairValueCount; j++)
2225         {
2226           OTF_PairValueRecord *rec = set[i].PairValueRecord + j;
2227
2228           READ_UINT16 (stream, rec->SecondGlyph);
2229           read_value_record (otf, stream, offset, bit1, &rec->Value1);
2230           read_value_record (otf, stream, offset, bit2, &rec->Value2);
2231         }
2232     }
2233   RESTORE_STREAM (stream, state);
2234   return set;
2235 }
2236
2237 static OTF_Class1Record *
2238 read_class1_record_list (OTF *otf, OTF_Stream *stream, long offset,
2239                          unsigned num1, enum OTF_ValueFormat bit1,
2240                          unsigned num2, enum OTF_ValueFormat bit2)
2241 {
2242   char *errfmt = "Class1Record%s";
2243   void *errret = NULL;
2244   OTF_Class1Record *rec;
2245   int i, j;
2246
2247   OTF_MALLOC (rec, num1, "");
2248   for (i = 0; i < num1; i++)
2249     {
2250       OTF_CALLOC (rec[i].Class2Record, num2, " (Class2Record)");
2251       for (j = 0; j < num2; j++)
2252         {
2253           if (read_value_record (otf, stream, offset,
2254                                  bit1, &rec[i].Class2Record[j].Value1) < 0
2255               || read_value_record (otf, stream, offset,
2256                                     bit2, &rec[i].Class2Record[j].Value2) < 0)
2257             return NULL;
2258         }
2259     }
2260   return rec;
2261 }
2262
2263 static unsigned
2264 read_entry_exit_list (OTF *otf, OTF_Stream *stream, long offset,
2265                       OTF_EntryExitRecord **rec)
2266 {
2267   char *errfmt = "EntryExitSet%s";
2268   int errret = 0;
2269   unsigned count;
2270   int i;
2271   OTF_StreamState state;
2272
2273   READ_UINT16 (stream, count);
2274   if (! count)
2275     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
2276   OTF_MALLOC (*rec, count, "");
2277   for (i = 0; i < count; i++)
2278     {
2279       READ_OFFSET (stream, (*rec)[i].EntryAnchor.offset);
2280       READ_OFFSET (stream, (*rec)[i].ExitAnchor.offset);
2281     }
2282   SAVE_STREAM (stream, state);
2283   for (i = 0; i < count; i++)
2284     {
2285       if (read_anchor (otf, stream, offset, &(*rec)[i].EntryAnchor) < 0)
2286         return -1;
2287       if (read_anchor (otf, stream, offset, &(*rec)[i].ExitAnchor) < 0)
2288         return -1;
2289     }
2290   RESTORE_STREAM (stream, state);
2291   return count;
2292 }
2293
2294 static int
2295 read_ligature_attach (OTF *otf, OTF_Stream *stream, long offset,
2296                       unsigned ClassCount, OTF_LigatureAttach *attach)
2297 {
2298   char *errfmt = "LigatureAttach%s";
2299   int errret = 1;
2300   int i, j;
2301
2302   SEEK_STREAM (stream, offset + attach->offset);
2303   READ_UINT16 (stream, attach->ComponentCount);
2304   OTF_MALLOC (attach->ComponentRecord, attach->ComponentCount, "");
2305   for (i = 0; i < attach->ComponentCount; i++)
2306     {
2307       OTF_MALLOC (attach->ComponentRecord[i].LigatureAnchor, ClassCount,
2308                   " (ComponentRecord)");
2309       for (j = 0; j < ClassCount; j++)
2310         READ_OFFSET (stream,
2311                      attach->ComponentRecord[i].LigatureAnchor[j].offset);
2312     }
2313   for (i = 0; i < attach->ComponentCount; i++)
2314     for (j = 0; j < ClassCount; j++)
2315       {
2316         if (attach->ComponentRecord[i].LigatureAnchor[j].offset)
2317           {
2318             if (read_anchor (otf, stream, offset + attach->offset,
2319                              &attach->ComponentRecord[i].LigatureAnchor[j]) < 0)
2320               return -1;
2321           }
2322         else
2323           attach->ComponentRecord[i].LigatureAnchor[j].AnchorFormat = 0;
2324       }
2325   return 0;
2326 }
2327
2328 static int
2329 read_ligature_array (OTF *otf, OTF_Stream *stream, long offset,
2330                      unsigned class_count, OTF_LigatureArray *array)
2331 {
2332   char *errfmt = "LigatureArray%s";
2333   int errret = -1;
2334   OTF_StreamState state;
2335   int i;
2336
2337   READ_OFFSET (stream, array->offset);
2338   SAVE_STREAM (stream, state);
2339   SEEK_STREAM (stream, offset + array->offset);
2340   READ_UINT16 (stream, array->LigatureCount);
2341   OTF_MALLOC (array->LigatureAttach, array->LigatureCount, "");
2342   for (i = 0; i < array->LigatureCount; i++)
2343     READ_OFFSET (stream, array->LigatureAttach[i].offset);
2344   for (i = 0; i < array->LigatureCount; i++)
2345     read_ligature_attach (otf, stream, offset + array->offset,
2346                           class_count, array->LigatureAttach + i);
2347   RESTORE_STREAM (stream, state);
2348   return 0;
2349 }
2350
2351 static int
2352 read_lookup_subtable_gpos (OTF *otf, OTF_Stream *stream,
2353                            long offset, unsigned type,
2354                            OTF_LookupSubTableGPOS *subtable)
2355 {
2356   char errfmt[256];
2357   int errret = -1;
2358
2359   SEEK_STREAM (stream, offset);
2360   READ_UINT16 (stream, subtable->Format);
2361   sprintf (errfmt, "GPOS Lookup %d-%d%%s", type, subtable->Format);
2362   switch (type)
2363     {
2364     case 1:
2365       if (subtable->Format == 1)
2366         {
2367           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2368             return -1;
2369           READ_UINT16 (stream, subtable->u.single1.ValueFormat);
2370           read_value_record (otf, stream, offset,
2371                              subtable->u.single1.ValueFormat,
2372                              &subtable->u.single1.Value);
2373         }
2374       else if (subtable->Format == 2)
2375         {
2376           OTF_GPOS_Single2 *single2 = &subtable->u.single2;
2377           int i;
2378
2379           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2380             return -1;
2381           READ_UINT16 (stream, single2->ValueFormat);
2382           READ_UINT16 (stream, single2->ValueCount);
2383           OTF_CALLOC (single2->Value, single2->ValueCount," (ValueRecord)");
2384           for (i = 0; i < single2->ValueCount; i++)
2385             read_value_record (otf, stream, offset, single2->ValueFormat,
2386                                single2->Value + i);
2387         }
2388       else
2389         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2390       break;
2391
2392     case 2:
2393       if (subtable->Format == 1)
2394         {
2395           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2396             return -1;
2397           READ_UINT16 (stream, subtable->u.pair1.ValueFormat1);
2398           READ_UINT16 (stream, subtable->u.pair1.ValueFormat2);
2399           READ_UINT16 (stream, subtable->u.pair1.PairSetCount);
2400           subtable->u.pair1.PairSet
2401             = read_pair_set_list (otf, stream, offset,
2402                                   subtable->u.pair1.PairSetCount,
2403                                   subtable->u.pair1.ValueFormat1,
2404                                   subtable->u.pair1.ValueFormat2);
2405           if (! subtable->u.pair1.PairSet)
2406             return -1;
2407         }
2408       else if (subtable->Format == 2)
2409         {
2410           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2411             return -1;
2412           READ_UINT16 (stream, subtable->u.pair2.ValueFormat1);
2413           READ_UINT16 (stream, subtable->u.pair2.ValueFormat2);
2414           if (read_class_def (otf, stream, offset,
2415                               &subtable->u.pair2.ClassDef1) < 0
2416               || read_class_def (otf, stream, offset,
2417                                  &subtable->u.pair2.ClassDef2) < 0)
2418             return -1;
2419           READ_UINT16 (stream, subtable->u.pair2.Class1Count);
2420           READ_UINT16 (stream, subtable->u.pair2.Class2Count);
2421           subtable->u.pair2.Class1Record
2422             = read_class1_record_list (otf, stream, offset,
2423                                        subtable->u.pair2.Class1Count,
2424                                        subtable->u.pair2.ValueFormat1,
2425                                        subtable->u.pair2.Class2Count,
2426                                        subtable->u.pair2.ValueFormat2);
2427           if (! subtable->u.pair2.Class1Record)
2428             return -1;
2429         }
2430       else
2431         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2432       break;
2433
2434     case 3:
2435       if (subtable->Format == 1)
2436         {
2437           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2438             return -1;
2439           subtable->u.cursive1.EntryExitCount
2440             = read_entry_exit_list (otf, stream, offset,
2441                                     &subtable->u.cursive1.EntryExitRecord);
2442           if (! subtable->u.cursive1.EntryExitCount)
2443             return -1;
2444         }
2445       else
2446         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2447       break;
2448
2449     case 4:
2450       if (subtable->Format == 1)
2451         {
2452           read_coverage (otf, stream, offset, &subtable->Coverage);
2453           read_coverage (otf, stream, offset,
2454                          &subtable->u.mark_base1.BaseCoverage);
2455           READ_UINT16 (stream, subtable->u.mark_base1.ClassCount);
2456           read_mark_array (otf, stream, offset,
2457                            &subtable->u.mark_base1.MarkArray);
2458           read_anchor_array (otf, stream, offset,
2459                              subtable->u.mark_base1.ClassCount,
2460                              &subtable->u.mark_base1.BaseArray);
2461         }
2462       else
2463         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2464       break;
2465
2466     case 5:
2467       if (subtable->Format == 1)
2468         {
2469           read_coverage (otf, stream, offset, &subtable->Coverage);
2470           read_coverage (otf, stream, offset,
2471                          &subtable->u.mark_lig1.LigatureCoverage);
2472           READ_UINT16 (stream, subtable->u.mark_lig1.ClassCount);
2473           read_mark_array (otf, stream, offset,
2474                            &subtable->u.mark_lig1.MarkArray);
2475           read_ligature_array (otf, stream, offset,
2476                                subtable->u.mark_lig1.ClassCount,
2477                                &subtable->u.mark_lig1.LigatureArray);
2478         }
2479       break;
2480
2481     case 6:
2482       if (subtable->Format == 1)
2483         {
2484           read_coverage (otf, stream, offset, &subtable->Coverage);
2485           read_coverage (otf, stream, offset,
2486                          &subtable->u.mark_mark1.Mark2Coverage);
2487           READ_UINT16 (stream, subtable->u.mark_base1.ClassCount);
2488           read_mark_array (otf, stream, offset,
2489                            &subtable->u.mark_mark1.Mark1Array);
2490           read_anchor_array (otf, stream, offset,
2491                              subtable->u.mark_mark1.ClassCount,
2492                              &subtable->u.mark_mark1.Mark2Array);
2493         }
2494       else
2495         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2496       break;
2497
2498     case 7:
2499       if (subtable->Format == 1)
2500         {
2501           if (read_context1 (otf, stream, offset, &subtable->Coverage,
2502                              &subtable->u.context1) < 0)
2503             return errret;
2504         }
2505       else if (subtable->Format == 2)
2506         {
2507           if (read_context2 (otf, stream, offset, &subtable->Coverage,
2508                              &subtable->u.context2) < 0)
2509             return errret;
2510         }
2511       else if (subtable->Format == 3)
2512         {
2513           if (read_context3 (otf, stream, offset, &subtable->Coverage,
2514                              &subtable->u.context3) < 0)
2515             return errret;
2516         }
2517       else
2518         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2519       break;
2520
2521     case 8:
2522       if (subtable->Format == 1)
2523         {
2524           if (read_chain_context1 (otf, stream, offset, &subtable->Coverage,
2525                                    &subtable->u.chain_context1) < 0)
2526             return errret;
2527         }
2528       else if (subtable->Format == 2)
2529         {
2530           if (read_chain_context2 (otf, stream, offset, &subtable->Coverage,
2531                                    &subtable->u.chain_context2) < 0)
2532             return errret;
2533         }
2534       else if (subtable->Format == 3)
2535         {
2536           if (read_chain_context3 (otf, stream, offset, &subtable->Coverage,
2537                                    &subtable->u.chain_context3) < 0)
2538             return errret;
2539         }
2540       else
2541         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2542       break;
2543
2544     case 9:
2545       if (subtable->Format == 1)
2546         {
2547           unsigned ex_type;
2548           long ex_offset;
2549           OTF_LookupSubTableGPOS *ex_subtable;
2550
2551           READ_USHORT (stream, ex_type);
2552           READ_ULONG (stream, ex_offset);
2553           OTF_CALLOC (ex_subtable, 1, " (SubTable)");
2554           if (read_lookup_subtable_gpos (otf, stream, offset + ex_offset,
2555                                          ex_type, ex_subtable) < 0)
2556             return errret;
2557           subtable->u.extension1.ExtensionLookupType = ex_type;
2558           subtable->u.extension1.ExtensionOffset = ex_offset;
2559           subtable->u.extension1.ExtensionSubtable = ex_subtable;
2560         }
2561       else
2562         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2563       break;
2564
2565     default:
2566       OTF_ERROR (OTF_ERROR_TABLE, " (Invalid LookupType)");
2567     }
2568   return 0;
2569 }
2570
2571 static void *
2572 read_gpos_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
2573 {
2574   return read_gsub_gpos_table (otf, table, 0, flag);
2575 }
2576
2577 \f
2578 #if 0
2579 /* BASE */
2580
2581 static OTF_BASE *
2582 read_base_table (OTF_Stream *stream, long offset)
2583 {
2584   OTF_BASE *base;
2585
2586   OTF_MALLOC (base, 1);
2587
2588   return base;
2589 }
2590
2591 \f
2592 /* JSTF */
2593
2594 static OTF_JSTF *
2595 read_jstf_table (OTF_Stream *stream, long offset)
2596 {
2597   OTF_JSTF *jstf;
2598
2599   OTF_MALLOC (jstf, 1);
2600
2601   return jstf;
2602 }
2603 #endif /* 0 */
2604 \f
2605 /*** (1-11) Structure for OTF */
2606
2607 int
2608 read_offset_table (OTF *otf, OTF_Stream *stream, OTF_OffsetTable *table)
2609 {
2610   int errret = -1;
2611
2612   READ_FIXED (stream, table->sfnt_version);
2613   READ_USHORT (stream, table->numTables);
2614   READ_USHORT (stream, table->searchRange);
2615   READ_USHORT (stream, table->enterSelector);
2616   READ_USHORT (stream, table->rangeShift);
2617   return 0;
2618 }
2619
2620 static OTF_Tag
2621 read_table_directory (OTF_Stream *stream, OTF_TableDirectory *table)
2622 {
2623   int errret = 0;
2624   OTF_Tag tag;
2625
2626   READ_TAG (stream, tag);
2627   table->tag = tag;
2628   table->name[0] = tag >> 24;
2629   table->name[1] = (tag >> 16) & 0xFF;
2630   table->name[2] = (tag >> 8) & 0xFF;
2631   table->name[3] = tag & 0xFF;
2632   table->name[4] = '\0';
2633   READ_ULONG (stream, table->checkSum);
2634   READ_ULONG (stream, table->offset);
2635   READ_ULONG (stream, table->length);
2636   return tag;
2637 }
2638
2639 static int
2640 read_header_part (OTF *otf, FILE *fp, FT_Face face)
2641 {
2642   char *errfmt = "otf header%s";
2643   int errret = -1;
2644   int i;
2645   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
2646
2647   internal_data->table_info[OTF_TABLE_TYPE_HEAD].address = (void *) &otf->head;
2648   internal_data->table_info[OTF_TABLE_TYPE_HEAD].reader = read_head_table;
2649   internal_data->table_info[OTF_TABLE_TYPE_NAME].address = (void *) &otf->name;
2650   internal_data->table_info[OTF_TABLE_TYPE_NAME].reader = read_name_table;
2651   internal_data->table_info[OTF_TABLE_TYPE_CMAP].address = (void *) &otf->cmap;
2652   internal_data->table_info[OTF_TABLE_TYPE_CMAP].reader = read_cmap_table;
2653   internal_data->table_info[OTF_TABLE_TYPE_GDEF].address = (void *) &otf->gdef;
2654   internal_data->table_info[OTF_TABLE_TYPE_GDEF].reader = read_gdef_table;
2655   internal_data->table_info[OTF_TABLE_TYPE_GSUB].address = (void *) &otf->gsub;
2656   internal_data->table_info[OTF_TABLE_TYPE_GSUB].reader = read_gsub_table;
2657   internal_data->table_info[OTF_TABLE_TYPE_GPOS].address = (void *) &otf->gpos;
2658   internal_data->table_info[OTF_TABLE_TYPE_GPOS].reader = read_gpos_table;
2659
2660   if (fp)
2661     {
2662       OTF_Tag head_tag = OTF_tag ("head");
2663       OTF_Tag name_tag = OTF_tag ("name");
2664       OTF_Tag cmap_tag = OTF_tag ("cmap");
2665       OTF_Tag gdef_tag = OTF_tag ("GDEF");
2666       OTF_Tag gsub_tag = OTF_tag ("GSUB");
2667       OTF_Tag gpos_tag = OTF_tag ("GPOS");
2668       OTF_Stream *stream = make_stream ("Offset Table");
2669
2670       if (! stream)
2671         return -1;
2672       internal_data->header_stream = stream;
2673
2674       /* Size of Offset Table is 12 bytes.  */
2675       if (setup_stream (stream, fp, 0, 12) < 0)
2676         return -1;
2677       if (read_offset_table (otf, stream, &otf->offset_table) < 0)
2678         return -1;
2679
2680       /* Size of each Table Directory is 16 bytes.  */
2681       if (setup_stream (stream, fp, 12, 16 * otf->offset_table.numTables) < 0)
2682         return -1;
2683
2684       OTF_CALLOC (otf->table_dirs, otf->offset_table.numTables,
2685                   " (OffsetTable)");
2686       for (i = 0; i < otf->offset_table.numTables; i++)
2687         {
2688           OTF_Tag tag = read_table_directory (stream, otf->table_dirs + i);
2689           OTF_TableInfo *table_info = NULL;
2690
2691           if (! tag)
2692             return -1;
2693           if (tag == head_tag)
2694             table_info = internal_data->table_info + OTF_TABLE_TYPE_HEAD;
2695           else if (tag == name_tag)
2696             table_info = internal_data->table_info + OTF_TABLE_TYPE_NAME;
2697           else if (tag == cmap_tag)
2698             table_info = internal_data->table_info + OTF_TABLE_TYPE_CMAP;
2699           else if (tag == gdef_tag)
2700             table_info = internal_data->table_info + OTF_TABLE_TYPE_GDEF;
2701           else if (tag == gsub_tag)
2702             table_info = internal_data->table_info + OTF_TABLE_TYPE_GSUB;
2703           else if (tag == gpos_tag)
2704             table_info = internal_data->table_info + OTF_TABLE_TYPE_GPOS;
2705
2706           if (table_info)
2707             {
2708               table_info->stream = make_stream (otf->table_dirs[i].name);
2709               if (setup_stream (table_info->stream, fp,
2710                                 otf->table_dirs[i].offset,
2711                                 otf->table_dirs[i].length) < 0)
2712                 return -1;
2713             }
2714         }
2715
2716       internal_data->header_stream = NULL;
2717       free_stream (stream);
2718     }
2719   else
2720     {
2721       OTF_Stream *stream;
2722
2723       internal_data->header_stream = NULL;
2724       if ((stream = make_stream_from_ft_face (face, "head")))
2725         internal_data->table_info[OTF_TABLE_TYPE_HEAD].stream = stream;
2726       if ((stream = make_stream_from_ft_face (face, "name")))
2727         internal_data->table_info[OTF_TABLE_TYPE_NAME].stream = stream;
2728       if ((stream = make_stream_from_ft_face (face, "cmap")))
2729         internal_data->table_info[OTF_TABLE_TYPE_CMAP].stream = stream;
2730       if ((stream = make_stream_from_ft_face (face, "GDEF")))
2731         internal_data->table_info[OTF_TABLE_TYPE_GDEF].stream = stream;
2732       if ((stream = make_stream_from_ft_face (face, "GSUB")))
2733         internal_data->table_info[OTF_TABLE_TYPE_GSUB].stream = stream;
2734       if ((stream = make_stream_from_ft_face (face, "GPOS")))
2735         internal_data->table_info[OTF_TABLE_TYPE_GPOS].stream = stream;
2736     }
2737
2738   return 0;
2739 }
2740
2741 static OTF_TableInfo *
2742 get_table_info (OTF *otf, const char *name)
2743 {
2744   char *errfmt = "OTF Table Read%s";
2745   OTF_TableInfo *errret = NULL;
2746   OTF_InternalData *internal_data = otf->internal_data;
2747   OTF_TableInfo *table_info;
2748   OTF_Tag tag = OTF_tag (name);
2749
2750   if (! tag)
2751     OTF_ERROR (OTF_ERROR_TABLE, " (invalid table name)");
2752
2753   if (tag == OTF_tag ("head"))
2754     table_info = internal_data->table_info + OTF_TABLE_TYPE_HEAD;
2755   else if (tag == OTF_tag ("name"))
2756     table_info = internal_data->table_info + OTF_TABLE_TYPE_NAME;
2757   else if (tag == OTF_tag ("cmap"))
2758     table_info = internal_data->table_info + OTF_TABLE_TYPE_CMAP;
2759   else if (tag == OTF_tag ("GDEF"))
2760     table_info = internal_data->table_info + OTF_TABLE_TYPE_GDEF;
2761   else if (tag == OTF_tag ("GSUB"))
2762     table_info = internal_data->table_info + OTF_TABLE_TYPE_GSUB;
2763   else if (tag == OTF_tag ("GPOS"))
2764     table_info = internal_data->table_info + OTF_TABLE_TYPE_GPOS;
2765   else
2766     OTF_ERROR (OTF_ERROR_TABLE, " (unsupported table name)");
2767
2768   if (*table_info->address)
2769     /* Already read.  */
2770     return table_info;
2771   if (! table_info->stream)
2772     OTF_ERROR (OTF_ERROR_TABLE, " (table not found)");
2773   if (! table_info->reader)
2774     OTF_ERROR (OTF_ERROR_TABLE, " (invalid contents)");
2775   return table_info;
2776 }
2777
2778
2779 \f
2780 /*** (2) API for reading OTF */
2781
2782 /*** (2-1) OTF_open() */
2783
2784 /* Note: We can't use memory allocation macros in the following
2785    functions because those macros return from the functions before
2786    freeing memory previously allocated.  */
2787
2788 OTF *
2789 OTF_open (const char *otf_name)
2790 {
2791   FILE *fp;
2792   char *errfmt = "opening otf (%s)";
2793   void *errret = NULL;
2794   OTF *otf;
2795   OTF_InternalData *internal_data;
2796   int len = strlen (otf_name);
2797   const char *ext = otf_name + (len - 4);
2798
2799   if (len < 4
2800       || ext[0] != '.'
2801       || (ext[1] != 'O' && ext[1] != 'T' && ext[1] != 'o' && ext[1] != 't')
2802       || (ext[2] != 'T' && ext[2] != 't')
2803       || (ext[3] != 'F' && ext[3] != 'f'))
2804     OTF_ERROR (OTF_ERROR_FILE, otf_name);
2805   fp = fopen (otf_name, "r");
2806   if (! fp)
2807     OTF_ERROR (OTF_ERROR_FILE, otf_name);
2808   otf = calloc (1, sizeof (OTF));
2809   if (! otf)
2810     OTF_ERROR (OTF_ERROR_MEMORY, "body allocation");
2811   otf->filename = strdup (otf_name);
2812   if (! otf->filename)
2813     {
2814       OTF_close (otf);
2815       fclose (fp);
2816       OTF_ERROR (OTF_ERROR_MEMORY, "filename allocation");
2817     }
2818
2819   internal_data = calloc (1, sizeof (OTF_InternalData));
2820   if (! internal_data)
2821     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData");
2822   otf->internal_data = internal_data;
2823   if (! allocate_memory_record (otf))
2824     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData)");
2825
2826   /* Here after, all pointers to allocated memory are recorded in
2827      otf->internal_data->memory_record except for what allocated by
2828      the functions allocate_memory_record and make_stream.  */
2829
2830   if (read_header_part (otf, fp, NULL) < 0)
2831     {
2832       OTF_close (otf);
2833       fclose (fp);
2834       return NULL;
2835     }
2836
2837   fclose (fp);
2838   return otf;
2839 }
2840
2841 OTF *
2842 OTF_open_ft_face (FT_Face face)
2843 {
2844   char *errfmt = "opening otf from Freetype (%s)";
2845   void *errret = NULL;
2846   OTF *otf;
2847   OTF_InternalData *internal_data;
2848
2849   if (! FT_IS_SFNT (face))
2850     OTF_ERROR (OTF_ERROR_FILE, (char *) face->family_name);
2851   otf = calloc (1, sizeof (OTF));
2852   if (! otf)
2853     OTF_ERROR (OTF_ERROR_MEMORY, "body allocation");
2854   otf->filename = NULL;
2855   
2856   internal_data = calloc (1, sizeof (OTF_InternalData));
2857   if (! internal_data)
2858     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData");
2859   otf->internal_data = internal_data;
2860   if (! allocate_memory_record (otf))
2861     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData)");
2862
2863   if (read_header_part (otf, NULL, face) < 0)
2864     {
2865       OTF_close (otf);
2866       return NULL;
2867     }
2868
2869   return otf;
2870 }
2871
2872 /*** (2-2) OTF_close() */
2873
2874 void
2875 OTF_close (OTF *otf)
2876 {
2877   OTF_InternalData *internal_data = otf->internal_data;
2878   int i;
2879
2880   if (internal_data)
2881     {
2882       OTF_MemoryRecord *memrec = internal_data->memory_record;
2883
2884       if (internal_data->header_stream)
2885         free_stream (internal_data->header_stream);
2886
2887       for (i = 0; i < OTF_TABLE_TYPE_MAX; i++)
2888         if (internal_data->table_info[i].stream)
2889           free_stream (internal_data->table_info[i].stream);
2890
2891       while (memrec)
2892         {
2893           OTF_MemoryRecord *next = memrec->next;
2894
2895           for (i = memrec->used - 1; i >= 0; i--)
2896             free (memrec->memory[i]);
2897           free (memrec);
2898           memrec = next;
2899         }
2900       free (internal_data);
2901     }
2902   if (otf->filename)
2903     free (otf->filename);
2904   free (otf);
2905 }
2906
2907 /*** (2-3) OTF_get_table() */
2908
2909 int
2910 OTF_get_table (OTF *otf, const char *name)
2911 {
2912   OTF_TableInfo *table_info = get_table_info (otf, name);
2913   void *address;
2914
2915   if (! table_info)
2916     return -1;
2917   if (! table_info->stream)
2918     /* Already fully loaded.  */
2919     return 0;
2920
2921   address = (*table_info->reader) (otf, table_info, OTF_READ_FULL);
2922   free_stream (table_info->stream);
2923   table_info->stream = NULL;
2924   if (! address)
2925     {
2926       table_info->reader = NULL;
2927       return -1;
2928     }
2929   return 0;
2930 }
2931
2932 /*** (2-4) OTF_check_table() */
2933
2934 int
2935 OTF_check_table (OTF *otf, const char *name)
2936 {
2937   return (get_table_info (otf, name) ? 0 : -1);
2938 }
2939
2940 /*** (2-5) OTF_get_scripts()  */
2941
2942 int
2943 OTF_get_scripts (OTF *otf, int gsubp)
2944 {
2945   OTF_TableInfo *table_info
2946     = (otf->internal_data->table_info
2947        + (gsubp ? OTF_TABLE_TYPE_GSUB : OTF_TABLE_TYPE_GPOS));
2948   void *address;
2949
2950   if (! table_info->reader)
2951     return -1;
2952   if (! table_info->stream)
2953     /* Already fully loaded.  */
2954     return 0;
2955
2956   address = (*table_info->reader) (otf, table_info, OTF_READ_SCRIPTS);
2957   if (! address)
2958     {
2959       table_info->reader = NULL;
2960       return -1;
2961     }
2962   return 0;
2963 }
2964
2965 /*** (2-6) OTF_get_features()  */
2966
2967 int
2968 OTF_get_features (OTF *otf, int gsubp)
2969 {
2970   OTF_TableInfo *table_info
2971     = (otf->internal_data->table_info
2972        + (gsubp ? OTF_TABLE_TYPE_GSUB : OTF_TABLE_TYPE_GPOS));
2973   void *address;
2974
2975   if (! table_info->reader)
2976     return -1;
2977   if (! table_info->stream)
2978     {
2979       if (*table_info->address)
2980         /* Already fully loaded.  */
2981         return 0;
2982       return -1;
2983     }
2984
2985   address = (*table_info->reader) (otf, table_info, OTF_READ_FEATURES);
2986   if (! address)
2987     {
2988       table_info->reader = NULL;
2989       return -1;
2990     }
2991   return 0;
2992 }
2993
2994 /*** (2-7) OTF_check_features  */
2995
2996 int
2997 OTF_check_features (OTF *otf, int gsubp,
2998                     OTF_Tag script, OTF_Tag language, const OTF_Tag *features,
2999                     int n_features)
3000 {
3001   OTF_ScriptList *script_list;
3002   OTF_Script *Script = NULL;
3003   OTF_LangSys *LangSys = NULL;
3004   OTF_FeatureList *feature_list;
3005   int i, j;
3006
3007   if (OTF_get_features (otf, gsubp) < 0)
3008     {
3009       for (i = 0; i < n_features; i++)
3010         {
3011           OTF_Tag feature = features[i];
3012
3013           if (feature == 0)
3014             continue;
3015           if ((((unsigned) feature) & 0x80000000) == 0)
3016             return -1;
3017         }
3018       return 1;
3019     }
3020   if (gsubp)
3021     {
3022       script_list = &otf->gsub->ScriptList;
3023       feature_list = &otf->gsub->FeatureList;
3024     }
3025   else
3026     {
3027       script_list = &otf->gpos->ScriptList;
3028       feature_list = &otf->gpos->FeatureList;
3029     }
3030   for (i = 0; i < script_list->ScriptCount && ! Script; i++)
3031     if (script_list->Script[i].ScriptTag == script)
3032       Script = script_list->Script + i;
3033   if (! Script)
3034     return 0;
3035   if (language)
3036     {
3037       for (i = 0; i < Script->LangSysCount && ! LangSys; i++)
3038         if (Script->LangSysRecord[i].LangSysTag == language)
3039           LangSys = Script->LangSys + i;
3040     }
3041   if (! LangSys)
3042     LangSys = &Script->DefaultLangSys;
3043   for (j = 0; j < n_features; j++)
3044     {
3045       OTF_Tag feature = features[j];
3046       int negate = 0;
3047
3048       if (feature == 0)
3049         continue;
3050       if (((unsigned) feature) & 0x80000000)
3051         {
3052           feature = (OTF_Tag) (((unsigned) feature) & 0x7FFFFFFF);
3053           negate = 1;
3054         }
3055       for (i = 0; i < LangSys->FeatureCount; i++)
3056         if (feature_list->Feature[LangSys->FeatureIndex[i]].FeatureTag
3057             == feature)
3058           {
3059             if (negate)
3060               return 0;
3061             break;
3062           }
3063       if (i == LangSys->FeatureCount)
3064         return 0;
3065     }
3066   return 1;
3067 }
3068
3069 \f
3070 /*** (5) API miscellaneous ***/
3071
3072 OTF_Tag
3073 OTF_tag (const char *name)
3074 {
3075   const unsigned char *p = (unsigned char *) name;
3076
3077   if (! name)
3078     return (OTF_Tag) 0;
3079   return (OTF_Tag) ((p[0] << 24)
3080                     | (! p[1] ? 0
3081                        : ((p[1] << 16)
3082                           | (! p[2] ? 0
3083                              : (p[2] << 8) | p[3]))));
3084 }
3085
3086 void
3087 OTF_tag_name (OTF_Tag tag, char *name)
3088 {
3089   name[0] = (char) (tag >> 24);
3090   name[1] = (char) ((tag >> 16) & 0xFF);
3091   name[2] = (char) ((tag >> 8) & 0xFF);
3092   name[3] = (char) (tag & 0xFF);
3093   name[4] = '\0';
3094 }