Debian Codegraph @

podofo/3rdparty/adobe/afdko/source/t1read/t1read.c

raw
1 /* Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved.
2 This software is licensed as OpenSource, under the Apache License, Version 2.0.
3 This license is available at: http://opensource.org/licenses/Apache-2.0. */
4
5 /*
6 * PostScript font file parser.
7 *
8 * Handles single master, multiple master, synthetic, and CID fonts.
9 *
10 * Print stream formats for name-keyed and cid-keyed fonts are also supported.
11 * These are generated by xcf and/or CoolType when downloading a font to a
12 * printer. Generally, these will need to be extracted from the print stream
13 * before submitting them to this library. It may also be necessary to fix up
14 * some constructs that don't follow the guidelines specified in the "Adobe
15 * Type Manager Compatibility" chapter in the Black Book.
16 */
17
18 #include "t1read.h"
19 #include "t1cstr.h"
20 #include "dynarr.h"
21 #include "pstoken.h"
22 #include "ctutil.h"
23 #include "txops.h"
24 #include "supportexcept.h"
25
26 #include <string.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <ctype.h>
31 #include <math.h>
32
33 #define RND(v) ((float)floor((v) + 0.5))
34
35 /* ----------------------- PostScript Dictionary Keys ---------------------- */
36
37 /* Note: t1read_keys.h must be ascii sorted by key name */
38
39 enum /* Key enumeration */
40 {
41 #define DCL_KEY(key, index) index,
42 #include "t1read_keys.h"
43 #undef DCL_KEY
44 kKeyCount
45 };
46
47 static const char *keys[] =
48 {
49 #define DCL_KEY(key, index) key,
50 #include "t1read_keys.h"
51 #undef DCL_KEY
52 };
53
54 #define MAX_AXES 4 /* Practical multiple master axis limit */
55
56 typedef unsigned short STI; /* String index */
57 #define STI_UNDEF 0xffff /* Undefined string index */
58 #define STI_LIMIT 65000
59 #define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0]))
60
61 typedef struct /* Map glyph name to its standard encoding */
62 {
63 unsigned char code;
64 char *gname;
65 } StdMap;
66
67 typedef abfGlyphInfo Char; /* Character record */
68 typedef unsigned short CHI; /* Char record index */
69 typedef long Offset;
70
71 typedef struct /* FDArray element */
72 {
73 abfFontDict *fdict; /* Font dict */
74 struct /* Subrs */
75 {
76 ctlRegion region; /* cstr data region */
77 dnaDCL(long, offset);
78 } subrs;
79 t1cAuxData aux; /* Auxiliary charstring data */
80 struct /* Dict key info */
81 {
82 long lenIV; /* Length random cipher bytes */
83 long SubrMapOffset; /* CID-specific key */
84 unsigned short SubrCount; /* CID-specific key */
85 unsigned short SDBytes; /* CID-specific key */
86 unsigned short BlueValues; /* Flags /BlueValues seen */
87 } key;
88 t1cDecryptFunc decrypt; /* Charstring decryption function */
89 } FDInfo;
90
91 typedef struct /* Length delimited string for search match */
92 {
93 long length;
94 char *value;
95 } MatchStr;
96
97 /* Module context */
98 struct t1rCtx_ {
99 long flags; /* Control flags */
100 #define MM_FONT (1UL << 31) /* MM font */
101 #define CID_FONT (1UL << 30) /* CID-keyed font */
102 #define SYN_FONT (1UL << 29) /* Synthetic font */
103 #define SEEN_END (1UL << 28) /* Seen CharStrings dict end operator */
104 #define STD_ENC (1UL << 27) /* Standard encoded font */
105 #define FREE_ENCODINGS (1UL << 26) /* Return encoding nodes to free list */
106 #define PRINT_STREAM (1UL << 25) /* CoolType print steam font */
107 #define CRLF_NEWLINES (1UL << 24) /* Font uses CR/LF newlines */
108 #define SEEN_NOTDEF (1UL << 23) /* Seen .notdef glyph */
109 abfTopDict top; /* Top dict */
110 FDInfo *fd; /* Active FDArray element */
111 dnaDCL(FDInfo, FDArray); /* FDArray */
112 dnaDCL(abfFontDict, fdicts); /* Font Dicts */
113 struct /* Encoding */
114 {
115 STI custom[256]; /* Custom encoding */
116 unsigned short standard[256]; /* Map standard encoding to tag */
117 } encoding;
118 struct /* Chars */
119 {
120 dnaDCL(Char, index); /* In parse order */
121 dnaDCL(long, byName); /* In glyph name order */
122 } chars;
123 struct /* String pool */
124 {
125 dnaDCL(long, index); /* In index order; [SRI]->iBuf */
126 dnaDCL(char, buf); /* String buffer */
127 } strings;
128 struct /* Dict key info */
129 {
130 char seen[kKeyCount]; /* Flags keys seen */
131 long CIDMapOffset; /* CID-specific key */
132 unsigned FDBytes; /* CID-specific key */
133 unsigned GDBytes; /* CID-specific key */
134 } key;
135 dnaDCL(char, tmp); /* Temporary char buffer */
136 pstToken token; /* Last PostScript token read from stream */
137 struct /* Synthetic font values */
138 {
139 abfString FontName;
140 abfString FullName;
141 float ItalicAngle;
142 long UniqueID;
143 abfFontMatrix FontMatrix;
144 } synthetic;
145 struct /* MM font values */
146 {
147 struct
148 {
149 long cnt;
150 float array[T1_MAX_MASTERS];
151 } WV;
152 struct
153 {
154 long cnt;
155 float array[T1_MAX_MASTERS * T1_MAX_AXES];
156 } BDP;
157 struct
158 {
159 long cnt;
160 float array[T1_MAX_AXES * T1_MAX_AXIS_MAPS];
161 } BDM;
162 float *UDV; /* From client */
163 float ForceBoldThreshold;
164 } mm;
165 pstCtx pst; /* pstoken lib context */
166 dnaCtx dna; /* dynarr lib context */
167 struct /* Client callbacks */
168 {
169 ctlMemoryCallbacks mem;
170 ctlStreamCallbacks stm;
171 } cb;
172 struct /* Streams */
173 {
174 void *tmp; /* Temporary */
175 void *dbg; /* Debug */
176 void *src; /* Source (CID-keyed only) */
177 } stm;
178 long tmpoff; /* Temporary stream offset */
179 struct /* Source stream data (CID-keyed only) */
180 {
181 long offset; /* Buffer offset */
182 char *buf; /* Buffer data */
183 size_t length; /* Buffer length */
184 char *end; /* Buffer end */
185 char *next; /* Next byte available */
186 } src;
187 abfEncoding *encfree; /* Encoding node free list */
188 struct /* Error handling */
189 {
190 _Exc_Buf env;
191 } err;
192 };
193
194 static void parseGlyphDirectory(t1rCtx h);
195
196 /* ----------------------------- Error Handling ---------------------------- */
197
198 /* Write message to debug stream from va_list. */
199 static void vmessage(t1rCtx h, char *fmt, va_list ap) {
200 char text[500];
201
202 if (h->stm.dbg == NULL)
203 return; /* Debug stream not available */
204
205 VSPRINTF_S(text, 500, fmt, ap);
206 (void)h->cb.stm.write(&h->cb.stm, h->stm.dbg, strlen(text), text);
207 }
208
209 /* Write message to debug stream from varargs. */
210 static void CTL_CDECL message(t1rCtx h, char *fmt, ...) {
211 va_list ap;
212 va_start(ap, fmt);
213 vmessage(h, fmt, ap);
214 va_end(ap);
215 }
216
217 /* Handle fatal error. */
218 static void CTL_CDECL fatal(t1rCtx h, int err_code, char *fmt, ...) {
219 if (fmt == NULL)
220 /* Write standard error message */
221 message(h, "%s", t1rErrStr(err_code));
222 else {
223 /* Write font-specific error message */
224 va_list ap;
225 va_start(ap, fmt);
226 vmessage(h, fmt, ap);
227 va_end(ap);
228 }
229 RAISE(&h->err.env, err_code, NULL);
230 }
231
232 /* --------------------------- Memory Management --------------------------- */
233
234 /* Allocate memory. */
235 static void *memNew(t1rCtx h, size_t size) {
236 void *ptr = h->cb.mem.manage(&h->cb.mem, NULL, size);
237 if (ptr == NULL)
238 fatal(h, t1rErrNoMemory, NULL);
239 return ptr;
240 }
241
242 /* Free memory. */
243 static void memFree(t1rCtx h, void *ptr) {
244 (void)h->cb.mem.manage(&h->cb.mem, ptr, 0);
245 }
246
247 /* -------------------------- Safe dynarr Callbacks ------------------------ */
248
249 /* Manage memory. */
250 static void *dna_manage(ctlMemoryCallbacks *cb, void *old, size_t size) {
251 t1rCtx h = cb->ctx;
252 void *ptr = h->cb.mem.manage(&h->cb.mem, old, size);
253 if (size > 0 && ptr == NULL)
254 fatal(h, t1rErrNoMemory, NULL);
255 return ptr;
256 }
257
258 /* Initialize error handling dynarr context. */
259 static void dna_init(t1rCtx h) {
260 ctlMemoryCallbacks cb;
261 cb.ctx = h;
262 cb.manage = dna_manage;
263 h->dna = dnaNew(&cb, DNA_CHECK_ARGS);
264 }
265
266 /* ----------------------- Temporary File Management ----------------------- */
267
268 /* Reset tmp stream to beginning. */
269 static void tmpSeek(t1rCtx h, long offset) {
270 if (h->cb.stm.seek(&h->cb.stm, h->stm.tmp, offset))
271 fatal(h, t1rErrTmpStream, NULL);
272 h->tmpoff = offset;
273 }
274
275 /* Write buffer to tmp steam and update offset. */
276 static void tmpWrite(t1rCtx h, long length, char *buf) {
277 if (h->cb.stm.write(&h->cb.stm, h->stm.tmp, length, buf) != (size_t)length)
278 fatal(h, t1rErrTmpStream, NULL);
279 h->tmpoff += length;
280 }
281
282 /* Initialize tmp stream with invalid cstr that is used to initialize bad or
283 missing subrs. Charstring parse fails if subr is referenced. The bad
284 charstring is located at offset 1 so that offset 0 can never become a
285 charstring offset. This restriction maintains compatibility with the buildch
286 library where a 0 charstring offset means uninitialized. */
287 static void tmpInit(t1rCtx h) {
288 char badcstr[] = {0}; /* Invalid charstring containing invalid op */
289 tmpSeek(h, 1);
290 tmpWrite(h, sizeof(badcstr), badcstr);
291 }
292
293 /* --------------------------- String Management --------------------------- */
294
295 /* Initialize strings. */
296 static void newStrings(t1rCtx h) {
297 dnaINIT(h->dna, h->strings.index, 50, 200);
298 dnaINIT(h->dna, h->strings.buf, 1500, 6000);
299 }
300
301 /* Reinitialize strings for new font. */
302 static void initStrings(t1rCtx h) {
303 h->strings.index.cnt = 0;
304 h->strings.buf.cnt = 0;
305 }
306
307 /* Free strings. */
308 static void freeStrings(t1rCtx h) {
309 dnaFREE(h->strings.index);
310 dnaFREE(h->strings.buf);
311 }
312
313 /* Add string. */
314 /* 64-bit warning fixed by type change here HO */
315 /* static STI addString(t1rCtx h, unsigned length, const char *value) */
316 static STI addString(t1rCtx h, size_t length, const char *value) {
317 STI sti = (STI)h->strings.index.cnt;
318
319 if (length == 0) {
320 /* A null name (/) is legal in PostScript but could lead to unexpected
321 behavior elsewhere in the coretype libraries so it is substituted
322 for a name that is very likely to be unique in the font */
323 static const char subs_name[] = "_null_name_substitute_";
324 value = subs_name;
325 length = sizeof(subs_name) - 1;
326 message(h, "null charstring name");
327 }
328
329 /* Add new string index */
330 *dnaNEXT(h->strings.index) = h->strings.buf.cnt;
331
332 /* Add null-terminated string to buffer */
333 /* 64-bit warning fixed by cast here HO */
334 memcpy(dnaEXTEND(h->strings.buf, (long)(length + 1)), value, length);
335 h->strings.buf.array[h->strings.buf.cnt - 1] = '\0';
336
337 return sti;
338 }
339
340 /* Get string from STI. */
341 static char *getString(t1rCtx h, STI sti) {
342 if ((sti != STI_UNDEF) && (sti >= STI_LIMIT))
343 fatal(h, t1rErrSTILimit, "String INDEX limit exceeded: [%hu]", sti);
344 else if ((sti == STI_UNDEF) || (sti >= h->strings.index.cnt))
345 fatal(h, t1rErrSTIUndef, "String undefined for index: [%hu]", sti);
346 else
347 return &h->strings.buf.array[h->strings.index.array[sti]];
348
349 return NULL;
350 }
351
352 /* ---------------------------- Chars Management --------------------------- */
353
354 /* Initialize chars. */
355 static void newChars(t1rCtx h) {
356 dnaINIT(h->dna, h->chars.index, 256, 1000);
357 dnaINIT(h->dna, h->chars.byName, 256, 1000);
358 }
359
360 /* Reinitialize chars for new font. */
361 static void initChars(t1rCtx h) {
362 h->chars.index.cnt = 0;
363 h->chars.byName.cnt = 0;
364 }
365
366 /* Free chars. */
367 static void freeChars(t1rCtx h) {
368 dnaFREE(h->chars.index);
369 dnaFREE(h->chars.byName);
370 }
371
372 /* Match glyph name. */
373 static int CTL_CDECL matchChar(const void *key, const void *value, void *ctx) {
374 t1rCtx h = ctx;
375 return strcmp((char *)key, getString(h, (STI)h->chars.index.array
376 [*(long *)value]
377 .gname.impl));
378 }
379
380 /* Add char record. Return 1 if record exists else 0. Char record returned by
381 "chr" parameter. */
382 static int addChar(t1rCtx h, STI sti, Char **chr) {
383 size_t index;
384 int found =
385 ctuLookup(getString(h, sti),
386 h->chars.byName.array, h->chars.byName.cnt,
387 sizeof(h->chars.byName.array[0]), matchChar, &index, h);
388
389 if (found)
390 /* Match found; return existing record */
391 *chr = &h->chars.index.array[h->chars.byName.array[index]];
392 else {
393 /* Not found; add to table and return new record */
394 long *new = &dnaGROW(h->chars.byName, h->chars.byName.cnt)[index];
395
396 /* Make and fill hole */
397 memmove(new + 1, new, (h->chars.byName.cnt++ - index) * sizeof(h->chars.byName.array[0]));
398 *new = h->chars.index.cnt;
399
400 *chr = dnaNEXT(h->chars.index);
401 }
402
403 return found;
404 }
405
406 /* Find char by name. NULL if not found else char record. */
407 static Char *findChar(t1rCtx h, STI sti) {
408 size_t index;
409 if (ctuLookup(getString(h, sti),
410 h->chars.byName.array, h->chars.byName.cnt,
411 sizeof(h->chars.byName.array[0]), matchChar, &index, h))
412 return &h->chars.index.array[h->chars.byName.array[index]];
413 else
414 return NULL;
415 }
416
417 /* ---------------------------- Encoding Support --------------------------- */
418
419 /* Add encoding to char. */
420 static void encAdd(t1rCtx h, Char *chr, unsigned long code) {
421 abfEncoding *enc = &chr->encoding;
422 if (strcmp(chr->gname.ptr, ".notdef") == 0)
423 return; /* Don't encode .notdef */
424 else if (enc->code == ABF_GLYPH_UNENC) {
425 /* First encoding; initialize */
426 enc->code = code;
427 enc->next = NULL;
428 } else {
429 /* Second or subsequent encoding; link new encoding */
430 abfEncoding *new = h->encfree;
431 if (new == NULL)
432 /* Get node from heap */
433 new = memNew(h, sizeof(abfEncoding));
434 else
435 /* Remove head node from free list */
436 h->encfree = new->next;
437
438 new->code = code;
439 new->next = enc->next;
440 enc->next = new;
441 h->flags |= FREE_ENCODINGS;
442 }
443 }
444
445 /* Put encoding node list on free list. */
446 static void encReuse(t1rCtx h, abfEncoding *node) {
447 if (node == NULL)
448 return;
449 encReuse(h, node->next);
450 node->next = h->encfree;
451 h->encfree = node;
452 }
453
454 /* Reuse encoding node list. */
455 static void encListReuse(t1rCtx h) {
456 long i;
457
458 if (!(h->flags & FREE_ENCODINGS))
459 return; /* Font has no multiple encodings */
460
461 /* Put multiple encodings back on free list */
462 for (i = 0; i < h->chars.index.cnt; i++) {
463 abfEncoding *enc = &h->chars.index.array[i].encoding;
464 if (enc->code != ABF_GLYPH_UNENC)
465 encReuse(h, enc->next);
466 }
467 h->flags &= ~FREE_ENCODINGS;
468 }
469
470 /* Free encoding node list. */
471 static void encListFree(t1rCtx h, abfEncoding *node) {
472 if (node == NULL)
473 return;
474 encListFree(h, node->next);
475 memFree(h, node);
476 }
477
478 /* --------------------------- Context Management -------------------------- */
479
480 /* Initialize FDArray element when allocated. */
481 static void allocFDInfo(void *ctx, long cnt, FDInfo *fd) {
482 t1rCtx h = ctx;
483 while (cnt--) {
484 dnaINIT(h->dna, fd->subrs.offset, 300, 300);
485 fd++;
486 }
487 }
488
489 /* Validate client and create context. */
490 t1rCtx t1rNew(ctlMemoryCallbacks *mem_cb, ctlStreamCallbacks *stm_cb,
491 CTL_CHECK_ARGS_DCL) {
492 t1rCtx h;
493
494 /* Check client/library compatibility */
495 if (CTL_CHECK_ARGS_TEST(T1R_VERSION))
496 return NULL;
497
498 /* Allocate context */
499 h = mem_cb->manage(mem_cb, NULL, sizeof(struct t1rCtx_));
500 if (h == NULL)
501 return NULL;
502
503 /* explicitly zero out entire structure */
504 memset(h, 0, sizeof(struct t1rCtx_));
505
506 /* Safety initialization */
507 h->FDArray.size = 0;
508 h->fdicts.size = 0;
509 h->chars.index.size = 0;
510 h->chars.byName.size = 0;
511 h->strings.index.size = 0;
512 h->strings.buf.size = 0;
513 h->tmp.size = 0;
514 h->pst = NULL;
515 h->dna = NULL;
516 h->stm.tmp = NULL;
517 h->stm.dbg = NULL;
518 h->stm.src = NULL;
519 h->encfree = NULL;
520
521 /* Copy callbacks */
522 h->cb.mem = *mem_cb;
523 h->cb.stm = *stm_cb;
524
525 /* Set error handler */
526 DURING_EX(h->err.env)
527
528 /* Initialize service library */
529 dna_init(h);
530
531 dnaINIT(h->dna, h->FDArray, 1, 20);
532 h->FDArray.func = allocFDInfo;
533 dnaINIT(h->dna, h->fdicts, 1, 20);
534 newChars(h);
535 newStrings(h);
536 dnaINIT(h->dna, h->tmp, 250, 750);
537
538 /* Initialize pstoken library */
539 h->pst = pstNew(mem_cb, stm_cb, T1R_SRC_STREAM_ID, PST_CHECK_ARGS);
540 if (h->pst == NULL)
541 RAISE(&h->err.env, t1rErrSrcStream, NULL);
542
543 /* Open tmp stream */
544 h->stm.tmp = h->cb.stm.open(&h->cb.stm, T1R_TMP_STREAM_ID, 0);
545 if (h->stm.tmp == NULL)
546 RAISE(&h->err.env, t1rErrTmpStream, NULL);
547
548 /* Open debug stream */
549 h->stm.dbg = h->cb.stm.open(&h->cb.stm, T1R_DBG_STREAM_ID, 0);
550
551 HANDLER
552
553 /* Initialization failed */
554 t1rFree(h);
555 h = NULL;
556
557 END_HANDLER
558
559 return h;
560 }
561
562 /* Free context. */
563 void t1rFree(t1rCtx h) {
564 int i;
565
566 if (h == NULL)
567 return;
568
569 for (i = 0; i < h->FDArray.size; i++)
570 dnaFREE(h->FDArray.array[i].subrs.offset);
571
572 dnaFREE(h->FDArray);
573 dnaFREE(h->fdicts);
574 freeChars(h);
575 freeStrings(h);
576 dnaFREE(h->tmp);
577
578 dnaFree(h->dna);
579 pstFree(h->pst);
580
581 /* Close tmp stream */
582 if (h->stm.tmp != NULL)
583 (void)h->cb.stm.close(&h->cb.stm, h->stm.tmp);
584
585 /* Close debug stream */
586 if (h->stm.dbg != NULL)
587 (void)h->cb.stm.close(&h->cb.stm, h->stm.dbg);
588
589 encListFree(h, h->encfree);
590
591 /* Free library context */
592 memFree(h, h);
593 }
594
595 /* --------------------------- Dictionary Parsing -------------------------- */
596
597 /* Handle fatal parse error. */
598 static void pstFatal(t1rCtx h, int err_code) {
599 message(h, "(pst) %s", pstErrStr(err_code));
600 fatal(h, t1rErrPostScript, NULL);
601 }
602
603 /* Get next PostScript token and store in context. Return token pointer. */
604 static pstToken *getToken(t1rCtx h) {
605 int result = pstGetToken(h->pst, &h->token);
606 if (result)
607 pstFatal(h, result);
608 return &h->token;
609 }
610
611 /* Find PostScript token. */
612 static void findToken(t1rCtx h, char *value) {
613 int result = pstFindToken(h->pst, &h->token, value);
614 if (result)
615 pstFatal(h, result);
616 }
617
618 /* Read encoding array. Just save the reference to encoded glyph names */
619 static void readEncoding(t1rCtx h) {
620 int i;
621 pstToken *token = getToken(h);
622
623 if (pstMatch(h->pst, token, "StandardEncoding")) {
624 /* Standard encoded font */
625 h->flags |= STD_ENC;
626 return;
627 }
628
629 /* Initialize encoding array */
630 for (i = 0; i < 256; i++)
631 h->encoding.custom[i] = STI_UNDEF;
632
633 /* Search for first entry */
634 for (;;) {
635 if (pstMatch(h->pst, token, "dup")) {
636 int code;
637 STI gname;
638
639 /* Parse encoding value */
640 token = getToken(h);
641 if (token->type != pstInteger) {
642 message(h, "Invalid token in encoding vector (integer expected)");
643 continue;
644 }
645
646 code = pstConvInteger(h->pst, token);
647 if (code < 0 || code > 255) {
648 message(h, "Invalid codepoint in encoding vector %d", code);
649 continue;
650 }
651
652 /* Parse glyph name */
653 token = getToken(h);
654 if (token->type != pstLiteral) {
655 message(h, "Invalid token in encoding vector (literal expected)");
656 continue;
657 }
658
659 gname = addString(h, token->length - 1, token->value + 1);
660
661 /* Check for put operator */
662 token = getToken(h);
663 if (!pstMatch(h->pst, token, "put")) {
664 message(h, "put operator expected in encoding vector");
665 continue;
666 }
667
668 /* Save encoding */
669 h->encoding.custom[code] = gname;
670
671 } else if (pstMatch(h->pst, token, "def") ||
672 pstMatch(h->pst, token, "readonly"))
673 return; /* Success */
674
675 token = getToken(h);
676 }
677 }
678
679 /* Compute hex string length taking newlines into account. */
680 static long calcHexLen(t1rCtx h, long len) {
681 long nl_cnt;
682 long nl_len = (h->flags & CRLF_NEWLINES) ? 2 : 1;
683
684 /* Compute number of newline chars in string */
685 if (h->fd->key.lenIV == -1)
686 nl_cnt = (len - 1) / 32;
687 else
688 nl_cnt = (len - h->fd->key.lenIV - 1) / 32;
689
690 return len * 2 + nl_cnt * nl_len;
691 }
692
693 /* Convert incremental download ASCIIHex charstring to binary. Returns number
694 of converted binary bytes or 0 on error. */
695 static long convASCIIHexCstr(t1rCtx h, long length, char *value) {
696 long i;
697 char *p = value;
698 char *end = value + length;
699 for (i = 0;; i++) {
700 int hi = -1; /* Hi-order nibble */
701 for (;;) {
702 int nib;
703 int c;
704 retry:
705 if (p == end) {
706 if (hi != -1)
707 value[i++] = hi; /* Partial byte, low nibble 0 */
708 return i;
709 }
710 c = *p++;
711 switch (c) {
712 case '0':
713 case '1':
714 case '2':
715 case '3':
716 case '4':
717 case '5':
718 case '6':
719 case '7':
720 case '8':
721 case '9':
722 nib = c - '0';
723 break;
724 case 'A':
725 case 'B':
726 case 'C':
727 case 'D':
728 case 'E':
729 case 'F':
730 nib = c - 'A' + 10;
731 break;
732 case 'a':
733 case 'b':
734 case 'c':
735 case 'd':
736 case 'e':
737 case 'f':
738 nib = c - 'a' + 10;
739 break;
740 case '\0':
741 case ' ':
742 case '\t':
743 case '\r':
744 case '\n':
745 goto retry; /* Skip white space */
746 default:
747 return 1;
748 }
749 if (hi == -1)
750 hi = nib << 4;
751 else {
752 value[i] = hi | nib;
753 break;
754 }
755 }
756 }
757 }
758
759 /* Convert incremental download ASCII85 charstring to binary. Normally 5 bytes
760 of ASCII-85 are decoded into 4 binary bytes. Thus, the result can be written
761 directly to the charstring. However, the character 'z' is special and
762 EXPANDS to 4 zero bytes which could overflow the charstring. Therefore, I
763 consider character 'z' to be invalid because the only thing in a Type 1
764 charstring it could represent would be a 5-byte representation of zero which
765 seems very unlikely. Also, the t1write library never generates uses 'z' in
766 an ASCII-85 charstring.
767
768 Returns number of converted binary bytes or 0 on error. */
769 static long convASCII85Cstr(t1rCtx h, char *value) {
770 int i;
771 char *p = value;
772 char *q = value;
773 int n = 0;
774 unsigned long tuple = 0;
775
776 for (p = value;; p++)
777 switch (*p) {
778 case '~':
779 /* End of string */
780 goto finish;
781 case '\0':
782 case ' ':
783 case '\t':
784 case '\r':
785 case '\n':
786 break; /* Skip whitespace */
787 case 'z':
788 return 0; /* Impossible charstring */
789 default:
790 tuple = tuple * 85 + *p - '!';
791 if (++n == 5) {
792 /* Write 4-tuple */
793 for (i = 3; i >= 0; i--) {
794 q[i] = (char)tuple;
795 tuple >>= 8;
796 }
797 q += 4;
798 n = 0;
799 }
800 break;
801 }
802
803 finish:
804 if (n == 1)
805 return 0; /* Invalid ASCII85 */
806 else if (n > 1) {
807 /* Partial 5-tuple; pad missing zeros */
808 for (i = n; i < 5; i++)
809 tuple = tuple * 85 + 84;
810
811 /* Discard unused bytes */
812 for (i = n; i < 5; i++)
813 tuple >>= 8;
814
815 /* Write partial 4-tuple */
816 for (i = n - 2; i >= 0; i--) {
817 q[i] = (char)tuple;
818 tuple >>= 8;
819 }
820 q += n - 1;
821 }
822
823 /* 64-bit warning fixed by cast here HO */
824 return (long)(q - value);
825 }
826
827 /* Save charstring to tmp file and return tmp file offset. */
828 static long saveSubr(t1rCtx h, long length, char *value, int iFD, long num) {
829 long offset = h->tmpoff;
830 FDInfo *fd = &h->FDArray.array[iFD];
831
832 if (fd->key.lenIV != -1 &&
833 t1cDecrypt(fd->key.lenIV, &length, value, value)) {
834 if (iFD != 0)
835 fatal(h, t1rErrCstrDecrypt,
836 "can't decrypt FD[%d].subr[%ld]", iFD, num);
837 else
838 fatal(h, t1rErrCstrDecrypt, "can't decrypt subr[%ld]", num);
839 }
840
841 /* Validate charstring */
842 switch ((length >= 1) ? value[length - 1] : 0) {
843 case tx_endchar:
844 case tx_callsubr:
845 case tx_return:
846 break;
847 case 6:
848 /* Second byte of possible seac operator */
849 if (length >= 2 && value[length - 2] == tx_escape)
850 break;
851 default:
852 if (iFD != 0)
853 message(h,
854 "unterminated charstring FD[%d].subr[%ld] (invalidating)",
855 iFD, num);
856 else
857 message(h,
858 "unterminated charstring subr[%ld] (invalidating)", num);
859
860 /* The subr is invalid but if it's never referenced by a charstring
861 we can still successfully parse the font. So, we set the subr to
862 reference the invalid charstring we inserted at the beginning of
863 the tmp file. If this is ever interpreted later the charstring
864 parser will fail with "invalid operator". */
865 return 1;
866 }
867
868 /* Save charstring to tmp file */
869 tmpWrite(h, length, value);
870
871 return offset;
872 }
873
874 /* Read charstring token sequence. Return 0 on error else charstring length. */
875 static long readCstrTokenSeq(t1rCtx h, char **cstr) {
876 int result;
877 long length;
878 pstToken *token;
879
880 /* Read initial token */
881 token = getToken(h);
882 switch (token->type) {
883 case pstHexString:
884 /* ASCIIHex string; one of the print stream formats */
885 *cstr = token->value;
886 return convASCIIHexCstr(h, token->length - 2, *cstr + 1);
887 case pstASCII85:
888 /* ASCII85 string; one of the print stream formats */
889 *cstr = token->value + 1;
890 return convASCII85Cstr(h, *cstr + 1);
891 case pstInteger:
892 break;
893 default:
894 return 0; /* Unexpected token type */
895 }
896
897 /* Convert charstring length */
898 length = pstConvInteger(h->pst, token);
899 if (length < 1 || length > 65535)
900 return 0;
901
902 /* Parse RD operator */
903 token = getToken(h);
904 if (token->type != pstOperator)
905 return 0;
906
907 if (h->flags & PRINT_STREAM) {
908 long hexlen = calcHexLen(h, length);
909 result = pstRead(h->pst, hexlen + 1, cstr);
910 if (result)
911 pstFatal(h, result);
912 if (convASCIIHexCstr(h, hexlen, *cstr + 1) != length)
913 return 0;
914 } else {
915 /* Read separator and charstring bytes */
916 result = pstRead(h->pst, length + 1, cstr);
917 if (result)
918 pstFatal(h, result);
919 }
920
921 return length;
922 }
923
924 /* Read /Subrs array. */
925 static void readSubrs(t1rCtx h) {
926 int i;
927 pstToken *token;
928 long num = 0; /* Suppress optimizer warning */
929 long cnt = 0; /* Suppress optimizer warning */
930
931 /* Parse subrs count */
932 token = getToken(h);
933 if (token->type != pstInteger)
934 fatal(h, t1rErrSubrsCount, NULL);
935
936 cnt = pstConvInteger(h->pst, token);
937 if (cnt < 0 || cnt > 65535)
938 fatal(h, t1rErrSubrsCount, NULL);
939
940 /* Allocate and initialize elements */
941 dnaSET_CNT(h->fd->subrs.offset, cnt);
942 for (i = 0; i < cnt; i++)
943 /* Set tmp file offset of invalid charstring */
944 h->fd->subrs.offset.array[i] = 0;
945
946 /* Save start of region */
947 h->fd->subrs.region.begin = h->tmpoff;
948
949 findToken(h, "array");
950 for (i = 0;; i++) {
951 long length;
952 char *cstr;
953
954 /* Read dup token */
955 token = getToken(h);
956 if (!pstMatch(h->pst, token, "dup")) {
957 /* Save end of region */
958 h->fd->subrs.region.end = h->tmpoff;
959
960 if (i > cnt)
961 message(h, "duplicate subrs");
962 else if (i < cnt)
963 message(h, "sparse /Subr array (invalidating unset entries)");
964
965 return;
966 }
967
968 /* Parse subr number */
969 token = getToken(h);
970 if (token->type != pstInteger)
971 break;
972
973 num = pstConvInteger(h->pst, token);
974 if (num < 0 || num >= h->fd->subrs.offset.cnt)
975 break;
976
977 /* Read cstr bytes */
978 length = readCstrTokenSeq(h, &cstr);
979 if (length == 0)
980 break;
981
982 /* Save charstring data omitting separator byte */
983 h->fd->subrs.offset.array[num] = saveSubr(h, length, cstr + 1, 0, num);
984
985 /* Parse NP operator */
986 token = getToken(h);
987 if (token->type != pstOperator)
988 break;
989
990 /* Check for "noaccess put" sequence */
991 if (pstMatch(h->pst, token, "noaccess")) {
992 token = getToken(h);
993 if (token->type != pstOperator)
994 break;
995 }
996 }
997
998 fatal(h, t1rErrSubrEntry, "invalid subr entry [%ld]", num);
999 }
1000
1001 /* Match std name. */
1002 static int CTL_CDECL matchStd(const void *key, const void *value) {
1003 return strcmp((char *)key, ((StdMap *)value)->gname);
1004 }
1005
1006 /* Get standard encoding from glyph name. Return -1 if no standard encoding
1007 else code. */
1008 static int getStdEnc(t1rCtx h, STI gname) {
1009 static const StdMap stdenc[] =
1010 {
1011 #include "stdenc3.h"
1012 };
1013 StdMap *map = (StdMap *)
1014 bsearch(getString(h, gname), stdenc, ARRAY_LEN(stdenc),
1015 sizeof(stdenc[0]), matchStd);
1016 return (map == NULL) ? -1 : map->code;
1017 }
1018
1019 /* Save glyph charstring to tmp file. */
1020 static void saveCstr(t1rCtx h, long length, char *value, Char *chr, int update) {
1021 FDInfo *fd = &h->FDArray.array[chr->iFD];
1022
1023 if (fd->key.lenIV != -1 &&
1024 fd->decrypt(fd->key.lenIV, &length, value, value)) {
1025 if (h->flags & CID_FONT)
1026 fatal(h, t1rErrCstrDecrypt, "can't decrypt CID-%d", chr->cid);
1027 else
1028 fatal(h, t1rErrCstrDecrypt, "can't decrypt <%s>",
1029 getString(h, (STI)chr->gname.impl));
1030 }
1031
1032 /* Validate charstring */
1033 switch ((length >= 1) ? value[length - 1] : 0) {
1034 case tx_endchar:
1035 case tx_callsubr:
1036 break;
1037 case 6:
1038 /* Second byte of possible seac operator */
1039 if (length >= 2 && value[length - 2] == tx_escape)
1040 break;
1041 default:
1042 if (h->flags & CID_FONT)
1043 fatal(h, t1rErrUntermCstr, "unterminated charstring CID-%d",
1044 chr->cid);
1045 else
1046 fatal(h, t1rErrUntermCstr, "unterminated charstring <%s>",
1047 getString(h, (STI)chr->gname.impl));
1048 }
1049
1050 /* Save charstring to tmp file */
1051 if (update) {
1052 chr->sup.begin = h->tmpoff;
1053 chr->sup.end = chr->sup.begin + length;
1054 }
1055 tmpWrite(h, length, value);
1056 }
1057
1058 /* Add missing .notdef character to font. The inserted charstring has a width
1059 of 250 units and no path. It could be argued that the charstring should be a
1060 copy of the space character's charstring or that the width be scaled
1061 appropriately for fonts with a non-standard design space but this makes the
1062 code unnecessarily complicated for handling what is, after all, a broken
1063 font. */
1064 static void addNotdef(t1rCtx h, unsigned short tag) {
1065 static const unsigned char cstr[] =
1066 {0x8b, 0xf7, 0x8e, 0xd, 0xe}; /* 0 250 hsbw endchar */
1067 Char *chr;
1068 STI gname;
1069 long save;
1070 FDInfo *fd = &h->FDArray.array[0];
1071
1072 /* Add new char */
1073 gname = addString(h, 7, ".notdef");
1074 (void)addChar(h, gname, &chr);
1075
1076 /* Initialize char */
1077 abfInitGlyphInfo(chr);
1078 chr->tag = tag;
1079 chr->gname.impl = gname;
1080
1081 /* Save plaintext charstring data */
1082 save = fd->key.lenIV;
1083 fd->key.lenIV = -1;
1084 saveCstr(h, sizeof(cstr), (char *)cstr, chr, 1);
1085 fd->key.lenIV = save;
1086
1087 message(h, "missing .notdef glyph (inserted)");
1088 }
1089
1090 /* Read CharStrings dictionary */
1091 static void readChars(t1rCtx h) {
1092 STI gname; /* Glyph name */
1093 unsigned short tag; /* Charstring tag */
1094 int LanguageGroup1 = h->fdicts.array[0].Private.LanguageGroup == 1;
1095
1096 findToken(h, "begin");
1097 tag = 0;
1098 for (;;) {
1099 Char *chr;
1100 pstToken *token;
1101 char *cstr;
1102 long length;
1103
1104 /* Parse glyph name */
1105 token = getToken(h);
1106 if (pstMatch(h->pst, token, "end")) {
1107 /* Reached end of CharStrings dict */
1108 if (!(h->flags & SEEN_NOTDEF))
1109 addNotdef(h, tag);
1110
1111 h->flags |= SEEN_END;
1112 return;
1113 } else if (token->type != pstLiteral)
1114 fatal(h, t1rErrCharName, NULL);
1115
1116 /* Trim leading / from glyph name literal */
1117 token->length--;
1118 token->value++;
1119
1120 if (token->length == 7 && strncmp(token->value, ".notdef", 7) == 0)
1121 h->flags |= SEEN_NOTDEF; /* Remember .notdef glyph */
1122
1123 /* Save glyph name string */
1124 gname = addString(h, token->length, token->value);
1125 if (addChar(h, gname, &chr)) {
1126 message(h, "duplicate charstring <%s> (discarded)",
1127 getString(h, gname));
1128 gname = STI_UNDEF;
1129 }
1130
1131 /* Read cstr bytes */
1132 length = readCstrTokenSeq(h, &cstr);
1133 if (length == 0)
1134 break;
1135
1136 if (gname != STI_UNDEF) {
1137 int code = getStdEnc(h, gname);
1138 if (code != -1)
1139 h->encoding.standard[code] = tag;
1140
1141 /* Initialize char */
1142 abfInitGlyphInfo(chr);
1143 chr->tag = tag++;
1144 chr->gname.impl = gname;
1145 if (LanguageGroup1)
1146 chr->flags |= ABF_GLYPH_LANG_1;
1147
1148 /* Save charstring */
1149 saveCstr(h, length, cstr + 1, chr, 1);
1150 }
1151
1152 /* Parse NP operator */
1153 token = getToken(h);
1154 if (token->type != pstOperator)
1155 break;
1156 }
1157
1158 fatal(h, t1rErrCharEntry,
1159 "invalid character entry <%s>", getString(h, gname));
1160 }
1161
1162 /* Init FD element. */
1163 static void initFDInfo(t1rCtx h, int iFD) {
1164 FDInfo *fd = &h->FDArray.array[iFD];
1165 abfFontDict *fdict = &h->fdicts.array[iFD];
1166 abfInitFontDict(fdict);
1167 fd->fdict = fdict;
1168 fd->key.lenIV = 4;
1169 fd->key.SubrMapOffset = -1;
1170 fd->key.SubrCount = 0;
1171 fd->key.SDBytes = 0;
1172 fd->key.BlueValues = 0;
1173 fd->decrypt = t1cDecrypt;
1174 }
1175
1176 /* ---------------------------- Multiple Master ---------------------------- */
1177
1178 /* Validate BlendDesignMap array. Return 1 if valid else 0. */
1179 static int validBDM(t1rCtx h, int nAxes, int nMasters) {
1180 int i;
1181 int j;
1182 float *BDM = h->mm.BDM.array;
1183
1184 i = 0;
1185 for (j = 0; j < nAxes; j++) {
1186 float U0;
1187 float N0;
1188
1189 if (i >= h->mm.BDM.cnt - 1)
1190 return 0;
1191 U0 = BDM[i++];
1192 N0 = BDM[i++];
1193
1194 if (N0 != 0.0)
1195 return 0;
1196
1197 for (;;) {
1198 float U1;
1199 float N1;
1200
1201 if (i >= h->mm.BDM.cnt - 1)
1202 return 0;
1203 U1 = BDM[i++];
1204 N1 = BDM[i++];
1205
1206 if (U0 >= U1 || N0 >= N1)
1207 return 0;
1208 else if (N1 == 1.0)
1209 break;
1210
1211 U0 = U1;
1212 N0 = N1;
1213 }
1214 }
1215
1216 return i == h->mm.BDM.cnt;
1217 }
1218
1219 /* Normalize user coordinate within range. */
1220 static int normRange(float *u, float *n, int cnt, const float *ranges) {
1221 int i;
1222
1223 /* Clamp to range */
1224 if (*u < ranges[0])
1225 *u = ranges[0];
1226 else if (*u > ranges[cnt - 1])
1227 *u = ranges[cnt - 1];
1228
1229 /* Find range */
1230 for (i = 0; i < cnt - 1; i++)
1231 if (*u < ranges[i + 1])
1232 break;
1233
1234 /* Interpolate range */
1235 *n = (*u - ranges[i]) / (ranges[i + 1] - ranges[i]);
1236
1237 return i;
1238 }
1239
1240 /* Perform bilinear interpolation of coordinate. */
1241 static float interpolate(float n, float op, float a, float b, float c, float d) {
1242 return a + n * (b - a) + op * (d - a) + n * op * (a - b + c - d);
1243 }
1244
1245 /* Piecewise normalize user coordinate. */
1246 static float normalize(float *u, const float *pieces) {
1247 float u0 = pieces[0];
1248 float n0 = pieces[1];
1249 int i = 2;
1250 if (*u < u0) {
1251 *u = u0;
1252 return 0.0; /* Clamp low value */
1253 }
1254 for (;;) {
1255 float u1 = pieces[i++];
1256 float n1 = pieces[i++];
1257 if (*u <= u1)
1258 return n0 + (n1 - n0) * (*u - u0) / (u1 - u0);
1259 else if (n1 == 1.0) {
1260 *u = u1;
1261 return 1.0; /* Clamp high value */
1262 }
1263 u0 = u1;
1264 n0 = n1;
1265 }
1266 }
1267
1268 /* Custom convert UDV to NDV for Kepler. */
1269 static void keplerNDV(t1rCtx h) {
1270 static const float wt_ranges[] = {275, 385, 775};
1271 static const float wd_ranges[] = {350, 450, 575, 850};
1272 static const float op_ranges[] = {5, 7, 10, 18, 72};
1273 static const float wt_tab[][ARRAY_LEN(wt_ranges)] =
1274 {
1275 {0.00f, 0.18f, 1.00f}, /* 5 point */
1276 {0.00f, 0.18f, 1.00f}, /* 7 point */
1277 {0.00f, 0.22f, 1.00f}, /* 10 point */
1278 {0.00f, 0.22f, 1.00f}, /* 18 point */
1279 {0.00f, 0.22f, 1.00f}, /* 72 point */
1280 };
1281 static const float wd_tab[][ARRAY_LEN(wd_ranges)] =
1282 {
1283 {0.00f, 0.20f, 0.41f, 1.00f}, /* 5 point */
1284 {0.00f, 0.20f, 0.41f, 1.00f}, /* 7 point */
1285 {0.00f, 0.20f, 0.45f, 1.00f}, /* 10 point */
1286 {0.00f, 0.17f, 0.50f, 1.00f}, /* 18 point */
1287 {0.00f, 0.00f, 0.58f, 1.00f}, /* 72 point */
1288 };
1289 static const float op_pieces[] =
1290 {
1291 5, 0.00f,
1292 6, 0.15f,
1293 7, 0.24f,
1294 8, 0.30f,
1295 10, 0.44f,
1296 13, 0.50f,
1297 18, 0.80f,
1298 72, 1.00f,
1299 };
1300 float wt;
1301 float wd;
1302 float op;
1303 float *UDV = h->fd->aux.UDV;
1304 float *NDV = h->fd->aux.NDV;
1305 int iwt = normRange(&UDV[0], &wt, ARRAY_LEN(wt_ranges), wt_ranges);
1306 int iwd = normRange(&UDV[1], &wd, ARRAY_LEN(wd_ranges), wd_ranges);
1307 int iop = normRange(&UDV[2], &op, ARRAY_LEN(op_ranges), op_ranges);
1308
1309 NDV[0] = interpolate(wt, op,
1310 wt_tab[iop + 0][iwt + 0],
1311 wt_tab[iop + 0][iwt + 1],
1312 wt_tab[iop + 1][iwt + 1],
1313 wt_tab[iop + 1][iwt + 0]);
1314 NDV[1] = interpolate(wd, op,
1315 wd_tab[iop + 0][iwd + 0],
1316 wd_tab[iop + 0][iwd + 1],
1317 wd_tab[iop + 1][iwd + 1],
1318 wd_tab[iop + 1][iwd + 0]);
1319 NDV[2] = normalize(&UDV[2], op_pieces);
1320 }
1321
1322 /* Custom convert NDV to WV for Jenson. */
1323 static void jensonCDV(t1rCtx h) {
1324 float wt = h->fd->aux.NDV[0];
1325 float op = h->fd->aux.NDV[1] * 2;
1326 float *WV = h->fd->aux.WV;
1327 if (op <= 1.0) {
1328 WV[0] = (1 - wt) * (1 - op);
1329 WV[1] = wt * (1 - op);
1330 WV[2] = (1 - wt) * op;
1331 WV[3] = wt * op;
1332 WV[4] = 0;
1333 WV[5] = 0;
1334 } else {
1335 WV[0] = 0;
1336 WV[1] = 0;
1337 WV[2] = (1 - wt) * (2 - op);
1338 WV[3] = wt * (2 - op);
1339 WV[4] = (1 - wt) * (op - 1);
1340 WV[5] = wt * (op - 1);
1341 }
1342 }
1343
1344 /* Match FontName. */
1345 static int CTL_CDECL matchFontName(const void *key, const void *value) {
1346 return strcmp((char *)key, *(char **)value);
1347 }
1348
1349 /* Convert UDV to NDV for standard MM font. */
1350 static void stdNDV(t1rCtx h, int nAxes) {
1351 int i;
1352 int j;
1353
1354 i = 0;
1355 for (j = 0;; j += 2) {
1356 h->fd->aux.NDV[i] = normalize(&h->fd->aux.UDV[i], &h->mm.BDM.array[j]);
1357
1358 if (++i == nAxes)
1359 break;
1360
1361 /* Find end of axis */
1362 for (;;) {
1363 j += 2;
1364 if (h->mm.BDM.array[j + 1] == 1.0)
1365 break;
1366 }
1367 }
1368 }
1369
1370 /* Convert NDV to WV for standard MM font. */
1371 static void stdCDV(t1rCtx h, int nAxes, int nMasters) {
1372 int i;
1373 int j;
1374 int k;
1375 char order[T1_MAX_MASTERS];
1376 char check[T1_MAX_MASTERS];
1377 float *NDV = h->fd->aux.NDV;
1378 float *WV = h->fd->aux.WV;
1379
1380 /* Create master design ordering */
1381 k = 0;
1382 for (i = 0; i < nMasters; i++) {
1383 order[i] = 0;
1384 for (j = 0; j < nAxes; j++) {
1385 double d = h->mm.BDP.array[k++];
1386 long n = (long)d;
1387
1388 if (n != d || (n != 0 && n != 1))
1389 /* Non-integer master coordinates must have CDV support */
1390 fatal(h, t1rErrGeometry, NULL);
1391
1392 /* Each master's position is computed by considering its axis
1393 coordinates as a binary number with first axis as lsb. */
1394 order[i] |= n << j;
1395 }
1396 }
1397
1398 /* Check every master represented */
1399 memset(check, 0, nMasters);
1400 for (i = 0; i < nMasters; i++)
1401 check[(int)order[i]] = 1;
1402 for (i = 0; i < nMasters; i++)
1403 if (!check[i])
1404 fatal(h, t1rErrGeometry, NULL);
1405
1406 /* Check nMasters for power of 2 */
1407 if (nMasters != "\002\004\010\020"[nAxes - 1])
1408 fatal(h, t1rErrGeometry, NULL);
1409
1410 /* Compute Weight Vector */
1411 for (i = 0; i < nMasters; i++) {
1412 WV[i] = 1;
1413 for (j = 0; j < nAxes; j++)
1414 WV[i] *= (order[i] & 1 << j) ? NDV[j] : 1 - NDV[j];
1415 }
1416 }
1417
1418 /* Calculate UDV for default instance (specified by WeightVector). */
1419 static void calcUDVFromWV(t1rCtx h, int nAxes, int nMasters) {
1420 int i;
1421 int j;
1422 float *BDM = h->mm.BDM.array;
1423
1424 i = 0;
1425 for (j = 0; j < nAxes; j++) {
1426 int k;
1427 int l = j;
1428 float U0;
1429 float N0;
1430 float norm = 0; /* Per-axis normalized coord accumulator */
1431
1432 /* Add normalized coord contribution for each master */
1433 for (k = 0; k < nMasters; k++) {
1434 norm += h->mm.BDP.array[l] * h->fd->aux.WV[k];
1435 l += nAxes;
1436 }
1437
1438 /* Find matching axis map and interpolate */
1439 U0 = BDM[i++];
1440 N0 = BDM[i++];
1441 for (;;) {
1442 float U1 = BDM[i++];
1443 float N1 = BDM[i++];
1444
1445 if (N0 <= norm && norm <= N1)
1446 h->fd->aux.UDV[j] =
1447 RND(((U1 - U0) * (norm - N0) / (N1 - N0) + U0));
1448
1449 if (N1 == 1.0)
1450 break; /* End of axis */
1451
1452 U0 = U1;
1453 N0 = N1;
1454 }
1455 }
1456 }
1457
1458 /* Initialize MM font. */
1459 static void mmInit(t1rCtx h) {
1460 static char *jenson[] =
1461 {
1462 "AJensonMM",
1463 "AJensonMM-Alt",
1464 "AJensonMM-Ep",
1465 "AJensonMM-It",
1466 "AJensonMM-ItAlt",
1467 "AJensonMM-ItEp",
1468 "AJensonMM-ItSC",
1469 "AJensonMM-SC",
1470 "AJensonMM-Sw",
1471 };
1472 static char *kepler[] =
1473 {
1474 "KeplMM",
1475 "KeplMM-Ep",
1476 "KeplMM-It",
1477 "KeplMM-ItEp",
1478 "KeplMM-ItSC",
1479 "KeplMM-SC",
1480 "KeplMM-Sw",
1481 };
1482 int nMasters;
1483 int nAxes;
1484 char *FontName = getString(h, (STI)h->fd->fdict->FontName.impl);
1485 if (FontName == NULL)
1486 fatal(h, t1rErrFontName, NULL);
1487 int isJenson = bsearch(FontName, jenson, ARRAY_LEN(jenson),
1488 sizeof(jenson[0]), matchFontName) != NULL;
1489 int isKepler = bsearch(FontName, kepler, ARRAY_LEN(kepler),
1490 sizeof(kepler[0]), matchFontName) != NULL;
1491
1492 if (h->flags & MM_FONT)
1493 return; /* Already done */
1494
1495 h->flags |= MM_FONT;
1496
1497 /* Check for required keys */
1498 if (!h->key.seen[kBlendDesignPositions])
1499 fatal(h, t1rErrBDP, NULL);
1500 if (!h->key.seen[kBlendDesignMap])
1501 fatal(h, t1rErrBDM, NULL);
1502 if (!h->key.seen[kWeightVector])
1503 fatal(h, t1rErrWV, NULL);
1504
1505 /* Compute and check design geometry */
1506 nMasters = h->mm.WV.cnt;
1507 nAxes = h->mm.BDP.cnt / nMasters;
1508 if (nAxes > T1_MAX_AXES || (long)nAxes * nMasters != h->mm.BDP.cnt ||
1509 !validBDM(h, nAxes, nMasters))
1510 fatal(h, t1rErrGeometry, NULL);
1511
1512 /* Copy WV */
1513 h->fd->aux.nMasters = nMasters;
1514 memcpy(h->fd->aux.WV, h->mm.WV.array, nMasters * sizeof(h->mm.WV.array[0]));
1515
1516 if (h->mm.UDV == NULL) {
1517 /* Not specified by client; use default */
1518 if (isKepler) {
1519 h->fd->aux.UDV[0] = 385;
1520 h->fd->aux.UDV[1] = 575;
1521 h->fd->aux.UDV[2] = 10;
1522 } else
1523 calcUDVFromWV(h, nAxes, nMasters);
1524 return;
1525 }
1526
1527 /* Copy UDV */
1528 memcpy(h->fd->aux.UDV, h->mm.UDV, nAxes * sizeof(h->mm.UDV[0]));
1529
1530 /* Compute NDV */
1531 if (isKepler)
1532 keplerNDV(h);
1533 else
1534 stdNDV(h, nAxes);
1535
1536 /* Compute WV */
1537 if (isJenson)
1538 jensonCDV(h);
1539 else
1540 stdCDV(h, nAxes, nMasters);
1541 }
1542
1543 /* Fix up multiple master snapshot. */
1544 static void prepMMData(t1rCtx h) {
1545 unsigned int i;
1546 size_t lenCoords;
1547 size_t lenFontName;
1548 char buf[64];
1549 char coords[64];
1550 char *p;
1551 char *pFontName = getString(h, (STI)h->fd->fdict->FontName.impl);
1552 char FontName[128];
1553 unsigned int nAxes;
1554 char *Weight = "SnapShotMM";
1555
1556 if (pFontName == NULL)
1557 fatal(h, t1rErrMMParse, "missing FontName");
1558
1559 /* copy FontName because call to addString() below may make pointer stale */
1560 strncpy(FontName, pFontName, 128);
1561 FontName[127] = 0;
1562
1563 if (h->fd->aux.nMasters == 0)
1564 fatal(h, t1rErrMMParse, "invalid number of masters");
1565
1566 nAxes = h->mm.BDP.cnt / h->fd->aux.nMasters;
1567
1568 if (h->top.ItalicAngle == 0) {
1569 /* BuildFont incorrectly specifies the ItalicAngle for MM oblique
1570 fonts as 0. This code checks for this condition and fixes the
1571 fonts known to have this problem. */
1572 static const struct
1573 {
1574 char *FontName;
1575 float ItalicAngle;
1576 } bad_fonts[] =
1577 {
1578 {"ITCAvantGardeMM-Oblique", -10.5},
1579 {"TektonMM-Oblique", -10.0},
1580 };
1581 for (i = 0; i < ARRAY_LEN(bad_fonts); i++)
1582 if (strcmp(FontName, bad_fonts[i].FontName) == 0) {
1583 h->top.ItalicAngle = bad_fonts[i].ItalicAngle;
1584 break;
1585 }
1586 }
1587
1588 /* Set new Weight string */
1589 h->top.Weight.impl = addString(h, strlen(Weight), Weight);
1590
1591 /* Delete FullName, FamilyName, UniqueID */
1592 h->top.FullName.impl = ABF_UNSET_INT;
1593 h->top.FamilyName.impl = ABF_UNSET_INT;
1594 h->top.UniqueID = ABF_UNSET_INT;
1595
1596 /* Construct instance FontName rounding coords to nearest int */
1597 coords[0] = '_';
1598 p = &coords[1];
1599 for (i = 0; i < nAxes; i++) {
1600 sprintf(p, "%d_", (int)RND(h->fd->aux.UDV[i]));
1601 p += strlen(p);
1602 }
1603 lenFontName = strlen(FontName);
1604 lenCoords = strlen(coords);
1605 if (lenCoords + lenFontName + 1 > sizeof(buf))
1606 sprintf(buf, "%.*s%s",
1607 (int)(sizeof(buf) - (lenCoords + 1)), FontName, coords);
1608 else
1609 sprintf(buf, "%s%s", FontName, coords);
1610 h->fd->fdict->FontName.impl = addString(h, strlen(buf), buf);
1611
1612 if (h->top.XUID.cnt == ABF_EMPTY_ARRAY)
1613 message(h, "no XUID in MM font");
1614 else {
1615 /* Append instance UDV to XUID */
1616 int iBase = h->top.XUID.cnt;
1617
1618 if (iBase + nAxes > ARRAY_LEN(h->top.XUID.array))
1619 iBase = ARRAY_LEN(h->top.XUID.array) - nAxes;
1620
1621 for (i = 0; i < nAxes; i++)
1622 h->top.XUID.array[iBase + i] = (long)h->fd->aux.UDV[i];
1623 h->top.XUID.cnt += nAxes;
1624 }
1625 }
1626
1627 /* ---------------------------- Literal Parsing ---------------------------- */
1628
1629 /* Report bad dict value */
1630 static void badKeyValue(t1rCtx h, int iKey) {
1631 if (h->FDArray.cnt > 1)
1632 fatal(h, t1rErrKeyValue, "/%s bad value: FD[%ld]",
1633 keys[iKey], h->fd - h->FDArray.array);
1634 else
1635 fatal(h, t1rErrKeyValue, "/%s bad value", keys[iKey]);
1636 }
1637
1638 /* Parse string value, add to string pool, and return its index. */
1639 static STI parseString(t1rCtx h, int kKey) {
1640 pstToken *token = getToken(h);
1641 if (token->type != pstString)
1642 badKeyValue(h, kKey);
1643 return addString(h, token->length - 2, token->value + 1);
1644 }
1645
1646 /* Parse name value, add to string pool, and return its index. */
1647 static STI parseName(t1rCtx h, int kKey) {
1648 pstToken *token = getToken(h);
1649 switch (token->type) {
1650 case pstString:
1651 return addString(h, token->length - 2, token->value + 1);
1652 case pstLiteral:
1653 return addString(h, token->length - 1, token->value + 1);
1654 default:
1655 badKeyValue(h, kKey);
1656 }
1657 return 0; /* Suppress compiler warning */
1658 }
1659
1660 /* Parse blend array and blend elements. */
1661 static double parseBlend(t1rCtx h, int kKey, char **str) {
1662 double value;
1663 int i;
1664 char *p = *str;
1665 char delim = (*p++ == '[') ? ']' : '}';
1666
1667 if (!(h->flags & MM_FONT))
1668 badKeyValue(h, kKey);
1669
1670 /* Skip initial whitespace */
1671 while (isspace(*p))
1672 p++;
1673
1674 /* Parse blend array */
1675 value = 0;
1676 for (i = 0; i < h->fd->aux.nMasters; i++) {
1677 char *q;
1678
1679 /* Parse and blend number */
1680 value += h->fd->aux.WV[i] * (double)ctuStrtod(p, &q);
1681 if (p == q)
1682 badKeyValue(h, kKey); /* Invalid number */
1683 p = q;
1684
1685 /* Skip trailing whitespace */
1686 while (isspace(*p))
1687 p++;
1688 }
1689
1690 if (*p != delim)
1691 badKeyValue(h, kKey);
1692
1693 *str = p;
1694 return value;
1695 }
1696
1697 /* Make temporary null-terminated copy to ensure strtod/l termination. */
1698 static char *copyArrayToken(t1rCtx h, pstToken *token) {
1699 dnaSET_CNT(h->tmp, token->length + 1);
1700 memcpy(h->tmp.array, token->value, token->length);
1701 h->tmp.array[token->length] = '\0';
1702 return h->tmp.array;
1703 }
1704
1705 /* Parse blendable integer value and return it. */
1706 static long parseInt(t1rCtx h, int kKey) {
1707 pstToken *token = getToken(h);
1708 char *p = token->value;
1709 switch (token->type) {
1710 case pstInteger:
1711 return pstConvInteger(h->pst, token);
1712 case pstArray:
1713 case pstProcedure:
1714 p = copyArrayToken(h, token);
1715 return (long)RND(parseBlend(h, kKey, &p));
1716 default:
1717 badKeyValue(h, kKey);
1718 }
1719 return 0; /* Suppress compiler warning */
1720 }
1721
1722 /* Parse blendable integer or real value and return it. */
1723 static float parseNum(t1rCtx h, int kKey, int round) {
1724 pstToken *token = getToken(h);
1725 switch (token->type) {
1726 case pstInteger:
1727 return (float)pstConvInteger(h->pst, token);
1728 case pstReal:
1729 return (float)pstConvReal(h->pst, token);
1730 case pstArray:
1731 case pstProcedure: {
1732 char *p = copyArrayToken(h, token);
1733 double value = parseBlend(h, kKey, &p);
1734 return round ? RND(value) : value;
1735 }
1736 default:
1737 badKeyValue(h, kKey);
1738 }
1739 return 0; /* Suppress compiler warning */
1740 }
1741
1742 /* Parse and save number array. */
1743 static int parseNumArray(t1rCtx h, int kKey,
1744 int min, int max, float *array,
1745 int blend, int report_empty) {
1746 int i;
1747 char *p;
1748 pstToken *token = getToken(h);
1749
1750 if (token->type != pstArray && token->type != pstProcedure)
1751 badKeyValue(h, kKey); /* Expecting array object */
1752
1753 i = 0;
1754 p = copyArrayToken(h, token) + 1;
1755 for (;;)
1756 switch (*p) {
1757 case '\0':
1758 goto finish;
1759 case '\t':
1760 case '\n':
1761 case '\f':
1762 case '\r':
1763 case ' ':
1764 case ']':
1765 case '}':
1766 p++;
1767 break;
1768 case '[':
1769 case '{':
1770 if (blend) {
1771 if (i < max) {
1772 double value = parseBlend(h, kKey, &p);
1773 if (kKey == kFontBBox) {
1774 array[i] =
1775 (double)((i < 2) ? floor(value) : ceil(value));
1776 i++;
1777 } else
1778 array[i++] = value;
1779 } else {
1780 message(h, "/%s array too big (truncated)", keys[kKey]);
1781 return max;
1782 }
1783 }
1784 p++;
1785 break;
1786 case 'd':
1787 if (p[1] == 'i' && p[2] == 'v' && i > 1 && array[i - 1] != 0) {
1788 /* Try to support div operator; unwisely used by drivers */
1789 array[i - 2] /= array[i - 1];
1790 i--;
1791 p += 3;
1792 } else
1793 badKeyValue(h, kKey);
1794 break;
1795 default:
1796 if (i < max) {
1797 char *q;
1798 array[i++] = (float)ctuStrtod(p, &q);
1799 if (p == q)
1800 badKeyValue(h, kKey); /* Invalid number */
1801 p = q;
1802 } else {
1803 message(h, "/%s array too big (truncated)", keys[kKey]);
1804 return max;
1805 }
1806 break;
1807 }
1808
1809 finish:
1810 if (i < min)
1811 badKeyValue(h, kKey);
1812 if (report_empty && i == 0)
1813 message(h, "/%s array empty (discarded)", keys[kKey]);
1814 return i;
1815 }
1816
1817 /* Parse and save integer array. */
1818 static int parseIntArray(t1rCtx h, int kKey, int min, int max, long *array) {
1819 int i;
1820 char *p;
1821 pstToken *token = getToken(h);
1822
1823 if (token->type != pstArray && token->type != pstProcedure)
1824 badKeyValue(h, kKey); /* Expecting array object */
1825
1826 i = 0;
1827 p = copyArrayToken(h, token) + 1;
1828 for (;;)
1829 switch (*p) {
1830 case '\0':
1831 goto finish;
1832 case '\t':
1833 case '\n':
1834 case '\f':
1835 case 'r':
1836 case ' ':
1837 case ']':
1838 p++;
1839 break;
1840 default:
1841 if (i < max) {
1842 char *q;
1843 array[i++] = strtol(p, &q, 0);
1844 if (p == q)
1845 badKeyValue(h, kKey); /* Invalid number */
1846 p = q;
1847 } else {
1848 message(h, "/%s array too big (truncated)", keys[kKey]);
1849 return max;
1850 }
1851 break;
1852 }
1853
1854 finish:
1855 if (i < min)
1856 badKeyValue(h, kKey);
1857 return i;
1858 }
1859
1860 /* Parse boolean value and return 0 if false and 1 if true. */
1861 static long parseBool(t1rCtx h, int kKey) {
1862 long boole = 0; /* Suppress optimizer warning */
1863 pstToken *token = getToken(h);
1864 switch (token->type) {
1865 case pstOperator:
1866 if (pstMatch(h->pst, token, "false"))
1867 boole = 0;
1868 else if (pstMatch(h->pst, token, "true"))
1869 boole = 1;
1870 else
1871 badKeyValue(h, kKey);
1872 break;
1873 case pstArray: {
1874 int i = 0;
1875 char *p = token->value + 1;
1876 float value = 0;
1877
1878 /* Skip initial whitespace */
1879 while (isspace(*p))
1880 p++;
1881
1882 /* Parse blend array */
1883 for (i = 0; i < h->fd->aux.nMasters; i++) {
1884 if (strncmp(p, "false", 5) == 0)
1885 p += 5;
1886 else if (strncmp(p, "true", 4) == 0) {
1887 value += h->fd->aux.WV[i];
1888 p += 4;
1889 } else
1890 badKeyValue(h, kKey); /* Invalid boolean */
1891
1892 /* Skip trailing whitespace */
1893 while (isspace(*p))
1894 p++;
1895 }
1896
1897 if (*p != ']')
1898 badKeyValue(h, kKey);
1899
1900 if (kKey == kForceBold)
1901 boole = value >= h->mm.ForceBoldThreshold;
1902 else
1903 boole = value >= 0.5;
1904 } break;
1905 default:
1906 badKeyValue(h, kKey);
1907 }
1908 return boole;
1909 }
1910
1911 /* Parse font matrix. Return 1 if Top dict FontMatrix else 0. */
1912 static int parseFontMatrix(t1rCtx h, abfTopDict *top, abfFontDict *font) {
1913 float array[6];
1914
1915 memset(array, 0, 6 * sizeof(float));
1916
1917 /* Parse matrix */
1918 (void)parseNumArray(h, kFontMatrix, 6, 6, array, 0, 0);
1919
1920 if (h->flags & CID_FONT && !h->key.seen[kFDArray]) {
1921 /* Top-level CIDFont matrix */
1922 if (array[0] != 1.0 ||
1923 array[1] != 0.0 ||
1924 array[2] != 0.0 ||
1925 array[3] != 1.0 ||
1926 array[4] != 0.0 ||
1927 array[5] != 0.0) {
1928 /* Save matrix if not identity */
1929 memcpy(top->cid.FontMatrix.array, array, sizeof(array));
1930 top->cid.FontMatrix.cnt = 6;
1931 }
1932 return 1;
1933 } else {
1934 /* Font dict matrix */
1935 float *result = font->FontMatrix.array;
1936
1937 if (top->cid.FontMatrix.cnt != ABF_EMPTY_ARRAY) {
1938 /* Form product of top and FDArray matrices */
1939 float *a = top->cid.FontMatrix.array;
1940 float *b = array;
1941
1942 result[0] = a[0] * b[0] + a[1] * b[2];
1943 result[1] = a[0] * b[1] + a[1] * b[3];
1944 result[2] = a[2] * b[0] + a[3] * b[2];
1945 result[3] = a[2] * b[1] + a[3] * b[3];
1946 result[4] = a[4] * b[0] + a[5] * b[2] + b[4];
1947 result[5] = a[4] * b[1] + a[5] * b[3] + b[5];
1948 } else
1949 /* Copy matrix */
1950 memcpy(result, array, sizeof(array));
1951
1952 if (result[0] != 0.001f ||
1953 result[1] != 0.0 ||
1954 result[2] != 0.0 ||
1955 result[3] != 0.001f ||
1956 result[4] != 0.0 ||
1957 result[5] != 0.0) {
1958 /* Non-default matrix */
1959 float max;
1960 int i;
1961
1962 /* Make matrix available */
1963 font->FontMatrix.cnt = 6;
1964
1965 /* Find the largest of a, b, c, and d */
1966 max = 0.0;
1967 for (i = 0; i < 4; i++) {
1968 float value = result[i];
1969 if (value < 0.0)
1970 value = -value;
1971 if (value > max)
1972 max = value;
1973 }
1974 if (max == 0.0)
1975 fatal(h, t1rErrFontMatrix, NULL);
1976
1977 /* Calculate units-per-em */
1978 top->sup.UnitsPerEm = (unsigned short)(1.0 / max + 0.5);
1979 }
1980 }
1981 return 0;
1982 }
1983
1984 /* Check RD type to see if this is an incremental download font. */
1985 static void checkRDType(t1rCtx h) {
1986 pstToken *token = getToken(h);
1987 if (token->type == pstProcedure) {
1988 dnaSET_CNT(h->tmp, token->length + 1);
1989 memcpy(h->tmp.array, token->value, token->length);
1990 h->tmp.array[token->length] = '\0';
1991 if (strstr(h->tmp.array, "readhexstring") != NULL)
1992 h->flags |= PRINT_STREAM;
1993 }
1994 }
1995
1996 /* Parse Erode proc. If we are parsing a print stream font we look for a
1997 carriage return in the proc. definition as a clue to the line ending type
1998 being used in the stream. If we haven't already seen the /StdVW key we
1999 derive its value from the 16th token in the proc. */
2000 static void parseErodeProc(t1rCtx h, abfPrivateDict *private) {
2001 int i;
2002 pstToken *token = getToken(h);
2003
2004 if (h->flags & PRINT_STREAM)
2005 for (i = 0; i < token->length; i++)
2006 if (token->value[i] == '\r') {
2007 h->flags |= CRLF_NEWLINES;
2008 break;
2009 }
2010
2011 if (h->key.seen[kStdVW])
2012 return;
2013
2014 if (token->type == pstProcedure) {
2015 char *p = copyArrayToken(h, token) + 1;
2016 char *endp = p + strlen(p);
2017 i = 0;
2018 while (*p != '\0') {
2019 /* Skip whitespace */
2020 while (isspace(*p) && (p < endp))
2021 p++;
2022
2023 if (*p == '}')
2024 break; /* Badly formed erode proc */
2025
2026 if (++i == 16) {
2027 /* Convert 16th token */
2028 char *q;
2029 long value = strtol(p, &q, 0);
2030 if (p != q && value >= 0)
2031 private->StdVW = (float)value;
2032 break;
2033 }
2034
2035 /* Skip token */
2036 while (!isspace(*p) && (p < endp))
2037 p++;
2038 }
2039 }
2040 }
2041
2042 /* Parse OrigFontType. */
2043 static void parseOrigFontType(t1rCtx h, abfTopDict *top) {
2044 pstToken *token = getToken(h);
2045 if (token->type == pstLiteral) {
2046 static struct
2047 {
2048 const char *name;
2049 int id;
2050 } map[] =
2051 {
2052 {"Type1", abfOrigFontTypeType1},
2053 {"CID", abfOrigFontTypeCID},
2054 {"TrueType", abfOrigFontTypeTrueType},
2055 {"OCF", abfOrigFontTypeOCF},
2056 };
2057 unsigned int i;
2058 long length;
2059 char *value = pstConvLiteral(h->pst, token, &length);
2060
2061 for (i = 0; i < ARRAY_LEN(map); i++)
2062 if (strlen(map[i].name) == (size_t)length &&
2063 strncmp(value, map[i].name, length) == 0) {
2064 top->OrigFontType = map[i].id;
2065 return;
2066 }
2067 }
2068
2069 badKeyValue(h, kOrigFontType);
2070 }
2071
2072 /* Initialize FDArray. */
2073 static void initFDArray(t1rCtx h, long cnt) {
2074 int i;
2075 if (cnt < 1 || cnt > 256)
2076 badKeyValue(h, kFDArray);
2077 dnaSET_CNT(h->FDArray, cnt);
2078 dnaSET_CNT(h->fdicts, cnt);
2079 for (i = 0; i < h->FDArray.cnt; i++)
2080 initFDInfo(h, i);
2081 h->fd = &h->FDArray.array[0];
2082 }
2083
2084 /* Match key name. */
2085 static int CTL_CDECL matchKey(const void *key, const void *value) {
2086 const char *a = ((MatchStr *)key)->value;
2087 const char *end = a + ((MatchStr *)key)->length;
2088 const char *b = *(char **)value;
2089 while (a != end)
2090 if (*b == '\0')
2091 return 1;
2092 else if (*a < *b)
2093 return -1;
2094 else if (*a++ > *b++)
2095 return 1;
2096 return (*b != '\0') ? -1 : 0;
2097 }
2098
2099 /* Initialize key seen array. */
2100 static void initKeySeen(t1rCtx h) {
2101 memset(h->key.seen, 0, sizeof(h->key.seen));
2102 }
2103
2104 /* Process literal. */
2105 static void doLiteral(t1rCtx h, pstToken *literal) {
2106 abfTopDict *top;
2107 abfFontDict *font;
2108 abfPrivateDict *private;
2109 MatchStr key;
2110 int keyId;
2111 const char **p;
2112
2113 /* Lookup literal in key list */
2114 key.value = pstConvLiteral(h->pst, literal, &key.length);
2115 p = (const char **)bsearch(&key, keys, ARRAY_LEN(keys),
2116 sizeof(keys[0]), matchKey);
2117 if (p == NULL)
2118 return; /* Ignore unknown key */
2119
2120 /* Convert to index */
2121 /* 64-bit warning fixed by cast here HO */
2122 keyId = (int)(p - keys);
2123
2124 /* For CIDFonts check for key redefinition which signals new FD */
2125 if (h->flags & CID_FONT && h->key.seen[keyId]) {
2126 if (++h->fd - h->FDArray.array >= h->FDArray.cnt)
2127 fatal(h, t1rErrFDArray, NULL);
2128 initKeySeen(h);
2129 }
2130
2131 top = &h->top;
2132 font = h->fd->fdict;
2133 private = &font->Private;
2134
2135 /* Process key */
2136 switch (keyId) {
2137 /* -------------------------- Top Dict ------------------------- */
2138 case kversion:
2139 top->version.impl = parseString(h, kversion);
2140 break;
2141 case kNotice:
2142 top->Notice.impl = parseString(h, kNotice);
2143 break;
2144 case kCopyright:
2145 top->Copyright.impl = parseString(h, kCopyright);
2146 break;
2147 case kFullName:
2148 top->FullName.impl = parseString(h, kFullName);
2149 break;
2150 case kFamilyName:
2151 top->FamilyName.impl = parseString(h, kFamilyName);
2152 break;
2153 case kWeight:
2154 top->Weight.impl = parseString(h, kWeight);
2155 break;
2156 case kisFixedPitch:
2157 top->isFixedPitch = parseBool(h, kisFixedPitch);
2158 break;
2159 case kItalicAngle:
2160 top->ItalicAngle = parseNum(h, kItalicAngle, 0);
2161 break;
2162 case kUnderlinePosition:
2163 top->UnderlinePosition = parseNum(h, kUnderlinePosition, 1);
2164 break;
2165 case kUnderlineThickness:
2166 top->UnderlineThickness = parseNum(h, kUnderlineThickness, 1);
2167 break;
2168 case kUniqueID:
2169 top->UniqueID = parseInt(h, kUniqueID);
2170 break;
2171 case kFontBBox:
2172 (void)parseNumArray(h, kFontBBox, 4, 4, top->FontBBox, 1, 0);
2173 break;
2174 case kStrokeWidth:
2175 top->StrokeWidth = parseNum(h, kStrokeWidth, 1);
2176 break;
2177 case kXUID:
2178 top->XUID.cnt = parseIntArray(h, kXUID, 1, 16, top->XUID.array);
2179 break;
2180 case kEncoding:
2181 readEncoding(h);
2182 break;
2183 case kPaintType:
2184 font->PaintType = parseInt(h, kPaintType);
2185 break;
2186 case kFontType:
2187 if (parseInt(h, kFontType) != 1)
2188 fatal(h, t1rErrFontType, NULL);
2189 break;
2190 case klenIV:
2191 h->fd->key.lenIV = parseInt(h, klenIV);
2192 if (h->fd->key.lenIV < -1)
2193 badKeyValue(h, klenIV);
2194 break;
2195 case kFontMatrix:
2196 if (parseFontMatrix(h, top, font))
2197 return; /* Avoid setting the key.seen[kFontMatrix] for top dict */
2198 break;
2199 case kFontName:
2200 font->FontName.impl = parseName(h, kFontName);
2201 break;
2202 case kPrivate:
2203 break;
2204 case kCharStrings:
2205 readChars(h);
2206 break;
2207 /* ------------------------ Private Dict ----------------------- */
2208 case kBlueValues:
2209 private->BlueValues.cnt =
2210 parseNumArray(h, kBlueValues, 0, 14,
2211 private->BlueValues.array, 1, 0);
2212 h->fd->key.BlueValues = 1;
2213 break;
2214 case kOtherBlues:
2215 private->OtherBlues.cnt =
2216 parseNumArray(h, kOtherBlues, 0, 10,
2217 private->OtherBlues.array, 1, 1);
2218 break;
2219 case kFamilyBlues:
2220 if (h->key.seen[kFamilyBlues] && !h->key.seen[kWeightVector])
2221 /* Ignore second FamilyBlues in some bad single master fonts */
2222 message(h, "duplicate /FamilyBlues (ignored)");
2223 else
2224 private->FamilyBlues.cnt =
2225 parseNumArray(h, kFamilyBlues, 0, 14,
2226 private->FamilyBlues.array, 1, 1);
2227 break;
2228 case kFamilyOtherBlues:
2229 private->FamilyOtherBlues.cnt =
2230 parseNumArray(h, kFamilyOtherBlues, 0, 10,
2231 private->FamilyOtherBlues.array, 1, 1);
2232 break;
2233 case kBlueScale:
2234 private->BlueScale = parseNum(h, kBlueScale, 0);
2235 break;
2236 case kBlueShift:
2237 private->BlueShift = parseNum(h, kBlueShift, 0);
2238 break;
2239 case kBlueFuzz:
2240 private->BlueFuzz = parseNum(h, kBlueFuzz, 1);
2241 break;
2242 case kStdHW:
2243 (void)parseNumArray(h, kStdHW, 0, 1, &private->StdHW, 1, 1);
2244 break;
2245 case kStdVW:
2246 (void)parseNumArray(h, kStdVW, 0, 1, &private->StdVW, 1, 1);
2247 break;
2248 case kStemSnapH:
2249 private->StemSnapH.cnt =
2250 parseNumArray(h, kStemSnapH, 0, 12,
2251 private->StemSnapH.array, 1, 1);
2252 break;
2253 case kStemSnapV:
2254 private->StemSnapV.cnt =
2255 parseNumArray(h, kStemSnapV, 0, 12,
2256 private->StemSnapV.array, 1, 1);
2257 break;
2258 case kForceBold:
2259 private->ForceBold = parseBool(h, kForceBold);
2260 break;
2261 case kForceBoldThreshold:
2262 h->mm.ForceBoldThreshold = parseNum(h, kForceBoldThreshold, 1);
2263 break;
2264 case kRndStemUp:
2265 /* RndStemUp with any value saved as LanguageGroup=1
2266 (which enables global coloring) */
2267 private->LanguageGroup = 1;
2268 break;
2269 case kLanguageGroup:
2270 private->LanguageGroup = parseInt(h, kLanguageGroup);
2271 break;
2272 case kExpansionFactor:
2273 private->ExpansionFactor = parseNum(h, kExpansionFactor, 1);
2274 break;
2275 case kinitialRandomSeed:
2276 private->initialRandomSeed = parseNum(h, kinitialRandomSeed, 0);
2277 break;
2278 case kSubrs:
2279 readSubrs(h);
2280 break;
2281 case kErode:
2282 parseErodeProc(h, private);
2283 break;
2284 case kRD:
2285 checkRDType(h);
2286 break;
2287 /* ------------------ Multiple Master Top Dict ----------------- */
2288 case kWeightVector:
2289 h->mm.WV.cnt =
2290 parseNumArray(h, kWeightVector, 2, ARRAY_LEN(h->mm.WV.array),
2291 h->mm.WV.array, 0, 0);
2292 break;
2293 case kBlendDesignPositions:
2294 h->mm.BDP.cnt =
2295 parseNumArray(h, kBlendDesignPositions, 2,
2296 ARRAY_LEN(h->mm.BDP.array), h->mm.BDP.array, 0, 0);
2297 break;
2298 case kBlendDesignMap:
2299 h->mm.BDM.cnt =
2300 parseNumArray(h, kBlendDesignMap, 4, ARRAY_LEN(h->mm.BDM.array),
2301 h->mm.BDM.array, 0, 0);
2302 break;
2303 case kBlend:
2304 mmInit(h);
2305 break;
2306 /* ------------------------ CID Top Dict ----------------------- */
2307 case kCIDFontName:
2308 top->cid.CIDFontName.impl = parseName(h, kCIDFontName);
2309 break;
2310 case kRegistry:
2311 top->cid.Registry.impl = parseString(h, kRegistry);
2312 break;
2313 case kOrdering:
2314 top->cid.Ordering.impl = parseString(h, kOrdering);
2315 break;
2316 case kSupplement:
2317 top->cid.Supplement = parseInt(h, kSupplement);
2318 break;
2319 case kCIDFontVersion:
2320 top->cid.CIDFontVersion = parseNum(h, kCIDFontVersion, 0);
2321 break;
2322 case kCIDFontRevision:
2323 top->cid.CIDFontRevision = parseInt(h, kCIDFontRevision);
2324 break;
2325 case kUIDBase:
2326 top->cid.UIDBase = parseInt(h, kUIDBase);
2327 break;
2328 case kCIDCount:
2329 top->cid.CIDCount = parseInt(h, kCIDCount);
2330 if (top->cid.CIDCount < 0 || top->cid.CIDCount > 65535)
2331 badKeyValue(h, kCIDCount);
2332 break;
2333 case kCIDInit:
2334 h->flags |= CID_FONT;
2335 break;
2336 case kCIDFontType:
2337 if (parseInt(h, kCIDFontType) != 0)
2338 fatal(h, t1rErrCIDFontType, NULL);
2339 break;
2340 case kCIDMapOffset:
2341 h->key.CIDMapOffset = parseInt(h, kCIDMapOffset);
2342 break;
2343 case kFDBytes:
2344 h->key.FDBytes = parseInt(h, kFDBytes);
2345 break;
2346 case kGDBytes:
2347 h->key.GDBytes = parseInt(h, kGDBytes);
2348 break;
2349 case kFDArray:
2350 initFDArray(h, parseInt(h, kFDArray));
2351 break;
2352 case kRunInt: {
2353 /* Check protection from the value of the /RunInt key. */
2354 pstToken *token = getToken(h);
2355 if (pstMatch(h->pst, token, "/CCRun"))
2356 /* Unprotected font */;
2357 else if (pstMatch(h->pst, token, "/eCCRun"))
2358 /* Protected font */
2359 h->fd->decrypt = t1cUnprotect;
2360 else
2361 badKeyValue(h, kRunInt);
2362 } break;
2363 case kSubrMapOffset:
2364 h->fd->key.SubrMapOffset = parseInt(h, kSubrMapOffset);
2365 break;
2366 case kSDBytes:
2367 h->fd->key.SDBytes = (unsigned short)parseInt(h, kSDBytes);
2368 break;
2369 case kSubrCount:
2370 h->fd->key.SubrCount = (unsigned short)parseInt(h, kSubrCount);
2371 break;
2372 case kGlyphDirectory:
2373 parseGlyphDirectory(h);
2374 h->flags |= (PRINT_STREAM | SEEN_END);
2375 break;
2376 /* ----------------------- Miscellaneous ----------------------- */
2377 case kPostScript:
2378 h->top.PostScript.impl = parseString(h, kPostScript);
2379 break;
2380 case kBaseFontName:
2381 h->top.BaseFontName.impl = parseString(h, kBaseFontName);
2382 break;
2383 case kBaseFontBlend:
2384 top->BaseFontBlend.cnt = parseIntArray(h, kBaseFontBlend, 1, 15,
2385 h->top.BaseFontBlend.array);
2386 break;
2387 case kFSType:
2388 top->FSType = parseInt(h, kFSType);
2389 if (top->FSType < 0 || top->FSType > 65535)
2390 badKeyValue(h, kFSType);
2391 break;
2392 case kOrigFontType:
2393 parseOrigFontType(h, top);
2394 break;
2395 case kWasEmbedded:
2396 top->WasEmbedded = parseBool(h, kWasEmbedded);
2397 break;
2398 case kChameleon:
2399 fatal(h, t1rErrChameleon, NULL);
2400 break;
2401 case khires:
2402 fatal(h, t1rErrHybrid, NULL);
2403 break;
2404 }
2405 h->key.seen[keyId] = 1; /* Note that key was seen */
2406 }
2407
2408 /* ---------------------------- Operator Parsing --------------------------- */
2409
2410 /* Process operator. */
2411 static void doOperator(t1rCtx h, pstToken *operator) {
2412 if (pstMatch(h->pst, operator, "currentfile")) {
2413 pstToken *token;
2414 int result = 0;
2415 token = getToken(h);
2416 if (pstMatch(h->pst, token, "eexec"))
2417 result = pstSetDecrypt(h->pst); /* Prepare for eexec */
2418 else if (pstMatch(h->pst, token, "closefile"))
2419 result = pstSetPlain(h->pst); /* Prepare for plaintext */
2420 if (result)
2421 pstFatal(h, result);
2422 } else if (h->key.seen[kPrivate] &&
2423 pstMatch(h->pst, operator, "FontDirectory")) {
2424 /* Synthetic font; temporarily save synthetic font values */
2425 h->synthetic.FontName = h->fd->fdict->FontName;
2426 h->synthetic.FullName = h->top.FullName;
2427 h->synthetic.ItalicAngle = h->top.ItalicAngle;
2428 h->synthetic.UniqueID = h->top.UniqueID;
2429 h->synthetic.FontMatrix = h->fd->fdict->FontMatrix;
2430
2431 /* Reinitialize */
2432 abfInitTopDict(&h->top);
2433 abfInitFontDict(h->fd->fdict);
2434
2435 initKeySeen(h);
2436 tmpInit(h);
2437 h->fd->subrs.offset.cnt = 0;
2438
2439 h->flags |= SYN_FONT;
2440 }
2441 }
2442
2443 /* ------------------------------ CID Parsing ------------------------------ */
2444
2445 /* Save 5 std subrs to tmp file and initialize each FD to use them. */
2446 static void saveStdSubrs(t1rCtx h) {
2447 static const unsigned char subr0[] =
2448 {0x8e, 0x8b, 0xc, 0x10, 0xc, 0x11, 0xc, 0x11, 0xc, 0x21, 0xb};
2449 static const unsigned char subr1[] =
2450 {0x8b, 0x8c, 0xc, 0x10, 0xb};
2451 static const unsigned char subr2[] =
2452 {0x8b, 0x8d, 0xc, 0x10, 0xb};
2453 static const unsigned char subr3[] =
2454 {0xb};
2455 static const unsigned char subr4[] =
2456 {0x8e, 0x8c, 0x8e, 0xc, 0x10, 0xc, 0x11, 0xa, 0xb};
2457 enum { subrcnt = 5 };
2458 long tmpoffs[subrcnt];
2459 long lenIV;
2460 ctlRegion region;
2461 int i;
2462
2463 /* Make temporary copy of lenIV */
2464 lenIV = h->FDArray.array[0].key.lenIV;
2465
2466 /* Set lenIV -1 to match pre-defined subrs */
2467 h->FDArray.array[0].key.lenIV = -1;
2468
2469 /* Write subrs to temp file */
2470 region.begin = h->tmpoff;
2471 tmpoffs[0] = saveSubr(h, sizeof(subr0), (char *)subr0, 0, 0);
2472 tmpoffs[1] = saveSubr(h, sizeof(subr1), (char *)subr1, 0, 1);
2473 tmpoffs[2] = saveSubr(h, sizeof(subr2), (char *)subr2, 0, 2);
2474 tmpoffs[3] = saveSubr(h, sizeof(subr3), (char *)subr3, 0, 3);
2475 tmpoffs[4] = saveSubr(h, sizeof(subr4), (char *)subr4, 0, 4);
2476 region.end = h->tmpoff;
2477
2478 /* Restore original lenIV */
2479 h->FDArray.array[0].key.lenIV = lenIV;
2480
2481 for (i = 0; i < h->FDArray.cnt; i++) {
2482 FDInfo *fd = &h->FDArray.array[i];
2483 fd->subrs.region = region;
2484 dnaSET_CNT(fd->subrs.offset, subrcnt);
2485 memcpy(fd->subrs.offset.array, tmpoffs, sizeof(tmpoffs));
2486 }
2487 }
2488
2489 /* Set LanguageGroup for glyph. */
2490 static void setLanguageGroup(t1rCtx h,
2491 abfGlyphInfo *info, unsigned char iFD, long cid) {
2492 if (iFD >= h->fdicts.cnt)
2493 fatal(h, t1rErrFDRange, "invalid FD index CID-%ld", cid);
2494 else if (h->fdicts.array[iFD].Private.LanguageGroup == 1)
2495 info->flags |= ABF_GLYPH_LANG_1;
2496 }
2497
2498 /* Save CID download format char. */
2499 static void cidSaveChar(t1rCtx h, long len, char *cstr, long cid) {
2500 unsigned char iFD;
2501 unsigned short tag = (unsigned short)h->chars.index.cnt;
2502 Char *chr = dnaNEXT(h->chars.index);
2503
2504 /* Handle fd index byte */
2505 if (h->key.FDBytes == 0)
2506 iFD = 0;
2507 else {
2508 iFD = (unsigned char)cstr[0];
2509 cstr++;
2510 len--;
2511 }
2512
2513 if (cid < 0 || cid >= h->top.cid.CIDCount)
2514 fatal(h, t1rErrCIDRange, NULL);
2515
2516 /* Initialize char */
2517 abfInitGlyphInfo(chr);
2518 chr->flags = ABF_GLYPH_CID;
2519 chr->tag = tag;
2520 chr->cid = (unsigned short)cid;
2521 chr->iFD = iFD;
2522 setLanguageGroup(h, chr, iFD, cid);
2523
2524 /* Save charstring */
2525 saveCstr(h, len, cstr, chr, 1);
2526 }
2527
2528 /* Parse GlyphDirectory in download CID format (unpublished). */
2529 static void parseGlyphDirectory(t1rCtx h) {
2530 char *cstr;
2531 pstToken *token;
2532 int state;
2533 int tokenType = pstHexString;
2534 long cid = 0; /* Suppress optimizer warning */
2535 long len = 0; /* Suppress optimizer warning */
2536
2537 h->chars.index.cnt = 0;
2538 saveStdSubrs(h);
2539
2540 /* Search for glyph data start */
2541 state = 0;
2542 for (;;) {
2543 token = getToken(h);
2544 switch (state) {
2545 case 0:
2546 if (token->type == pstInteger) {
2547 cid = pstConvInteger(h->pst, token);
2548 state = 1;
2549 }
2550 break;
2551 case 1:
2552 switch (token->type) {
2553 case pstInteger:
2554 len = pstConvInteger(h->pst, token);
2555 state = 2;
2556 break;
2557 case pstASCII85:
2558 tokenType = pstASCII85;
2559 /* Fall through */
2560 case pstHexString:
2561 goto parse_hex_fmt;
2562 default:
2563 state = 0;
2564 break;
2565 }
2566 break;
2567 case 2:
2568 if (pstMatch(h->pst, token, ":"))
2569 goto parse_bin_fmt;
2570 state = 0;
2571 }
2572 }
2573
2574 /* Hexadecimal charstring parse loop */
2575 parse_hex_fmt:
2576 for (;;) {
2577 /* Convert hex string to binary */
2578 if (tokenType == pstASCII85) {
2579 cstr = token->value + 2;
2580 len = convASCII85Cstr(h, cstr);
2581 } else {
2582 cstr = token->value + 1;
2583 len = convASCIIHexCstr(h, token->length - 2, cstr);
2584 }
2585 if (len == 0)
2586 goto bad_char;
2587
2588 cidSaveChar(h, len, cstr, cid);
2589
2590 /* Parse terminating operator */
2591 if (!pstMatch(h->pst, getToken(h), "|"))
2592 goto bad_char;
2593
2594 /* Parse CID token */
2595 token = getToken(h);
2596 if (token->type != pstInteger)
2597 return;
2598 cid = pstConvInteger(h->pst, token);
2599
2600 /* Parse cstr */
2601 token = getToken(h);
2602 if (token->type != tokenType)
2603 goto bad_char;
2604 }
2605
2606 /* Binary charstring parse loop */
2607 parse_bin_fmt:
2608 for (;;) {
2609 int result = pstRead(h->pst, len + 1, &cstr);
2610 if (result)
2611 pstFatal(h, result);
2612
2613 cidSaveChar(h, len, cstr + 1, cid);
2614
2615 /* Parse NP operator */
2616 if (!pstMatch(h->pst, getToken(h), "|"))
2617 goto bad_char;
2618
2619 /* Parse CID token */
2620 token = getToken(h);
2621 if (token->type != pstInteger)
2622 return;
2623 cid = pstConvInteger(h->pst, token);
2624
2625 /* Parse cstr length */
2626 token = getToken(h);
2627 if (token->type != pstInteger)
2628 goto bad_char;
2629 len = pstConvInteger(h->pst, token);
2630 if (len < 1 || len > 65535)
2631 goto bad_char;
2632
2633 /* Parse RD operator */
2634 if (!pstMatch(h->pst, getToken(h), ":"))
2635 goto bad_char;
2636 }
2637
2638 bad_char:
2639 fatal(h, t1rErrCharEntry, "invalid char entry CID-%ld", cid);
2640 }
2641
2642 /* Fill source buffer. */
2643 static void fillbuf(t1rCtx h, long offset) {
2644 h->src.length = h->cb.stm.read(&h->cb.stm, h->stm.src, &h->src.buf);
2645 if (h->src.length == 0)
2646 fatal(h, t1rErrSrcStream, NULL);
2647 h->src.offset = offset;
2648 h->src.next = h->src.buf;
2649 h->src.end = h->src.buf + h->src.length;
2650 }
2651
2652 /* Refill source buffer. */
2653 static char nextbuf(t1rCtx h) {
2654 /* 64-bit warning fixed by cast here HO */
2655 fillbuf(h, (long)(h->src.offset + h->src.length));
2656 return *h->src.next++;
2657 }
2658
2659 /* Seek to specified offset. */
2660 static void srcSeek(t1rCtx h, long offset) {
2661 long delta = offset - h->src.offset;
2662 if (delta >= 0 && (size_t)delta < h->src.length)
2663 /* Offset within current buffer; reposition next byte */
2664 h->src.next = h->src.buf + delta;
2665 else {
2666 if (h->stm.src == NULL)
2667 fatal(h, t1rErrSrcStream, NULL);
2668
2669 /* Offset outside current buffer; seek to offset and fill buffer */
2670 if (h->cb.stm.seek(&h->cb.stm, h->stm.src, offset))
2671 fatal(h, t1rErrSrcStream, NULL);
2672 fillbuf(h, offset);
2673 }
2674 }
2675
2676 /* Read charstring from source stream. */
2677 static char *readCstr(t1rCtx h, long begin, long end) {
2678 char *p;
2679 long left;
2680 long length = end - begin;
2681
2682 srcSeek(h, begin);
2683
2684 /* 64-bit warning fixed by cast here HO */
2685 left = (long)(h->src.end - h->src.next);
2686 if (left >= length) {
2687 /* Source buffer contains charstring; return it */
2688 p = h->src.next;
2689 h->src.next += length;
2690 return p;
2691 } else {
2692 /* Charstring spans source buffers; make copy */
2693 dnaSET_CNT(h->tmp, length);
2694
2695 p = h->tmp.array;
2696 do {
2697 /* Copy buffer */
2698 memcpy(p, h->src.next, left);
2699 p += left;
2700 length -= left;
2701
2702 /* Refill buffer */
2703 /* 64-bit warning fixed by cast here HO */
2704 fillbuf(h, (long)(h->src.offset + h->src.length));
2705 /* 64-bit warning fixed by cast here HO */
2706 left = (long)h->src.length;
2707 } while (left < length);
2708
2709 memcpy(p, h->src.next, length);
2710 h->src.next += length;
2711
2712 return h->tmp.array;
2713 }
2714 }
2715
2716 /* Read 1-byte unsigned number. */
2717 #define read1(h) \
2718 ((unsigned char)((h->src.next == h->src.end) ? nextbuf(h) : *h->src.next++))
2719
2720 /* Read CIDMap or SubrMap offset. */
2721 static long readN(t1rCtx h, int N) {
2722 unsigned long value = 0;
2723 switch (N) {
2724 case 4:
2725 value = read1(h);
2726 case 3:
2727 value = value << 8 | read1(h);
2728 case 2:
2729 value = value << 8 | read1(h);
2730 case 1:
2731 value = value << 8 | read1(h);
2732 }
2733 return value;
2734 }
2735
2736 /* Read CIDMap. */
2737 static void readCIDMap(t1rCtx h,
2738 long StartDataOffset, long length, long *maxoff) {
2739 long cid;
2740 long tag;
2741 unsigned char fd;
2742 long offset;
2743
2744 /* Set chars array size */
2745 dnaSET_CNT(h->chars.index, h->top.cid.CIDCount);
2746
2747 /* Validate */
2748 if (h->key.CIDMapOffset == -1)
2749 fatal(h, t1rErrCIDMap, NULL);
2750
2751 if (h->key.GDBytes < 1 || h->key.GDBytes > 4)
2752 badKeyValue(h, kGDBytes);
2753
2754 /* Read to CIDMap */
2755 srcSeek(h, StartDataOffset + h->key.CIDMapOffset);
2756 tag = 0;
2757 fd = (h->key.FDBytes == 0) ? 0 : read1(h);
2758 offset = readN(h, h->key.GDBytes);
2759 for (cid = 0; cid < h->chars.index.cnt; cid++) {
2760 unsigned char nextfd = (h->key.FDBytes == 0) ? 0 : read1(h);
2761 long nextoff = readN(h, h->key.GDBytes);
2762 if (offset != nextoff) {
2763 long charstring_length;
2764 Char *chr = &h->chars.index.array[tag];
2765
2766 /* Initialize char */
2767 abfInitGlyphInfo(chr);
2768 chr->flags = ABF_GLYPH_CID;
2769 chr->tag = (unsigned short)tag++;
2770 chr->cid = (unsigned short)cid;
2771 chr->iFD = fd;
2772 chr->sup.begin = StartDataOffset + offset;
2773 chr->sup.end = StartDataOffset + nextoff;
2774
2775 setLanguageGroup(h, chr, fd, cid);
2776
2777 charstring_length = chr->sup.end - chr->sup.begin;
2778 if (charstring_length < 0 || charstring_length > 65535)
2779 fatal(h, t1rErrCharLength,
2780 "bad charstring length <cid-%ld>", cid);
2781 }
2782 fd = nextfd;
2783 offset = nextoff;
2784 }
2785 h->chars.index.cnt = tag;
2786 if (h->chars.index.cnt == 0)
2787 fatal(h, t1rErrCIDMap, NULL);
2788
2789 if (h->chars.index.array[h->chars.index.cnt - 1].cid + 1 !=
2790 h->top.cid.CIDCount)
2791 message(h, "/CIDCount too big (ignored)");
2792
2793 if (h->chars.index.array[0].cid != 0)
2794 /* CID 0 (notdef) missing. I would have liked to insert the missing
2795 character but this is too complicated cid-keyed fonts to be
2796 worthwhile for such a rare case so I just report a fatal error */
2797 fatal(h, t1rErrNoCID0, NULL);
2798
2799 if (offset > *maxoff)
2800 *maxoff = offset;
2801 }
2802
2803 /* Read SubrMaps and subr charstrings. */
2804 static void readSubrMaps(t1rCtx h, long StartDataOffset, long *maxoff) {
2805 long i;
2806 long j;
2807
2808 for (i = 0; i < h->FDArray.cnt; i++) {
2809 FDInfo *fd = &h->FDArray.array[i];
2810
2811 /* Grow buffer to accommodate SubrCount+1 subr offset */
2812 (void)dnaGROW(fd->subrs.offset, fd->key.SubrCount);
2813 fd->subrs.offset.cnt = fd->key.SubrCount;
2814 if (fd->subrs.offset.cnt == 0)
2815 continue; /* No subrs */
2816
2817 /* Validate */
2818 if (fd->key.SubrMapOffset == -1)
2819 fatal(h, t1rErrSubrMap, "/SubrMapOffset missing: FD[%ld]", i);
2820
2821 if (fd->key.SDBytes < 1 || fd->key.SDBytes > 4)
2822 fatal(h, t1rErrKeyValue, "/SDBytes: bad value: FD[%ld]", i);
2823
2824 /* Read SubrMap */
2825 srcSeek(h, StartDataOffset + fd->key.SubrMapOffset);
2826 for (j = 0; j <= fd->subrs.offset.cnt; j++)
2827 fd->subrs.offset.array[j] =
2828 StartDataOffset + readN(h, fd->key.SDBytes);
2829 }
2830
2831 /* Read, decrypt, and copy charstrings to tmp file. */
2832 for (i = 0; i < h->FDArray.cnt; i++) {
2833 FDInfo *fd = &h->FDArray.array[i];
2834 long offset =
2835 fd->subrs.offset.array[fd->subrs.offset.cnt] - StartDataOffset;
2836 if (offset > *maxoff)
2837 *maxoff = offset;
2838 fd->subrs.region.begin = h->tmpoff;
2839 for (j = 0; j < fd->subrs.offset.cnt; j++) {
2840 char *cstr;
2841 long begin = fd->subrs.offset.array[j];
2842 long end = fd->subrs.offset.array[j + 1];
2843 long length = end - begin;
2844
2845 if (length < 1 || length > 65535)
2846 fatal(h, t1rErrKeyValue,
2847 "bad subr length FD[%ld].subr[%ld]", i, j);
2848
2849 cstr = readCstr(h, begin, end);
2850
2851 if (fd->key.lenIV != -1 && cstr != h->tmp.array) {
2852 /* Make copy of charstring. A copy is need here because
2853 saveSubr() will perform in-place decryption of the
2854 charstring and it is possible the the same charstring is
2855 referenced from other FDs and would therefore be decrypted a
2856 second time causing failure. */
2857 dnaSET_CNT(h->tmp, length);
2858 memcpy(h->tmp.array, cstr, length);
2859 cstr = h->tmp.array;
2860 }
2861
2862 fd->subrs.offset.array[j] = saveSubr(h, length, cstr, i, j);
2863 }
2864
2865 fd->subrs.region.end = h->tmpoff;
2866 }
2867 }
2868
2869 /* Seen first token of possible StartData sequence. Try to match the rest.
2870 Return NULL on match else non-matching token. */
2871 static pstToken *cidRead(t1rCtx h, int binary) {
2872 pstToken *token;
2873 long maxoff;
2874 long length;
2875 long StartDataOffset;
2876
2877 /* Match length */
2878 token = getToken(h);
2879 if (token->type != pstInteger)
2880 return token;
2881 length = pstConvInteger(h->pst, token);
2882
2883 /* Match StartData token */
2884 token = getToken(h);
2885 if (!pstMatch(h->pst, token, "StartData"))
2886 return token;
2887
2888 if (!binary)
2889 fatal(h, t1rErrStartData, NULL);
2890
2891 /* Matched: (Binary) <length> StartData; validate keys */
2892 if (h->key.FDBytes != 1 && h->key.FDBytes != 0)
2893 badKeyValue(h, kFDBytes);
2894
2895 /* Hijack source stream from pstoken lib */
2896 h->stm.src = pstHijackStream(h->pst, &StartDataOffset);
2897 if (h->stm.src == NULL)
2898 fatal(h, t1rErrSrcStream, NULL);
2899
2900 /* Initialize source read */
2901 h->src.offset = 0;
2902 h->src.length = 0;
2903
2904 /* Skip separator byte */
2905 StartDataOffset++;
2906
2907 maxoff = 0;
2908 readCIDMap(h, StartDataOffset, length, &maxoff);
2909 readSubrMaps(h, StartDataOffset, &maxoff);
2910
2911 if (maxoff != length) {
2912 long diff = length - maxoff;
2913 if (diff > 0)
2914 message(h,
2915 "StartData length is %ld bytes too long (ignored)", diff);
2916 else
2917 message(h,
2918 "StartData length is %ld bytes too short (ignored)", -diff);
2919 }
2920
2921 h->flags |= SEEN_END;
2922
2923 return NULL;
2924 }
2925
2926 /* Add string pointer from string index. */
2927 static void addStrPtr(t1rCtx h, abfString *str) {
2928 if (str->impl != ABF_UNSET_INT)
2929 str->ptr = getString(h, (STI)str->impl);
2930 }
2931
2932 /* Return the offset of a standard encoded glyph of -1 if none. */
2933 static long getStdEncGlyphOffset(void *ctx, int stdcode) {
2934 t1rCtx h = ctx;
2935 unsigned short tag = h->encoding.standard[stdcode];
2936 return (tag == 0xffff) ? -1 : h->chars.index.array[tag].sup.begin;
2937 }
2938
2939 /* Report absfont error message to debug stream. */
2940 static void report_error(abfErrCallbacks *cb, int err_code, int iFD) {
2941 t1rCtx h = cb->ctx;
2942 if (iFD == -1)
2943 message(h, "%s (ignored)", abfErrStr(err_code));
2944 else
2945 message(h, "%s FD[%d] (ignored)", abfErrStr(err_code), iFD);
2946 }
2947
2948 /* Prepare font data for client. */
2949 static void prepClientData(t1rCtx h) {
2950 long i;
2951
2952 if (h->flags & SYN_FONT) {
2953 /* Synthetic font; save base FontName */
2954 h->top.SynBaseFontName = h->fd->fdict->FontName;
2955
2956 /* Restore synthetic font values */
2957 h->fd->fdict->FontName = h->synthetic.FontName;
2958 h->top.FullName = h->synthetic.FullName;
2959 h->top.ItalicAngle = h->synthetic.ItalicAngle;
2960 h->top.UniqueID = h->synthetic.UniqueID;
2961 h->fd->fdict->FontMatrix = h->synthetic.FontMatrix;
2962 h->top.sup.flags |= ABF_SYN_FONT;
2963 }
2964 if (h->flags & MM_FONT)
2965 prepMMData(h);
2966
2967 /* Add strings to top dict */
2968 addStrPtr(h, &h->top.version);
2969 addStrPtr(h, &h->top.Notice);
2970 addStrPtr(h, &h->top.Copyright);
2971 addStrPtr(h, &h->top.FullName);
2972 addStrPtr(h, &h->top.FamilyName);
2973 addStrPtr(h, &h->top.Weight);
2974 addStrPtr(h, &h->top.PostScript);
2975 addStrPtr(h, &h->top.BaseFontName);
2976 addStrPtr(h, &h->top.SynBaseFontName);
2977 addStrPtr(h, &h->top.cid.CIDFontName);
2978 addStrPtr(h, &h->top.cid.Registry);
2979 addStrPtr(h, &h->top.cid.Ordering);
2980
2981 /* Add strings to font dicts */
2982 for (i = 0; i < h->fdicts.cnt; i++) {
2983 abfFontDict *font = &h->fdicts.array[i];
2984 addStrPtr(h, &font->FontName);
2985 }
2986
2987 /* Prepare auxiliary data */
2988 for (i = 0; i < h->FDArray.cnt; i++) {
2989 FDInfo *fd = &h->FDArray.array[i];
2990 fd->aux.flags = 0;
2991 if (h->flags & T1R_UPDATE_OPS)
2992 fd->aux.flags |= T1C_UPDATE_OPS;
2993 fd->aux.src = h->stm.tmp;
2994 fd->aux.subrs.cnt = fd->subrs.offset.cnt;
2995 fd->aux.subrs.offset = fd->subrs.offset.array;
2996 fd->aux.subrsEnd = fd->subrs.region.end;
2997 fd->aux.stm = &h->cb.stm;
2998 fd->aux.ctx = h;
2999 fd->aux.getStdEncGlyphOffset = getStdEncGlyphOffset;
3000 if (h->flags & T1R_USE_MATRIX) {
3001 abfFontMatrix *FontMatrix = &h->fdicts.array[i].FontMatrix;
3002
3003 if (FontMatrix->cnt != ABF_EMPTY_ARRAY) {
3004 /* Prepare transformation matrix */
3005 int j;
3006 for (j = 0; j < 6; j++)
3007 fd->aux.matrix[j] =
3008 FontMatrix->array[j] * h->top.sup.UnitsPerEm;
3009 fd->aux.flags |= T1C_USE_MATRIX;
3010 }
3011 }
3012 if (!(h->flags & MM_FONT))
3013 fd->aux.nMasters = 1;
3014 if (!(fd->key.BlueValues))
3015 message(h, "/BlueValues missing: FD[%ld]", i);
3016 }
3017
3018 h->top.sup.nGlyphs = h->chars.index.cnt;
3019 h->top.FDArray.cnt = h->fdicts.cnt;
3020 h->top.FDArray.array = h->fdicts.array;
3021
3022 /* Validate dictionaries */
3023 if (h->stm.dbg == NULL)
3024 abfCheckAllDicts(NULL, &h->top);
3025 else {
3026 abfErrCallbacks cb;
3027 cb.ctx = h;
3028 cb.report_error = report_error;
3029 abfCheckAllDicts(&cb, &h->top);
3030 }
3031
3032 if (h->flags & CID_FONT) {
3033 /* CID-keyed font */
3034 h->top.sup.flags |= ABF_CID_FONT;
3035 h->top.sup.srcFontType = abfSrcFontTypeType1CID;
3036
3037 /* We pre-multiplied the FontMatrix's in the FDArray with the one in
3038 the top dict FontMatrix so we can discard it */
3039 h->top.cid.FontMatrix.cnt = ABF_EMPTY_ARRAY;
3040 return;
3041 }
3042
3043 /* Name-keyed font; set source font type */
3044 h->top.sup.srcFontType = abfSrcFontTypeType1Name;
3045
3046 /* Add strings to glyphs */
3047 for (i = 0; i < h->chars.index.cnt; i++)
3048 addStrPtr(h, &h->chars.index.array[i].gname);
3049
3050 /* Add glyph encodings */
3051 if (h->flags & STD_ENC) {
3052 /* Standard encoding */
3053 for (i = 0; i < h->chars.index.cnt; i++) {
3054 Char *chr = &h->chars.index.array[i];
3055 if ((STI)chr->gname.impl != STI_UNDEF) {
3056 int code = getStdEnc(h, (STI)chr->gname.impl);
3057 if (code != -1)
3058 encAdd(h, chr, code);
3059 }
3060 }
3061 } else {
3062 /* Custom encoding */
3063 for (i = 0; i < 256; i++) {
3064 STI sti = h->encoding.custom[i];
3065 if (sti != STI_UNDEF) {
3066 Char *chr = findChar(h, sti);
3067 if (chr != NULL)
3068 /* Char exists; add encoding */
3069 encAdd(h, chr, i);
3070 }
3071 }
3072 }
3073 }
3074
3075 /* Parse PostScript font. */
3076 int t1rBegFont(t1rCtx h, long flags, long origin, abfTopDict **top, float *UDV) {
3077 int result;
3078
3079 /* Set error handler */
3080 DURING_EX(h->err.env)
3081
3082 /* Initialize */
3083 h->flags = flags & 0xffff;
3084 abfInitTopDict(&h->top);
3085 dnaSET_CNT(h->FDArray, 1);
3086 dnaSET_CNT(h->fdicts, 1);
3087 initFDInfo(h, 0);
3088 h->fd = &h->FDArray.array[0];
3089 initChars(h);
3090 initStrings(h);
3091 initKeySeen(h);
3092 h->key.CIDMapOffset = -1;
3093 h->key.FDBytes = (unsigned)-1;
3094 h->key.GDBytes = (unsigned)-1;
3095 memset(h->encoding.standard, 0xff, sizeof(h->encoding.standard));
3096 h->mm.UDV = UDV;
3097 h->mm.WV.cnt = 0;
3098 h->mm.BDP.cnt = 0;
3099 h->mm.BDM.cnt = 0;
3100 h->mm.ForceBoldThreshold = 0.5;
3101 tmpInit(h);
3102
3103 /* Begin new parse */
3104 result = pstBegParse(h->pst, origin);
3105 if (result)
3106 pstFatal(h, result);
3107 if (flags & T1R_DUMP_TOKENS)
3108 pstSetDumpLevel(h->pst, 1);
3109
3110 /* Parse font */
3111 do {
3112 pstToken *token = getToken(h);
3113 retry:
3114 switch (token->type) {
3115 case pstLiteral:
3116 doLiteral(h, token);
3117 break;
3118 case pstOperator:
3119 doOperator(h, token);
3120 break;
3121 case pstString: {
3122 int binary;
3123
3124 /* Try to match possible StartData sequence */
3125 if (pstMatch(h->pst, token, "(Hex)"))
3126 binary = 0;
3127 else if (pstMatch(h->pst, token, "(Binary)"))
3128 binary = 1;
3129 else
3130 break; /* No match */
3131
3132 token = cidRead(h, binary);
3133 if (token != NULL)
3134 goto retry; /* No match */
3135 } break;
3136 default:
3137 break;
3138 }
3139 } while (!(h->flags & SEEN_END));
3140
3141 prepClientData(h);
3142 *top = &h->top;
3143
3144 HANDLER
3145 return Exception.Code;
3146 END_HANDLER
3147
3148 return t1rSuccess;
3149 }
3150
3151 /* End PostScript font parse. */
3152 int t1rEndFont(t1rCtx h) {
3153 int result = pstEndParse(h->pst);
3154 if (result) {
3155 message(h, "(pst) %s", pstErrStr(result));
3156 message(h, "%s", t1rErrStr(t1rErrPostScript));
3157 return t1rErrPostScript;
3158 }
3159 encListReuse(h);
3160 return t1rSuccess;
3161 }
3162
3163 /* Read charstring. */
3164 static void readGlyph(t1rCtx h,
3165 unsigned short tag, abfGlyphCallbacks *glyph_cb) {
3166 int result;
3167 long offset;
3168 long flags = h->flags;
3169 Char *chr = &h->chars.index.array[tag];
3170 t1cAuxData *aux = &h->FDArray.array[chr->iFD].aux;
3171
3172 if ((flags & CID_FONT) && !(flags & PRINT_STREAM)) {
3173 /* Unlike a name-keyed font the charstrings in a cid-keyed font aren't
3174 processed until the client requests a particular glyph via this
3175 function. In order to conserve space charstrings are normally
3176 overwritten because they are decrypted and saved to the same
3177 position in the tmp stream. However, the client can preserve them
3178 by setting the T1R_KEEP_CID_CSTRS flag. The following code handles
3179 this functionality. */
3180 char *cstr = readCstr(h, chr->sup.begin, chr->sup.end);
3181 long length = chr->sup.end - chr->sup.begin;
3182
3183 offset = h->tmpoff;
3184 if (flags & T1R_KEEP_CID_CSTRS) {
3185 /* Preserve charstrings */
3186 saveCstr(h, length, cstr, chr, 1);
3187 result = glyph_cb->beg(glyph_cb, chr);
3188 } else {
3189 /* Overwrite charstrings */
3190 long saveoff = chr->sup.begin;
3191
3192 tmpSeek(h, offset);
3193 saveCstr(h, length, cstr, chr, 0);
3194 h->tmpoff = offset;
3195
3196 /* Call client with temporary offset */
3197 chr->sup.begin = offset;
3198 chr->sup.end = chr->sup.begin + length;
3199 result = glyph_cb->beg(glyph_cb, chr);
3200 chr->sup.begin = saveoff;
3201 chr->sup.end = chr->sup.begin + length;
3202 }
3203 } else {
3204 offset = chr->sup.begin;
3205 result = glyph_cb->beg(glyph_cb, chr);
3206 }
3207
3208 /* Mark glyph as seen */
3209 chr->flags |= ABF_GLYPH_SEEN;
3210
3211 /* Check result */
3212 switch (result) {
3213 case ABF_CONT_RET:
3214 aux->flags &= ~T1C_WIDTH_ONLY;
3215 break;
3216 case ABF_WIDTH_RET:
3217 aux->flags |= T1C_WIDTH_ONLY;
3218 break;
3219 case ABF_SKIP_RET:
3220 return;
3221 case ABF_QUIT_RET:
3222 fatal(h, t1rErrCstrQuit, NULL);
3223 case ABF_FAIL_RET:
3224 fatal(h, t1rErrCstrFail, NULL);
3225 }
3226
3227 /* Parse charstring */
3228 result = t1cParse(offset, aux, glyph_cb);
3229 if (result) {
3230 if (chr->flags & ABF_GLYPH_CID)
3231 message(h, "(t1c) %s <cid-%hu>", t1cErrStr(result), chr->cid);
3232 else
3233 message(h, "(t1c) %s <%s>", t1cErrStr(result), chr->gname.ptr);
3234 fatal(h, t1rErrCstrParse, NULL);
3235 }
3236
3237 /* End glyph */
3238 glyph_cb->end(glyph_cb);
3239 }
3240
3241 /* Iterate through all glyphs in font. */
3242 int t1rIterateGlyphs(t1rCtx h, abfGlyphCallbacks *glyph_cb) {
3243 long i;
3244
3245 /* Set error handler */
3246 DURING_EX(h->err.env)
3247
3248 for (i = 0; i < h->chars.index.cnt; i++)
3249 readGlyph(h, (unsigned short)i, glyph_cb);
3250
3251 HANDLER
3252 return Exception.Code;
3253 END_HANDLER
3254
3255 return t1rSuccess;
3256 }
3257
3258 /* Get glyph from font by its tag. */
3259 int t1rGetGlyphByTag(t1rCtx h,
3260 unsigned short tag, abfGlyphCallbacks *glyph_cb) {
3261 if (tag >= h->chars.index.cnt)
3262 return t1rErrNoGlyph;
3263
3264 /* Set error handler */
3265 DURING_EX(h->err.env)
3266 readGlyph(h, tag, glyph_cb);
3267 HANDLER
3268 return Exception.Code;
3269 END_HANDLER
3270
3271 return t1rSuccess;
3272 }
3273
3274 /* Match glyph name after font fully parsed. */
3275 static int CTL_CDECL postMatchChar(const void *key, const void *value,
3276 void *ctx) {
3277 t1rCtx h = ctx;
3278 return strcmp((char *)key,
3279 h->chars.index.array[*(long *)value].gname.ptr);
3280 }
3281
3282 /* Get glyph from font by its name. */
3283 int t1rGetGlyphByName(t1rCtx h, char *gname, abfGlyphCallbacks *glyph_cb) {
3284 size_t index;
3285
3286 if (h->flags & CID_FONT)
3287 return t1rErrNoGlyph;
3288
3289 if (!ctuLookup(gname, h->chars.byName.array, h->chars.byName.cnt,
3290 sizeof(h->chars.byName.array[0]), postMatchChar, &index, h))
3291 return t1rErrNoGlyph;
3292
3293 /* Set error handler */
3294 DURING_EX(h->err.env)
3295
3296 readGlyph(h, (unsigned short)h->chars.byName.array[index], glyph_cb);
3297
3298 HANDLER
3299 return Exception.Code;
3300 END_HANDLER
3301
3302 return t1rSuccess;
3303 }
3304
3305 /* Match CID value. */
3306 static int CTL_CDECL matchCID(const void *key, const void *value) {
3307 unsigned short a = *(unsigned short *)key;
3308 unsigned short b = ((Char *)value)->cid;
3309 if (a < b)
3310 return -1;
3311 else if (a > b)
3312 return 1;
3313 else
3314 return 0;
3315 }
3316
3317 /* Get glyph from font by its CID. */
3318 int t1rGetGlyphByCID(t1rCtx h,
3319 unsigned short cid, abfGlyphCallbacks *glyph_cb) {
3320 volatile unsigned short tag; /* volatile suppresses optimizer warning */
3321
3322 if (!(h->flags & CID_FONT))
3323 return t1rErrNoGlyph;
3324
3325 if (h->chars.index.array[h->chars.index.cnt - 1].cid ==
3326 h->chars.index.cnt - 1) {
3327 /* Non-subset font; index by CID */
3328 if (cid >= h->chars.index.cnt)
3329 return t1rErrNoGlyph;
3330 else
3331 tag = cid;
3332 } else {
3333 /* Subset font; search for matching CID */
3334 Char *chr =
3335 (Char *)bsearch(&cid, h->chars.index.array,
3336 h->chars.index.cnt, sizeof(Char), matchCID);
3337 if (chr == NULL)
3338 return t1rErrNoGlyph;
3339 else
3340 /* 64-bit warning fixed by cast here HO */
3341 tag = (unsigned short)(chr - h->chars.index.array);
3342 }
3343
3344 /* Set error handler */
3345 DURING_EX(h->err.env)
3346
3347 readGlyph(h, tag, glyph_cb);
3348
3349 HANDLER
3350 return Exception.Code;
3351 END_HANDLER
3352
3353 return t1rSuccess;
3354 }
3355
3356 /* Get standard-encoded glyph from font. */
3357 int t1rGetGlyphByStdEnc(t1rCtx h, int stdcode, abfGlyphCallbacks *glyph_cb) {
3358 unsigned short tag = 0; /* Suppress optimizer warning */
3359
3360 if (stdcode < 0 || stdcode >= 256 ||
3361 (tag = h->encoding.standard[stdcode]) == 0xffff)
3362 return t1rErrNoGlyph;
3363
3364 /* Set error handler */
3365 DURING_EX(h->err.env)
3366
3367 readGlyph(h, tag, glyph_cb);
3368
3369 HANDLER
3370 return Exception.Code;
3371 END_HANDLER
3372
3373 return t1rSuccess;
3374 }
3375
3376 /* Clear record of glyphs seen by client. */
3377 int t1rResetGlyphs(t1rCtx h) {
3378 long i;
3379
3380 for (i = 0; i < h->chars.index.cnt; i++)
3381 h->chars.index.array[i].flags &= ~ABF_GLYPH_SEEN;
3382
3383 if (h->top.sup.flags & ABF_CID_FONT)
3384 {
3385 /* If the font is a Type1 CID font, the charstrings must be read
3386 when building a subset, in order to get the FD index. When a CID
3387 charstring is read, it is decrypted in place in the src buffer.
3388 If the total charstrings are smaller than the src buffer, then
3389 when the glyph data is later read again when the subset is
3390 applied, the charstring data is just copied from the buffer.
3391 However, they are now decrypted, leading to parsing failure. Set
3392 the buffer length to 0 so that the src charstring data will get
3393 reloaded again. */
3394 h->src.offset = 0;
3395 h->src.length = 0;
3396 }
3397
3398 return t1rSuccess;
3399 }
3400
3401 /* Return Weight Vector. */
3402 const float *t1rGetWV(t1rCtx h, long *nMasters) {
3403 if (h->fd->aux.nMasters == 1) {
3404 *nMasters = 0;
3405 return NULL;
3406 } else {
3407 *nMasters = h->fd->aux.nMasters;
3408 return h->fd->aux.WV;
3409 }
3410 }
3411
3412 /* Get subrs info. */
3413 const ctlSubrs *t1rGetSubrs(t1rCtx h, int iFD, const ctlRegion **region) {
3414 if (iFD < 0 || iFD >= h->FDArray.cnt) {
3415 *region = NULL;
3416 return NULL;
3417 } else {
3418 FDInfo *fd = &h->FDArray.array[iFD];
3419 *region = &fd->subrs.region;
3420 return &fd->aux.subrs;
3421 }
3422 }
3423
3424 /* Get version numbers of libraries. */
3425 void t1rGetVersion(ctlVersionCallbacks *cb) {
3426 if (cb->called & 1 << T1R_LIB_ID)
3427 return; /* Already enumerated */
3428
3429 /* Support libraries */
3430 abfGetVersion(cb);
3431 ctuGetVersion(cb);
3432 dnaGetVersion(cb);
3433 pstGetVersion(cb);
3434 t1cGetVersion(cb);
3435
3436 /* This library */
3437 cb->getversion(cb, T1R_VERSION, "t1read");
3438
3439 /* Record this call */
3440 cb->called |= 1 << T1R_LIB_ID;
3441 }
3442
3443 /* ----------------------------- Error Support ----------------------------- */
3444
3445 /* Map error code to error string. */
3446 char *t1rErrStr(int err_code) {
3447 static char *errstrs[] =
3448 {
3449 #undef CTL_DCL_ERR
3450 #define CTL_DCL_ERR(name, string) string,
3451 #include "t1rerr.h"
3452 };
3453 return (err_code < 0 || err_code >= (int)ARRAY_LEN(errstrs)) ? "unknown error" : errstrs[err_code];
3454 }
3455
3456 /* ----------------------------- Debug Support ----------------------------- */
3457
3458 #if T1R_DEBUG
3459
3460 /* Dump string table. */
3461 static void dbstrs(t1rCtx h) {
3462 long i;
3463 printf("--- strings [index]=<string>\n");
3464 for (i = 0; i < h->strings.index.cnt; i++)
3465 printf("[%03ld]=<%s>\n", i, getString(h, (STI)i));
3466 }
3467
3468 /* Dump char table. */
3469 static void dbchars(t1rCtx h) {
3470 long i;
3471 if (h->flags & CID_FONT)
3472 printf("--- chars [tag]={offset,cid,iFD}\n");
3473 else
3474 printf("--- chars [tag]={offset,code[+code]+,gname}\n");
3475 for (i = 0; i < h->chars.index.cnt; i++) {
3476 Char *chr = &h->chars.index.array[i];
3477
3478 printf("[%05hu]={%05ld,", chr->tag, chr->sup.begin);
3479 if (chr->flags & ABF_GLYPH_CID)
3480 ;
3481 else {
3482 /* Print encoding */
3483 abfEncoding *enc = &chr->encoding;
3484 if (enc->code == ABF_GLYPH_UNENC)
3485 printf("-");
3486 else {
3487 printf("0x%02lx", enc->code);
3488 for (;;) {
3489 enc = enc->next;
3490 if (enc == NULL)
3491 break;
3492 printf("+0x%02lx", enc->code);
3493 }
3494 }
3495 }
3496
3497 /* Name-keyed glyph; print gname */
3498 if (chr->gname.impl == ABF_UNSET_INT)
3499 printf(",-}\n");
3500 else
3501 printf(",%s}\n", getString(h, (STI)chr->gname.impl));
3502 }
3503 }
3504
3505 /* Dump encoding. */
3506 static void dbencs(t1rCtx h) {
3507 printf("--- encoding\n");
3508 if (h->flags & STD_ENC)
3509 printf("StandardEncoding\n");
3510 else {
3511 int i;
3512 for (i = 0; i < 256; i++) {
3513 STI sti = h->encoding.custom[i];
3514 printf("[%d]=<%s> ", i,
3515 (sti == STI_UNDEF) ? "-unenc-" : getString(h, sti));
3516 }
3517 printf("\n");
3518 }
3519 }
3520
3521 /* This function just serves to suppress annoying "defined but not used"
3522 compiler messages when debugging. */
3523 static void CTL_CDECL dbuse(int arg, ...) {
3524 dbuse(0, dbstrs, dbchars, dbencs);
3525 }
3526
3527 #endif /* T1R_DEBUG */