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