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