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