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