Debian Codegraph @

podofo/3rdparty/adobe/afdko/source/cffread/cffread.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 * Compact Font Format (CFF) parser.
7 */
8
9 #include "cffread.h"
10 #include "dynarr.h"
11 #include "t2cstr.h"
12 #include "dictops.h"
13 #include "txops.h"
14 #include "ctutil.h"
15 #include "sfntread.h"
16 #include "nameread.h"
17 #include "varread.h"
18 #include "supportfp.h"
19 #include "supportexcept.h"
20
21 #include <string.h>
22 #include <stdlib.h>
23 #include <limits.h>
24 #include <math.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <ctype.h>
28
29 /* Predefined encodings */
30 static const uint8_t stdenc[] =
31 {
32 #include "stdenc0.h"
33 };
34 static const uint8_t exenc[] =
35 {
36 #include "exenc0.h"
37 };
38
39 static char *stdstrs[] =
40 {
41 #include "stdstr1.h"
42 };
43
44 /* Glyph names for Standard Apple Glyph Ordering */
45 static char *applestd[258] =
46 {
47 #include "applestd.h"
48 };
49
50 #define SHORT_PS_NAME_LIMIT 63 /* according to the OpenType name table spec */
51 #define LONG_PS_NAME_LIMIT 127 /* according to Adobe tech notes #5902 */
52 #define STRING_BUFFER_LIMIT 1024 /* used to load family name/full name/copyright/trademark strings */
53 #define SUBR_INDEX_CNT_LIMIT 67108864 /* limit subrINDEX cnt to avoid large memory allocations */
54
55 #define ARRAY_LEN(t) (sizeof(t) / sizeof((t)[0]))
56
57 typedef uint8_t OffSize; /* Offset size indicator */
58 typedef long Offset; /* 1, 2, 3, or 4-byte offset */
59 typedef unsigned short SID; /* String identifier */
60 #define SID_SIZE 2 /* SID byte size */
61
62 typedef struct /* INDEX */
63 {
64 unsigned long count; /* Element count */
65 OffSize offSize; /* Offset size */
66 Offset offset; /* Offset start */
67 Offset data; /* Data start - 1 */
68 unsigned bias; /* Subr number bias */
69 } INDEX;
70
71 typedef dnaDCL(long, SubrOffsets); /* Subr charstring offsets */
72
73 typedef struct /* FDArray element */
74 {
75 unsigned long flags;
76 #define SEEN_BLUE_VALUES (1 << 0) /* Flags BlueValues operator seen */
77 cfrRepeatRegions region;
78 SubrOffsets Subrs; /* Local subr offsets */
79 t2cAuxData aux; /* Auxiliary charstring parse data */
80 abfFontDict *fdict; /* Abstract font data */
81 } cfrFDInfo;
82
83 typedef struct /* Operand Stack element */
84 {
85 int is_int;
86 union {
87 int32_t int_val; /* allow at least 32-bit int */
88 float real_val;
89 } u;
90 unsigned short numBlends; /* The last operand before the blend operator. */
91 /* The number of items in blend_val is numBlends*(h->numRegions). */
92 float *blend_val; /* NULL unless the blend operator has been encountered. */
93 } stack_elem;
94
95 typedef struct /* Format 2.0 data */
96 {
97 dnaDCL(unsigned short, glyphNameIndex);
98 dnaDCL(char *, strings);
99 dnaDCL(char, buf);
100 } postFmt2;
101
102 typedef short FWord;
103
104 typedef struct /* post table */
105 {
106 Fixed format; /* =1.0, 2.0, 2.5, 3.0, 4.0 */
107 Fixed italicAngle;
108 FWord underlinePosition;
109 FWord underlineThickness;
110 unsigned long isFixedPitch;
111 unsigned long minMemType42;
112 unsigned long maxMemType42;
113 unsigned long minMemType1;
114 unsigned long maxMemType1;
115 postFmt2 fmt2;
116 } postTbl;
117
118 struct cfrCtx_ /* Context */
119 {
120 long flags; /* Status flags */
121 #define CID_FONT (1UL << 31) /* CID Font */
122 #define FREE_ENCODINGS (1UL << 30) /* Return encoding nodes to free list */
123 #define CFR_SEEN_BLEND (1 << 29)
124 #define CFR_IS_CFF2 (1 << 28)
125 cfrSingleRegions region;
126 struct /* CFF header */
127 {
128 uint8_t major;
129 uint8_t minor;
130 uint8_t hdrSize;
131 OffSize offSize;
132 } header;
133 struct /* INDEXes */
134 {
135 INDEX name;
136 INDEX top;
137 INDEX string;
138 INDEX FDArray;
139 } index;
140 SubrOffsets gsubrs; /* Global subr offsets */
141 abfTopDict top; /* Top dict */
142 dnaDCL(cfrFDInfo, FDArray); /* FDArray */
143 dnaDCL(abfFontDict, fdicts); /* Font Dicts */
144 cfrFDInfo *fd; /* Active Font Dict */
145 struct /* DICT operand stack */
146 {
147 /* Operands are pushed on the stack as they are encountered. However,
148 when the 'blend' operator is called, the stack is edited. See the
149 comment in copyToBlendStackElement() for what is done. */
150 int cnt;
151 int numRegions; /* current number of regions ( 1 less than the */
152 /* number of source master designs), defined by the */
153 /* varData structure which is selected by the */
154 /* current vsindex into the VarStore. */
155 stack_elem array[CFF2_MAX_OP_STACK];
156 } stack;
157 struct /* String data */
158 {
159 dnaDCL(Offset, offsets);
160 dnaDCL(char *, ptrs);
161 dnaDCL(char, buf);
162 } string;
163 dnaDCL(abfGlyphInfo, glyphs); /* Glyph data */
164 dnaDCL(unsigned short, glyphsByName); /* Glyphs sorted by name */
165 dnaDCL(unsigned short, glyphsByCID); /* Glyphs sorted by cid */
166 struct /* Streams */
167 {
168 void *src;
169 void *dbg;
170 } stm;
171 struct /* Source stream */
172 {
173 Offset origin; /* Origin offset of font */
174 Offset offset; /* Buffer offset */
175 size_t length; /* Buffer length */
176 char *buf; /* Buffer beginning */
177 char *end; /* Buffer end */
178 char *next; /* Next byte available (buf <= next < end) */
179 } src;
180 unsigned short stdEnc2GID[256]; /* Map standard encoding to GID */
181 abfEncoding *encfree; /* Supplementary encoding free list */
182 postTbl post; /* post table */
183 struct /* CFF2 font tables */
184 {
185 float *UDV; /* From client */
186 Fixed ndv[CFF2_MAX_AXES]; /* normalized weight vector */
187 float scalars[CFF2_MAX_MASTERS]; /* scalar values for regions */
188 unsigned short regionListCount; /* number of all regions */
189 unsigned short regionIndices[CFF2_MAX_MASTERS]; /* region indices for the current vsindex */
190
191 unsigned short axisCount;
192 var_axes axes;
193 var_hmtx hmtx;
194 var_MVAR mvar;
195 nam_name name;
196 var_itemVariationStore varStore;
197 void *lastResortInstanceNameClientCtx;
198 cfrlastResortInstanceNameCallback lastResortInstanceNameCallback;
199 } cff2;
200 struct /* Client callbacks */
201 {
202 ctlMemoryCallbacks mem;
203 ctlStreamCallbacks stm;
204 cff2GlyphCallbacks cff2;
205 ctlSharedStmCallbacks shstm;
206 } cb;
207 struct /* Contexts */
208 {
209 dnaCtx dna; /* dynarr */
210 sfrCtx sfr; /* sfntread */
211 } ctx;
212 struct /* Error handling */
213 {
214 _Exc_Buf env;
215 } err;
216 };
217
218 static void encListFree(cfrCtx h, abfEncoding *node);
219 static void setupSharedStream(cfrCtx h);
220
221 /* ----------------------------- Error Handling ---------------------------- */
222
223 /* Write message to debug stream from va_list. */
224 static void vmessage(cfrCtx h, char *fmt, va_list ap) {
225 char text[500];
226 if (h->stm.dbg == NULL)
227 return; /* Debug stream not available */
228
229 VSPRINTF_S(text, sizeof(text), fmt, ap);
230 (void)h->cb.stm.write(&h->cb.stm, h->stm.dbg, strlen(text), text);
231 }
232
233 /* Write message to debug stream from varargs. */
234 static void CTL_CDECL message(cfrCtx h, char *fmt, ...) {
235 va_list ap;
236 va_start(ap, fmt);
237 vmessage(h, fmt, ap);
238 va_end(ap);
239 }
240
241 /* Handle fatal error. */
242 static void fatal(cfrCtx h, int err_code) {
243 message(h, "%s", cfrErrStr(err_code));
244 RAISE(&h->err.env, err_code, NULL);
245 }
246
247 /* --------------------------- Memory Management --------------------------- */
248
249 /* Allocate memory. */
250 static void *memNew(cfrCtx h, size_t size) {
251 void *ptr = h->cb.mem.manage(&h->cb.mem, NULL, size);
252 if (ptr == NULL) {
253 fatal(h, cfrErrNoMemory);
254 } else {
255 /* Safety initialization */
256 memset(ptr, 0, size);
257 }
258 return ptr;
259 }
260
261 /* Free memory. */
262 static void memFree(cfrCtx h, void *ptr) {
263 h->cb.mem.manage(&h->cb.mem, ptr, 0);
264 }
265
266 /* -------------------------- Safe dynarr Context -------------------------- */
267
268 /* Manage memory. */
269 static void *dna_manage(ctlMemoryCallbacks *cb, void *old, size_t size) {
270 cfrCtx h = (cfrCtx)cb->ctx;
271 void *ptr = h->cb.mem.manage(&h->cb.mem, old, size);
272 if (size > 0 && ptr == NULL)
273 fatal(h, cfrErrNoMemory);
274 return ptr;
275 }
276
277 /* Initialize error handling dynarr context. */
278 static void dna_init(cfrCtx h) {
279 ctlMemoryCallbacks cb;
280 cb.ctx = h;
281 cb.manage = dna_manage;
282 h->ctx.dna = dnaNew(&cb, DNA_CHECK_ARGS);
283 }
284
285 /* --------------------------- Context Management -------------------------- */
286
287 /* Initialize FDArray element. */
288 static void initFDArray(void *ctx, long cnt, cfrFDInfo *info) {
289 cfrCtx h = (cfrCtx)ctx;
290 while (cnt--) {
291 memset(info, 0, sizeof(*info));
292 dnaINIT(h->ctx.dna, info->Subrs, 200, 100);
293 info++;
294 }
295 }
296
297 /* Validate client and create context. */
298 cfrCtx cfrNew(ctlMemoryCallbacks *mem_cb, ctlStreamCallbacks *stm_cb,
299 CTL_CHECK_ARGS_DCL) {
300 cfrCtx h;
301
302 /* Check client/library compatibility */
303 if (CTL_CHECK_ARGS_TEST(CFR_VERSION))
304 return NULL;
305
306 /* Allocate context */
307 h = (cfrCtx)mem_cb->manage(mem_cb, NULL, sizeof(struct cfrCtx_));
308 if (h == NULL)
309 return NULL;
310
311 /* Safety initialization */
312 memset(h, 0, sizeof(*h));
313
314 /* Copy callbacks */
315 h->cb.mem = *mem_cb;
316 h->cb.stm = *stm_cb;
317
318 /* Set error handler */
319 DURING_EX(h->err.env)
320
321 /* Initialize service libraries */
322 dna_init(h);
323 h->ctx.sfr = sfrNew(mem_cb, stm_cb, SFR_CHECK_ARGS);
324 if (h->ctx.sfr == NULL)
325 fatal(h, cfrErrSfntread);
326
327 /* Initialize */
328 dnaINIT(h->ctx.dna, h->gsubrs, 200, 100);
329 dnaINIT(h->ctx.dna, h->FDArray, 1, 13);
330 h->FDArray.func = initFDArray;
331 dnaINIT(h->ctx.dna, h->fdicts, 1, 13);
332 dnaINIT(h->ctx.dna, h->glyphs, 256, 768);
333 dnaINIT(h->ctx.dna, h->glyphsByName, 256, 768);
334 dnaINIT(h->ctx.dna, h->glyphsByCID, 256, 768);
335 dnaINIT(h->ctx.dna, h->post.fmt2.glyphNameIndex, 256, 768);
336 dnaINIT(h->ctx.dna, h->post.fmt2.strings, 50, 200);
337 dnaINIT(h->ctx.dna, h->post.fmt2.buf, 300, 1200);
338 dnaINIT(h->ctx.dna, h->string.offsets, 16, 256);
339 dnaINIT(h->ctx.dna, h->string.ptrs, 16, 256);
340 dnaINIT(h->ctx.dna, h->string.buf, 200, 2000);
341
342 /* Open optional debug stream */
343 h->stm.dbg = h->cb.stm.open(&h->cb.stm, CFR_DBG_STREAM_ID, 0);
344
345 /* Set up shared source stream callbacks */
346 setupSharedStream(h);
347
348 HANDLER
349 /* Initialization failed */
350 cfrFree(h);
351 h = NULL;
352 END_HANDLER
353
354 return h;
355 }
356
357 static void freeBlend(cfrCtx h, abfOpEntry *blend) {
358 if (blend->blendValues != NULL) {
359 memFree(h, blend->blendValues);
360 blend->blendValues = NULL;
361 }
362 }
363
364 static void freeBlendArray(cfrCtx h, abfOpEntryArray *blendArray) {
365 long i;
366 for (i = 0; i < blendArray->cnt; i++)
367 freeBlend(h, &blendArray->array[i]);
368 }
369
370 static void freePrivateBlends(cfrCtx h, abfPrivateDict *priv) {
371 freeBlend(h, &priv->blendValues.StdHW);
372 freeBlend(h, &priv->blendValues.StdVW);
373 freeBlend(h, &priv->blendValues.BlueScale);
374 freeBlend(h, &priv->blendValues.BlueShift);
375 freeBlend(h, &priv->blendValues.BlueFuzz);
376 freeBlendArray(h, &priv->blendValues.BlueValues);
377 freeBlendArray(h, &priv->blendValues.OtherBlues);
378 freeBlendArray(h, &priv->blendValues.FamilyBlues);
379 freeBlendArray(h, &priv->blendValues.FamilyOtherBlues);
380 freeBlendArray(h, &priv->blendValues.StemSnapH);
381 freeBlendArray(h, &priv->blendValues.StemSnapV);
382 }
383
384 /* Free library context. */
385 void cfrFree(cfrCtx h) {
386 int i;
387
388 if (h == NULL)
389 return;
390
391 /* Free dynamic arrays */
392 for (i = 0; i < h->FDArray.size; i++) {
393 dnaFREE(h->FDArray.array[i].Subrs);
394 }
395
396 /* Free dynamic arrays */
397 for (i = 0; i < h->FDArray.cnt; i++) {
398 if (h->FDArray.array[i].fdict)
399 freePrivateBlends(h, &h->FDArray.array[i].fdict->Private);
400 }
401
402 dnaFREE(h->gsubrs);
403 dnaFREE(h->FDArray);
404 dnaFREE(h->fdicts);
405 dnaFREE(h->glyphs);
406 dnaFREE(h->glyphsByName);
407 dnaFREE(h->glyphsByCID);
408 dnaFREE(h->post.fmt2.glyphNameIndex);
409 dnaFREE(h->post.fmt2.strings);
410 dnaFREE(h->post.fmt2.buf);
411 dnaFREE(h->string.offsets);
412 dnaFREE(h->string.ptrs);
413 dnaFREE(h->string.buf);
414
415 if (h->cff2.varStore != NULL) {
416 /* Call this here rather than end cfrEndFont, so that
417 the allocated memory will be available to any client modules
418 */
419 var_freeItemVariationStore(&h->cb.shstm, h->cff2.varStore);
420 }
421
422 encListFree(h, h->encfree);
423
424 dnaFree(h->ctx.dna);
425 sfrFree(h->ctx.sfr);
426
427 /* Close debug stream */
428 if (h->stm.dbg != NULL)
429 (void)h->cb.stm.close(&h->cb.stm, h->stm.dbg);
430
431 /* Free library context */
432 h->cb.mem.manage(&h->cb.mem, h, 0);
433 }
434
435 /* ----------------------------- Source Stream ----------------------------- */
436
437 /* Fill source buffer. */
438 static void fillbuf(cfrCtx h, long offset) {
439 h->src.length = h->cb.stm.read(&h->cb.stm, h->stm.src, &h->src.buf);
440 if (h->src.length == 0)
441 fatal(h, cfrErrSrcStream);
442 h->src.offset = offset;
443 h->src.next = h->src.buf;
444 h->src.end = h->src.buf + h->src.length;
445 }
446
447 /* Perform initial seek and buffer fill. */
448 static void seekbuf(cfrCtx h, long offset) {
449 if (h->cb.stm.seek(&h->cb.stm, h->stm.src, offset))
450 fatal(h, cfrErrSrcStream);
451 fillbuf(h, offset);
452 }
453
454 /* Read next sequential source buffer; update offset and return first byte. */
455 static char nextbuf(cfrCtx h) {
456 /* 64-bit warning fixed by cast here */
457 fillbuf(h, (int32_t)(h->src.offset + h->src.length));
458 return *h->src.next++;
459 }
460
461 /* Seek to specified offset. */
462 static void srcSeek(cfrCtx h, long offset) {
463 long delta = offset - h->src.offset;
464 if (delta >= 0 && (size_t)delta < h->src.length)
465 /* Offset within current buffer; reposition next byte */
466 h->src.next = h->src.buf + delta;
467 else
468 /* Offset outside current buffer; seek to offset and fill buffer */
469 seekbuf(h, offset);
470 }
471
472 /* Return absolute byte position in stream. */
473 #define srcTell(h) (h->src.offset + (h->src.next - h->src.buf))
474
475 /* Copy count bytes from source stream. */
476 static void srcRead(cfrCtx h, size_t count, char *ptr) {
477 size_t left = h->src.end - h->src.next;
478
479 while (left < count) {
480 /* Copy buffer */
481 memcpy(ptr, h->src.next, left);
482 ptr += left;
483 count -= left;
484
485 /* Refill buffer */
486 /* 64-bit warning fixed by cast here */
487 fillbuf(h, (int32_t)(h->src.offset + h->src.length));
488 left = h->src.length;
489 }
490
491 memcpy(ptr, h->src.next, count);
492 h->src.next += count;
493 }
494
495 /* Read 1-byte unsigned number. */
496 #define read1(h) \
497 ((uint8_t)((h->src.next == h->src.end) ? nextbuf(h) : *h->src.next++))
498
499 /* Read 2-byte number. */
500 static uint16_t read2(cfrCtx h) {
501 uint16_t value = (uint16_t)read1(h) << 8;
502 return value | (uint16_t)read1(h);
503 }
504
505 /* Read 1-, 2-, 3-, or 4-byte number. */
506 static uint32_t readN(cfrCtx h, int N) {
507 uint32_t value = 0;
508 switch (N) {
509 default:
510 fatal(h, cfrErrINDEXHeader);
511 break;
512 case 4:
513 value = read1(h);
514 case 3:
515 value = value << 8 | read1(h);
516 case 2:
517 value = value << 8 | read1(h);
518 case 1:
519 value = value << 8 | read1(h);
520 }
521 return value;
522 }
523
524 /* Open source stream. */
525 static void srcOpen(cfrCtx h, long flags, long origin, int ttcIndex) {
526 int i;
527 int result;
528 ctlTag sfnt_tag;
529 long offset = origin;
530
531 h->stm.src = h->cb.stm.open(&h->cb.stm, CFR_SRC_STREAM_ID, 0);
532 if (h->stm.src == NULL)
533 fatal(h, cfrErrSrcStream);
534 /* Parse stream as sfnt */
535 readhdr:
536 /* Read sfnt header */
537 result = sfrBegFont(h->ctx.sfr, h->stm.src, offset, &sfnt_tag);
538 /* If it looks like an SFNT, use the logic for OTF and TTC.*/
539 if (result == sfrSuccess) {
540 switch (sfnt_tag) {
541 case sfr_ttcf_tag:
542 /* Get i'th TrueType Collection offset */
543 for (i = 0; (offset = sfrGetNextTTCOffset(h->ctx.sfr)) != 0; i++)
544 if (i == ttcIndex) {
545 ttcIndex = 0;
546 goto readhdr;
547 }
548 fatal(h, cfrErrSfntread);
549 case sfr_OTTO_tag:
550 if (ttcIndex != 0)
551 fatal(h, cfrErrSfntread);
552 break;
553 case sfr_true_tag:
554 if (ttcIndex != 0)
555 fatal(h, cfrErrSfntread);
556 break;
557 default:
558 fatal(h, cfrErrSfntread);
559 }
560
561 switch (result) {
562 case sfrSuccess:
563 if (sfnt_tag == sfr_OTTO_tag) {
564 /* OTF; use CFF table offset */
565 sfrTable *table = NULL;
566 if (!(flags & CFR_CFF2_ONLY))
567 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('C', 'F', 'F', ' '));
568 if (table == NULL) {
569 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('C', 'F', 'F', '2'));
570 }
571 if (table == NULL) {
572 fatal(h, cfrErrNoCFF);
573 } else {
574 origin = table->offset;
575 }
576
577 /* Try to read OS/2.fsType */
578 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('O', 'S', '/', '2'));
579 if (table != NULL) {
580 seekbuf(h, table->offset + 4 * 2);
581 h->top.FSType = read2(h);
582 }
583
584 /* See if its a SING glyphlet */
585 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('n', 'a', 'm', 'e'));
586 if (table == NULL) {
587 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('S', 'I', 'N', 'G'));
588 if (table != NULL) {
589 /* Read "permissions" field as FSType */
590 seekbuf(h, table->offset + 3 * 2);
591 h->top.FSType = read2(h);
592 h->top.sup.flags |= ABF_SING_FONT;
593 }
594 }
595 } else
596 fatal(h, cfrErrBadFont);
597 break;
598 case sfrErrBadSfnt:
599 break; /* Not a recognized sfnt; assume naked CFF */
600 default:
601 fatal(h, cfrErrSfntread);
602 }
603 }
604 /* Read first buffer */
605 seekbuf(h, origin);
606 h->src.origin = origin;
607 }
608
609 /* ------------------------------ DICT Parsing ----------------------------- */
610
611 /* Check stack contains at least n elements. */
612 #define CHKUFLOW(n) \
613 do \
614 if (h->stack.cnt < (n)) fatal(h, cfrErrStackUnderflow); \
615 while (0)
616
617 /* Check stack has room for n elements. */
618 #define CHKOFLOW(n) \
619 do \
620 if (h->stack.cnt + (n) > h->top.maxstack) fatal(h, cfrErrStackOverflow); \
621 while (0)
622
623 /* Check that dict has enough bytes left. */
624 #define CHECK_DICT_BYTES_LEFT(n) \
625 do \
626 if ((srcTell(h) + n) > region->end) \
627 fatal(h, cfrErrSrcStream); \
628 while (0)
629
630 /* Stack access without check. */
631 #define INDEX(i) (h->stack.array[i])
632 #define INDEX_INT(i) (INDEX(i).is_int ? INDEX(i).u.int_val : (int32_t)INDEX(i).u.real_val)
633 #define PUSH_INT(v) \
634 { \
635 stack_elem *elem = &h->stack.array[h->stack.cnt++]; \
636 elem->is_int = 1; \
637 elem->u.int_val = (v); \
638 elem->numBlends = 0; \
639 }
640 #define INDEX_REAL(i) (INDEX(i).is_int ? (float)INDEX(i).u.int_val : INDEX(i).u.real_val)
641 #define PUSH_REAL(v) \
642 { \
643 stack_elem *elem = &h->stack.array[h->stack.cnt++]; \
644 elem->is_int = 0; \
645 elem->u.real_val = (v); \
646 elem->numBlends = 0; \
647 }
648
649 /* Save font transformation matrix. */
650 static void saveMatrix(cfrCtx h, int topdict) {
651 float array[6];
652
653 CHKUFLOW(6);
654
655 array[0] = INDEX_REAL(0);
656 array[1] = INDEX_REAL(1);
657 array[2] = INDEX_REAL(2);
658 array[3] = INDEX_REAL(3);
659 array[4] = INDEX_REAL(4);
660 array[5] = INDEX_REAL(5);
661
662 if (topdict && h->flags & CID_FONT) {
663 /* Top-level CIDFont matrix */
664 if (array[0] != 1.0 ||
665 array[1] != 0.0 ||
666 array[2] != 0.0 ||
667 array[3] != 1.0 ||
668 array[4] != 0.0 ||
669 array[5] != 0.0) {
670 /* Save matrix if not identity */
671 memcpy(h->top.cid.FontMatrix.array, array, 6 * sizeof(float));
672 h->top.cid.FontMatrix.cnt = 6;
673 }
674 } else {
675 /* Font dict matrix */
676 float *result = h->fd->fdict->FontMatrix.array;
677
678 if (h->top.cid.FontMatrix.cnt != ABF_EMPTY_ARRAY) {
679 /* Form product of top and FDArray matrices */
680 float *a = h->top.cid.FontMatrix.array;
681 float *b = array;
682
683 result[0] = a[0] * b[0] + a[1] * b[2];
684 result[1] = a[0] * b[1] + a[1] * b[3];
685 result[2] = a[2] * b[0] + a[3] * b[2];
686 result[3] = a[2] * b[1] + a[3] * b[3];
687 result[4] = a[4] * b[0] + a[5] * b[2] + b[4];
688 result[5] = a[4] * b[1] + a[5] * b[3] + b[5];
689 } else
690 /* Copy matrix */
691 memcpy(result, array, 6 * sizeof(float));
692
693 if (result[0] != 0.001f ||
694 result[1] != 0.0 ||
695 result[2] != 0.0 ||
696 result[3] != 0.001f ||
697 result[4] != 0.0 ||
698 result[5] != 0.0) {
699 /* Non-default matrix */
700 float max;
701 int i;
702
703 /* Make matrix available */
704 h->fd->fdict->FontMatrix.cnt = 6;
705
706 /* Find the largest of a, b, c, and d */
707 max = 0.0;
708 for (i = 0; i < 4; i++) {
709 float value = result[i];
710 if (value < 0.0)
711 value = -value;
712 if (value > max)
713 max = value;
714 }
715 if (max == 0.0)
716 fatal(h, cfrErrFontMatrix);
717
718 /* Calculate units-per-em */
719 h->top.sup.UnitsPerEm = (unsigned short)(1.0 / max + 0.5);
720
721 if (h->flags & CFR_USE_MATRIX) {
722 /* Prepare charstring transformation matrix */
723 for (i = 0; i < 6; i++)
724 h->fd->aux.matrix[i] = result[i] * h->top.sup.UnitsPerEm;
725 h->fd->aux.flags |= T2C_USE_MATRIX;
726 }
727 }
728 }
729 }
730
731 /* Convert BCD number to double. */
732 static double convBCD(cfrCtx h, ctlRegion *region) {
733 double result;
734 char *p;
735 char buf[64];
736 int byte = 0; /* Suppress optimizer warning */
737 int i = 0;
738 int count = 0;
739
740 /* Construct string representation of number */
741 for (;;) {
742 int nibble;
743
744 if (count++ & 1)
745 nibble = byte & 0xf;
746 else {
747 CHECK_DICT_BYTES_LEFT(1);
748 byte = read1(h);
749 nibble = byte >> 4;
750 }
751
752 if (nibble == 0xf)
753 break;
754 else if (nibble == 0xd || i >= (int)sizeof(buf) - 2)
755 fatal(h, cfrErrBCDArg);
756 else {
757 buf[i++] = "0123456789.EE?-?"[nibble];
758 if (nibble == 0xc)
759 buf[i++] = '-'; /* Negative exponent */
760 }
761 }
762 buf[i] = '\0';
763
764 result = ctuStrtod(buf, &p);
765 if (*p != '\0')
766 fatal(h, cfrErrBCDArg);
767
768 return result;
769 }
770
771 static void handleBlend(cfrCtx h) {
772 /* When the CFF2 blend operator is encountered, the last items on the stack are
773 the blend operands. These are in order:
774 numBlends operands from the default font
775 (numMaster-1)* numBlends blend delta operands
776 numBlends value
777
778 What we do is to find the first blend operand item, which is the first value from the
779 default font. We assign numBlends to the field of the same name in this struct_elem, and pop
780 it off the stack. We then allocate memory to hold the (numMaster-1)* numBlends blend delta operands,
781 and copy them to the blendValues field. We then pop the (numMaster-1)* numBlends blend delta operands,
782 leaving the numBlends operands.
783 When an operator is encountered, a handler that does not know about the blend values will
784 simply see the usual stack values from the default fonts. A handler which does know about
785 the blend values can use the blend values to fill the blendable fields.
786
787 Alternatively, the blend handler can use the blend operands to actually produce blended values,
788 and replace the numBlends operands from the defaultfont with the blended values.
789 */
790
791 int numBlends = INDEX_INT(h->stack.cnt - 1);
792 stack_elem *firstItem;
793 int i = 0;
794 int numDeltaBlends = numBlends * h->stack.numRegions;
795 int numTotalBlends = numBlends + numDeltaBlends;
796 int firstItemIndex;
797 h->flags |= CFR_SEEN_BLEND;
798
799 h->stack.cnt--;
800
801 if (numBlends < 0 || numDeltaBlends < 0 || numTotalBlends < 0 /*check signed int overflow*/)
802 fatal(h, cfrErrStackUnderflow);
803 CHKUFLOW(numTotalBlends);
804 firstItemIndex = (h->stack.cnt - numTotalBlends);
805 firstItem = &(h->stack.array[firstItemIndex]);
806
807 if (h->flags & CFR_FLATTEN_VF) {
808 /* Blend values on the stack and replace the default values with the results.
809 */
810 for (i = 0; i < numBlends; i++) {
811 float val = INDEX_REAL(firstItemIndex + i);
812 int r;
813
814 for (r = 0; r < h->stack.numRegions; r++) {
815 int index = (i * h->stack.numRegions) + r + (h->stack.cnt - numDeltaBlends);
816 val += INDEX_REAL(index) * h->cff2.scalars[h->cff2.regionIndices[r]];
817 }
818
819 firstItem[i].is_int = 0;
820 firstItem[i].u.real_val = val;
821 firstItem[i].numBlends = 0;
822 }
823
824 h->stack.cnt -= numDeltaBlends;
825 } else {
826 firstItem->numBlends = (unsigned short)numBlends;
827 firstItem->blend_val = (float *)memNew(h, sizeof(float) * numDeltaBlends);
828 while (i < numDeltaBlends) {
829 int index = i + (h->stack.cnt - numDeltaBlends);
830 float val = INDEX_REAL(index);
831 firstItem->blend_val[i] = val;
832 i++;
833 }
834 h->stack.cnt -= numDeltaBlends;
835 }
836 }
837
838 /* Get string from its sid. */
839 static char *sid2str(cfrCtx h, long sid) {
840 if (sid < 0)
841 ;
842 else if (sid < (int)ARRAY_LEN(stdstrs))
843 return stdstrs[sid]; /* Standard string */
844 else {
845 sid -= ARRAY_LEN(stdstrs);
846 if (sid < h->string.ptrs.cnt)
847 return h->string.ptrs.array[sid]; /* Custom string */
848 }
849
850 fatal(h, cfrErrSID);
851 return NULL; /* Suppress compiler warning */
852 }
853
854 static int hasBlend(cfrCtx h) {
855 int i;
856 int hasBlend = 0;
857 for (i = 0; i < h->stack.cnt; i++) {
858 if (INDEX(i).numBlends > 0) {
859 hasBlend = 1;
860 }
861 }
862 return hasBlend;
863 }
864
865 /* Save real delta array operands. */
866 static void saveDeltaArray(cfrCtx h, size_t max, long *cnt, float *array, long *blendCnt, abfOpEntry *blendArray) {
867 /* The regular values on the stack just need to be copied to the regular value array, and this happens
868 whether or not there are blend operators.
869
870 However, some of the values are the default font values from the operands for a blend operation.
871 If any of these exist in the stack, then we fill out the blendArray. The regular values in the stack are just
872 copied over as is. However, when we encounter a stack entry with numBlends > 0, we know this is the start of
873 numBlends operands from a blend operation. In this case, we first copy the numBlends operands
874 the current blendArray entry, and then copy the numBlends * numMaster delta values
875 from that first stack entry to the current blendArray entry. The current blend entry then contains all the
876 operands for the blend operator.
877 We then skip over the numBlends stack entries, as these have already been copied to the current blendArray entry.
878
879 Note that the blendArray will have fewer elements than the regular stack, as each set of numBlends default font
880 values from a blend operation will be copied into a single blendArray entry.
881 */
882
883 int i;
884
885 if (h->stack.cnt == 0 || h->stack.cnt > (long)max)
886 fatal(h, cfrErrDICTArray);
887
888 array[0] = INDEX_REAL(0);
889 for (i = 1; i < h->stack.cnt; i++)
890 array[i] = array[i - 1] + INDEX_REAL(i);
891
892 *cnt = h->stack.cnt;
893
894 if (!hasBlend(h)) {
895 *blendCnt = 0; /* show that there are no blended values - the regular array should be used. */
896 } else {
897 int j, k, bi;
898 float lastValue = 0;
899
900 i = j = k = bi = 0;
901 while (i < h->stack.cnt) {
902 int numBlends;
903
904 abfOpEntry *blendEntry = &blendArray[bi];
905
906 stack_elem *stackEntry = &(INDEX(i));
907 numBlends = stackEntry->numBlends;
908
909 if (numBlends == 0) {
910 blendEntry->value = lastValue + (stackEntry->is_int ? (float)stackEntry->u.int_val : stackEntry->u.real_val);
911 lastValue = blendEntry->value;
912 blendEntry->numBlends = 0;
913 blendEntry->blendValues = NULL;
914 i++;
915 bi++;
916 } else {
917 int l;
918 float val;
919 signed int numRegions = h->stack.numRegions;
920 unsigned short numBlendValues = (unsigned short)(numBlends + numBlends * numRegions);
921 float *blendValues = (float *)memNew(h, sizeof(abfOpEntry) * numBlendValues);
922
923 blendEntry->numBlends = (unsigned short)numBlends;
924 blendEntry->blendValues = blendValues;
925
926 /* first, copy the numBlend default values to blendArray[i], summing the deltas to give absolute values. */
927 for (j = 0; j < numBlends; j++) {
928 val = INDEX_REAL(i);
929 blendValues[j] = lastValue + val;
930 lastValue = blendValues[j];
931 i++;
932 }
933 /* now, copy the blend deltas default values to blendArray[i].
934 We write all the absolute values for region 0, then for region 1, ..., region n.*/
935 l = numBlends;
936 for (j = 0; j < numRegions; j++) {
937 float diff = 0;
938 for (k = 0; k < numBlends; k++) {
939 val = stackEntry->blend_val[j + numRegions * k];
940 diff += val;
941 blendValues[l++] = blendValues[k] + diff;
942 }
943 }
944
945 bi++;
946 }
947 }
948 *blendCnt = bi;
949 }
950 }
951
952 static void saveBlend(cfrCtx h, float *realValue, abfOpEntry *blendEntry) {
953 /* Save a value that may be blended. Stack depth is 1 for a non-blended value, or numBlends for a blended value. */
954 int numBlends;
955
956 stack_elem *stackEntry = &(INDEX(0));
957 numBlends = stackEntry->numBlends;
958
959 *realValue = (stackEntry->is_int) ? (float)stackEntry->u.int_val : stackEntry->u.real_val;
960
961 if (numBlends == 0) {
962 blendEntry->value = *realValue;
963 blendEntry->numBlends = 0; /* shows there is no blend value, and the regular value should be used instead. */
964 blendEntry->blendValues = NULL;
965 } else if (numBlends == 1) {
966 int i;
967 float defaultValue;
968 signed int numRegions = h->stack.numRegions;
969 unsigned short numBlendValues = (unsigned short)(numBlends + numRegions);
970 float *blendValues = (float *)memNew(h, sizeof(abfOpEntry) * numBlendValues);
971
972 blendEntry->numBlends = (unsigned short)numBlends;
973 blendEntry->blendValues = blendValues;
974
975 // copy the default region value
976 blendValues[0] = defaultValue = INDEX_REAL(0);
977
978 /* now, copy the blend absolute values to blendArray[i].
979 The default region value is in stackEntry->int_val or real_val
980 The region delta values are in the stackEntry->blend_val array.
981 */
982
983 for (i = 0; i < numRegions; i++) {
984 blendValues[i + 1] = stackEntry->blend_val[i] + defaultValue;
985 }
986 } else
987 fatal(h, cfrErrDICTOp);
988 }
989
990 /* Save integer array operands. */
991 static void saveIntArray(cfrCtx h, size_t max, long *cnt, long *array,
992 int delta) {
993 int i;
994 if (h->stack.cnt == 0 || h->stack.cnt > (int)max)
995 fatal(h, cfrErrDICTArray);
996 array[0] = INDEX_INT(0);
997 for (i = 1; i < h->stack.cnt; i++)
998 array[i] = (delta ? array[i - 1] + INDEX_INT(i) : INDEX_INT(i));
999 *cnt = h->stack.cnt;
1000 }
1001
1002 static int setNumMasters(cfrCtx h, unsigned short vsindex) {
1003 int numMasters = h->stack.numRegions = var_getIVDRegionCountForIndex(h->cff2.varStore, vsindex);
1004
1005 if (!var_getIVSRegionIndices(h->cff2.varStore, vsindex, h->cff2.regionIndices, h->cff2.regionListCount)) {
1006 message(h, "inconsistent region indices detected in item variation store subtable %d", vsindex);
1007 numMasters = 0;
1008 }
1009 return numMasters;
1010 }
1011
1012 /* -------------------------------- VarStore ------------------------------- */
1013
1014 static void readVarStore(cfrCtx h) {
1015 unsigned short length;
1016 unsigned int vstoreStart = h->region.VarStore.begin + 2;
1017
1018 if (h->region.VarStore.begin == -1)
1019 fatal(h, cfrErrNoFDSelect);
1020
1021 if (h->cff2.varStore) {
1022 var_freeItemVariationStore(&h->cb.shstm, h->cff2.varStore);
1023 h->cff2.varStore = 0;
1024 }
1025
1026 srcSeek(h, h->region.VarStore.begin);
1027 length = (unsigned long)read2(h);
1028 h->region.VarStore.end = vstoreStart + length;
1029 h->cff2.varStore = var_loadItemVariationStore(&h->cb.shstm, (unsigned long)vstoreStart, length, 0);
1030 if (!h->cff2.varStore)
1031 return;
1032 h->cff2.regionListCount = var_getIVSRegionCount(h->cff2.varStore);
1033 if (h->cff2.regionListCount > CFF2_MAX_MASTERS)
1034 fatal(h, cfrErrGeometry);
1035 h->top.varStore = h->cff2.varStore;
1036 /* pre-calculate scalars for all regions for the current weight vector */
1037 var_calcRegionScalars(&h->cb.shstm, h->cff2.varStore, &h->cff2.axisCount, h->cff2.ndv, h->cff2.scalars);
1038 }
1039
1040 /* Save PostScript operator string. */
1041 static char *savePostScript(cfrCtx h, char *str) {
1042 int32_t value;
1043 int n;
1044 char *p;
1045 char *q;
1046
1047 p = strstr(str, "/FSType");
1048 if (p != NULL) {
1049 /* Extract FSType from string */
1050 n = -1;
1051 q = p + sizeof("/FSType") - 1;
1052 if (SSCANF_S(q, " %d def%n", &value, &n) == 1 && n != -1 &&
1053 0 <= value && value < 65536) {
1054 /* Successfully parsed value; remove definition from string */
1055 memmove(p, q + n, strlen(p) + 1 - (q - p + n));
1056
1057 if (h->top.FSType != ABF_UNSET_INT)
1058 message(h,
1059 "two FSTypes (OS/2 value retained, "
1060 "CFF value removed)");
1061 else
1062 h->top.FSType = value;
1063 } else
1064 fatal(h, cfrErrFSType);
1065 }
1066
1067 p = strstr(str, "/OrigFontType");
1068 if (p != NULL) {
1069 /* Extract OrigFontType from string */
1070 n = -1;
1071 q = p + sizeof("/OrigFontType") - 1;
1072 if (SSCANF_S(q, " /Type1 def%n", &n) == 0 && n != -1)
1073 h->top.OrigFontType = abfOrigFontTypeType1;
1074 else if (SSCANF_S(q, " /CID def%n", &n) == 0 && n != -1)
1075 h->top.OrigFontType = abfOrigFontTypeCID;
1076 else if (SSCANF_S(q, " /TrueType def%n", &n) == 0 && n != -1)
1077 h->top.OrigFontType = abfOrigFontTypeTrueType;
1078 else if (SSCANF_S(q, " /OCF def%n", &n) == 0 && n != -1)
1079 h->top.OrigFontType = abfOrigFontTypeOCF;
1080 else if (SSCANF_S(q, " /UFO def%n", &n) == 0 && n != -1)
1081 h->top.OrigFontType = abfOrigFontTypeUFO;
1082 else
1083 fatal(h, cfrErrOrigFontType);
1084
1085 /* Successfully parsed value; remove definition from string */
1086 memmove(p, q + n, strlen(p) + 1 - (q - p + n));
1087 }
1088
1089 /* Check for empty string */
1090 for (p = str; isspace(*p); p++)
1091 ;
1092 if (*p == '\0')
1093 return NULL;
1094
1095 return str;
1096 }
1097
1098 /* Read DICT data */
1099 static void readDICT(cfrCtx h, ctlRegion *region, int topdict) {
1100 abfTopDict *top = &h->top;
1101 abfFontDict *font = h->fd->fdict;
1102 abfPrivateDict *priv = &font->Private;
1103
1104 if (region->begin == region->end) {
1105 /* Empty dictionary (assuming Private); valid but set BlueValues to
1106 avoid warning */
1107 h->fd->flags |= SEEN_BLUE_VALUES;
1108 return;
1109 }
1110
1111 srcSeek(h, region->begin);
1112
1113 h->stack.cnt = 0;
1114 h->stack.numRegions = priv->numRegions = 0;
1115 priv->vsindex = 0;
1116
1117 if (h->cff2.varStore != NULL) {
1118 h->stack.numRegions = priv->numRegions = setNumMasters(h, priv->vsindex);
1119 }
1120 while (srcTell(h) < region->end) {
1121 int byte0;
1122 CHECK_DICT_BYTES_LEFT(1);
1123 byte0 = read1(h);
1124 switch (byte0) {
1125 case cff_vsindex:
1126 priv->vsindex = (unsigned short)INDEX_INT(0);
1127 h->stack.numRegions = priv->numRegions = setNumMasters(h, priv->vsindex);
1128 break;
1129
1130 case cff_version:
1131 CHKUFLOW(1);
1132 top->version.ptr = sid2str(h, (SID)INDEX_INT(0));
1133 break;
1134 case cff_Notice:
1135 CHKUFLOW(1);
1136 top->Notice.ptr = sid2str(h, (SID)INDEX_INT(0));
1137 break;
1138 case cff_FullName:
1139 CHKUFLOW(1);
1140 top->FullName.ptr = sid2str(h, (SID)INDEX_INT(0));
1141 break;
1142 case cff_FamilyName:
1143 CHKUFLOW(1);
1144 top->FamilyName.ptr = sid2str(h, (SID)INDEX_INT(0));
1145 break;
1146 case cff_Weight:
1147 CHKUFLOW(1);
1148 top->Weight.ptr = sid2str(h, (SID)INDEX_INT(0));
1149 break;
1150 case cff_FontBBox:
1151 CHKUFLOW(4);
1152 top->FontBBox[0] = INDEX_REAL(0);
1153 top->FontBBox[1] = INDEX_REAL(1);
1154 top->FontBBox[2] = INDEX_REAL(2);
1155 top->FontBBox[3] = INDEX_REAL(3);
1156 break;
1157 case cff_BlueValues:
1158 saveDeltaArray(h, ARRAY_LEN(priv->BlueValues.array),
1159 &priv->BlueValues.cnt,
1160 priv->BlueValues.array,
1161 &priv->blendValues.BlueValues.cnt,
1162 priv->blendValues.BlueValues.array);
1163 h->fd->flags |= SEEN_BLUE_VALUES;
1164 break;
1165 case cff_OtherBlues:
1166 if (h->stack.cnt > 0)
1167 saveDeltaArray(h, ARRAY_LEN(priv->OtherBlues.array),
1168 &priv->OtherBlues.cnt,
1169 priv->OtherBlues.array,
1170 &priv->blendValues.OtherBlues.cnt,
1171 priv->blendValues.OtherBlues.array);
1172 else
1173 message(h, "OtherBlues empty array (ignored)");
1174 break;
1175 case cff_FamilyBlues:
1176 if (h->stack.cnt > 0)
1177 saveDeltaArray(h, ARRAY_LEN(priv->FamilyBlues.array),
1178 &priv->FamilyBlues.cnt,
1179 priv->FamilyBlues.array,
1180 &priv->blendValues.FamilyBlues.cnt,
1181 priv->blendValues.FamilyBlues.array);
1182
1183 else
1184 message(h, "FamilyBlues empty array (ignored)");
1185 break;
1186 case cff_FamilyOtherBlues:
1187 if (h->stack.cnt > 0)
1188 saveDeltaArray(h, ARRAY_LEN(priv->FamilyOtherBlues.array),
1189 &priv->FamilyOtherBlues.cnt,
1190 priv->FamilyOtherBlues.array,
1191 &priv->blendValues.FamilyOtherBlues.cnt,
1192 priv->blendValues.FamilyOtherBlues.array);
1193
1194 else
1195 message(h, "FamilyBlues empty array (ignored)");
1196 break;
1197 case cff_StdHW:
1198 saveBlend(h, &priv->StdHW, &priv->blendValues.StdHW);
1199 break;
1200 case cff_StdVW:
1201 saveBlend(h, &priv->StdVW, &priv->blendValues.StdVW);
1202 break;
1203 case cff_escape:
1204 /* Process escaped operator */
1205 CHECK_DICT_BYTES_LEFT(1);
1206 byte0 = read1(h);
1207 switch (cff_ESC(byte0)) {
1208 case cff_Copyright:
1209 CHKUFLOW(1);
1210 top->Copyright.ptr = sid2str(h, (SID)INDEX_INT(0));
1211 break;
1212 case cff_isFixedPitch:
1213 CHKUFLOW(1);
1214 top->isFixedPitch = INDEX_INT(0);
1215 break;
1216 case cff_ItalicAngle:
1217 CHKUFLOW(1);
1218 top->ItalicAngle = INDEX_REAL(0);
1219 break;
1220 case cff_UnderlinePosition:
1221 CHKUFLOW(1);
1222 top->UnderlinePosition = INDEX_REAL(0);
1223 break;
1224 case cff_UnderlineThickness:
1225 CHKUFLOW(1);
1226 top->UnderlineThickness = INDEX_REAL(0);
1227 break;
1228 case cff_PaintType:
1229 CHKUFLOW(1);
1230 font->PaintType = INDEX_INT(0);
1231 break;
1232 case cff_CharstringType:
1233 CHKUFLOW(1);
1234 switch (INDEX_INT(0)) {
1235 case 2:
1236 break;
1237 default:
1238 fatal(h, cfrErrCstrType);
1239 }
1240 break;
1241 case cff_FontMatrix:
1242 saveMatrix(h, topdict);
1243 break;
1244 case cff_StrokeWidth:
1245 CHKUFLOW(1);
1246 top->StrokeWidth = INDEX_REAL(0);
1247 break;
1248 case cff_BlueScale:
1249 saveBlend(h, &priv->BlueScale, &priv->blendValues.BlueScale);
1250 break;
1251 case cff_BlueShift:
1252 saveBlend(h, &priv->BlueShift, &priv->blendValues.BlueShift);
1253 break;
1254 case cff_BlueFuzz:
1255 saveBlend(h, &priv->BlueFuzz, &priv->blendValues.BlueFuzz);
1256 break;
1257 case cff_StemSnapH:
1258 saveDeltaArray(h, ARRAY_LEN(priv->StemSnapH.array),
1259 &priv->StemSnapH.cnt,
1260 priv->StemSnapH.array,
1261 &priv->blendValues.StemSnapH.cnt,
1262 priv->blendValues.StemSnapH.array);
1263
1264 break;
1265 case cff_StemSnapV:
1266 saveDeltaArray(h, ARRAY_LEN(priv->StemSnapV.array),
1267 &priv->StemSnapV.cnt,
1268 priv->StemSnapV.array,
1269 &priv->blendValues.StemSnapV.cnt,
1270 priv->blendValues.StemSnapV.array);
1271
1272 break;
1273 case cff_ForceBold:
1274 CHKUFLOW(1);
1275 priv->ForceBold = INDEX_INT(0);
1276 break;
1277 case cff_LanguageGroup:
1278 CHKUFLOW(1);
1279 priv->LanguageGroup = INDEX_INT(0);
1280 break;
1281 case cff_ExpansionFactor:
1282 CHKUFLOW(1);
1283 priv->ExpansionFactor = INDEX_REAL(0);
1284 break;
1285 case cff_initialRandomSeed:
1286 CHKUFLOW(1);
1287 priv->initialRandomSeed = INDEX_REAL(0);
1288 break;
1289 case cff_PostScript:
1290 CHKUFLOW(1);
1291 top->PostScript.ptr =
1292 savePostScript(h, sid2str(h, (SID)INDEX_INT(0)));
1293 break;
1294 case cff_BaseFontName:
1295 CHKUFLOW(1);
1296 top->BaseFontName.ptr = sid2str(h, (SID)INDEX_INT(0));
1297 break;
1298 case cff_BaseFontBlend:
1299 saveIntArray(h, ARRAY_LEN(top->BaseFontBlend.array),
1300 &top->BaseFontBlend.cnt,
1301 top->BaseFontBlend.array, 1);
1302 break;
1303 case cff_ROS:
1304 CHKUFLOW(3);
1305 top->cid.Registry.ptr = sid2str(h, (SID)INDEX_INT(0));
1306 top->cid.Ordering.ptr = sid2str(h, (SID)INDEX_INT(1));
1307 top->cid.Supplement = INDEX_INT(2);
1308 h->flags |= CID_FONT;
1309 break;
1310 case cff_CIDFontVersion:
1311 CHKUFLOW(1);
1312 top->cid.CIDFontVersion = INDEX_REAL(0);
1313 break;
1314 case cff_CIDFontRevision:
1315 CHKUFLOW(1);
1316 top->cid.CIDFontRevision = INDEX_INT(0);
1317 break;
1318 case cff_CIDFontType:
1319 /* Validate and discard */
1320 CHKUFLOW(1);
1321 if (INDEX_INT(0) != 0)
1322 fatal(h, cfrErrCIDType);
1323 break;
1324 case cff_CIDCount:
1325 CHKUFLOW(1);
1326 top->cid.CIDCount = INDEX_INT(0);
1327 break;
1328 case cff_UIDBase:
1329 CHKUFLOW(1);
1330 top->cid.UIDBase = INDEX_INT(0);
1331 break;
1332 case cff_FDArray:
1333 CHKUFLOW(1);
1334 h->region.FDArrayINDEX.begin = h->src.origin + INDEX_INT(0);
1335 break;
1336 case cff_FDSelect:
1337 CHKUFLOW(1);
1338 h->region.FDSelect.begin = h->src.origin + INDEX_INT(0);
1339 h->flags |= CID_FONT;
1340 break;
1341 case cff_FontName:
1342 CHKUFLOW(1);
1343 font->FontName.ptr = sid2str(h, (SID)INDEX_INT(0));
1344 break;
1345 case cff_reservedESC15:
1346 /* Was cff_ForceBoldThreshold but was erroneously retained in
1347 snapshot MMs by cffsub. Report, but otherwise ignore. */
1348 message(h, "defunct /ForceBoldThreshold operator (ignored)");
1349 break;
1350 case cff_SyntheticBase:
1351 case cff_Chameleon:
1352 fatal(h, cfrErrChameleon);
1353 case cff_reservedESC16:
1354 /* Was cff_lenIV but later removed from specification. Some
1355 Dainippon Screen fonts are using this operator with a value
1356 of -1 which is a no-op so can be safely ignored. */
1357 if (h->stack.cnt != 1 || INDEX_INT(0) != -1)
1358 fatal(h, cfrErrDICTOp);
1359 message(h, "defunct /lenIV operator (ignored)");
1360 break;
1361 case cff_numMasters:
1362 /* Was cff_MultipleMaster so this must be one of the old test
1363 MMs that are no longer supported. There are too many things
1364 that will break if an attempt is made to continue so just
1365 print a helpful message and quit. */
1366 message(h, "defunct /MultipleMaster operator");
1367 break;
1368 case cff_reservedESC40:
1369 /* Was an experimental cff_VToHOrigin but the experiment was
1370 never conducted. However, it was implemented in cff_parse.c
1371 and Apple apparently saw it in that code and decided to use
1372 in their implementation of "Save As PDF" when subsetting
1373 fonts. Since it has never done anything it can be safely
1374 ignored. */
1375 message(h, "defunct /VToHOrigin operator (ignored)");
1376 break;
1377 case cff_reservedESC41:
1378 /* Was an experimental cff_defaultWidthY but the experiment was
1379 never conducted. However, it was implemented in cff_parse.c
1380 and Apple apparently saw it in that code and decided to use
1381 in their implementation of "Save As PDF" when subsetting
1382 fonts. Since it has never done anything it can be safely
1383 ignored. */
1384 message(h, "defunct /defaultWidthY operator (ignored)");
1385 break;
1386 case cff_reservedESC25:
1387 case cff_reservedESC26:
1388 case cff_reservedESC27:
1389 case cff_reservedESC28:
1390 case cff_reservedESC29:
1391 default:
1392 if (h->stm.dbg == NULL)
1393 fatal(h, cfrErrDICTOp);
1394 else
1395 message(h, "invalid DICT op ESC%hu (ignored)", byte0);
1396 } /* End: switch (escop) */
1397 break;
1398 case cff_UniqueID:
1399 CHKUFLOW(1);
1400 top->UniqueID = INDEX_INT(0);
1401 break;
1402 case cff_XUID:
1403 saveIntArray(h, ARRAY_LEN(top->XUID.array),
1404 &top->XUID.cnt,
1405 top->XUID.array, 0);
1406 break;
1407 case cff_charset:
1408 CHKUFLOW(1);
1409 h->region.Charset.begin = INDEX_INT(0);
1410 if (h->region.Charset.begin > cff_ExpertSubsetCharset)
1411 /* Custom charset; adjust offset */
1412 h->region.Charset.begin += h->src.origin;
1413 break;
1414 case cff_Encoding:
1415 CHKUFLOW(1);
1416 h->region.Encoding.begin = INDEX_INT(0);
1417 if (h->region.Encoding.begin > cff_ExpertEncoding)
1418 /* Custom encoding; adjust offset */
1419 h->region.Encoding.begin += h->src.origin;
1420 break;
1421 case cff_CharStrings:
1422 CHKUFLOW(1);
1423 h->region.CharStringsINDEX.begin = h->src.origin + INDEX_INT(0);
1424 break;
1425 case cff_Private:
1426 CHKUFLOW(2);
1427 h->fd->region.PrivateDICT.begin = h->src.origin + INDEX_INT(1);
1428 h->fd->region.PrivateDICT.end =
1429 h->fd->region.PrivateDICT.begin + INDEX_INT(0);
1430 break;
1431 case cff_VarStore:
1432 CHKUFLOW(1);
1433 h->region.VarStore.begin = h->src.origin + INDEX_INT(0);
1434 break;
1435 case cff_maxstack:
1436 CHKUFLOW(1);
1437 /* deprecated April 2017.
1438 top->maxstack = (uint16_t)INDEX_INT(0); */
1439 break;
1440 case cff_Subrs:
1441 CHKUFLOW(1);
1442 h->fd->region.LocalSubrINDEX.begin =
1443 region->begin + INDEX_INT(0);
1444 break;
1445 case cff_defaultWidthX:
1446 CHKUFLOW(1);
1447 h->fd->aux.defaultWidthX = INDEX_REAL(0);
1448 break;
1449 case cff_nominalWidthX:
1450 CHKUFLOW(1);
1451 h->fd->aux.nominalWidthX = INDEX_REAL(0);
1452 break;
1453 case cff_shortint:
1454 /* 3 byte number */
1455 CHKOFLOW(1);
1456 CHECK_DICT_BYTES_LEFT(2);
1457 {
1458 int16_t value = read1(h);
1459 value = value << 8 | read1(h);
1460 PUSH_INT(value);
1461 }
1462 continue;
1463 case cff_longint:
1464 /* 5 byte number */
1465 CHKOFLOW(1);
1466 CHECK_DICT_BYTES_LEFT(4);
1467 {
1468 int32_t value = read1(h);
1469 value = value << 8 | read1(h);
1470 value = value << 8 | read1(h);
1471 value = value << 8 | read1(h);
1472 PUSH_INT(value);
1473 }
1474 continue;
1475 case cff_BCD:
1476 CHKOFLOW(1);
1477 PUSH_REAL((float)convBCD(h, region));
1478 continue;
1479 case cff_blend:
1480 if (h->stack.numRegions == 0) {
1481 /* priv->vsindex is set to 0 by default; it is otherwise only if the vsindex operator is used */
1482 setNumMasters(h, priv->vsindex);
1483 }
1484 handleBlend(h);
1485 continue;
1486 default:
1487 /* 1 byte number */
1488 CHKOFLOW(1);
1489 PUSH_INT(byte0 - 139);
1490 continue;
1491 case 247:
1492 case 248:
1493 case 249:
1494 case 250:
1495 /* Positive 2 byte number */
1496 CHKOFLOW(1);
1497 CHECK_DICT_BYTES_LEFT(1);
1498 PUSH_INT(108 + 256 * (byte0 - 247) + read1(h));
1499 continue;
1500 case 251:
1501 case 252:
1502 case 253:
1503 case 254:
1504 /* Negative 2 byte number */
1505 CHKOFLOW(1);
1506 CHECK_DICT_BYTES_LEFT(1);
1507 PUSH_INT(-108 - 256 * (byte0 - 251) - read1(h));
1508 continue;
1509 case cff_reserved26:
1510 case cff_reserved27:
1511 case cff_reserved255:
1512 if (h->stm.dbg == NULL)
1513 fatal(h, cfrErrDICTOp);
1514 else
1515 message(h, "Invalid DICT op %hu (ignored)", byte0);
1516 } /* End: switch (byte0) */
1517 if (h->flags & CFR_SEEN_BLEND) {
1518 int j = 0;
1519 while (j < h->stack.cnt) {
1520 if (h->stack.array[j].numBlends > 0) {
1521 memFree(h, h->stack.array[j].blend_val);
1522 h->stack.array[j].numBlends = 0;
1523 }
1524 j++;
1525 }
1526 h->flags &= ~CFR_SEEN_BLEND;
1527 }
1528
1529 h->stack.cnt = 0; /* Clear stack */
1530 } /* End: while (...) */
1531 }
1532
1533 /* -------------------------- Component Processing ------------------------- */
1534
1535 /* Read subroutine index. */
1536 static void readSubrINDEX(cfrCtx h, ctlRegion *region, SubrOffsets *offsets) {
1537 long i;
1538 uint32_t cnt;
1539 Offset dataoff;
1540 OffSize offSize;
1541 OffSize cntSize;
1542
1543 /* Read INDEX count */
1544 srcSeek(h, region->begin);
1545 if (h->flags & CFR_IS_CFF2) {
1546 cntSize = 4;
1547 cnt = readN(h, cntSize);
1548 if (cnt > SUBR_INDEX_CNT_LIMIT)
1549 {
1550 message(h, "subroutine count [%d] exceeds limit [%d]", cnt, SUBR_INDEX_CNT_LIMIT);
1551 fatal(h, cfrErrINDEXHeader);
1552 }
1553 } else {
1554 cntSize = 2;
1555 cnt = read2(h);
1556 }
1557
1558 if (cnt == 0) {
1559 /* Empty INDEX */
1560 region->end = region->begin + cntSize;
1561 return;
1562 }
1563
1564 offSize = read1(h); /* Get offset size */
1565 if (offSize < 1 || offSize > 4)
1566 fatal(h, cfrErrINDEXHeader);
1567
1568 /* Compute data offset */
1569 dataoff = region->begin + cntSize + 1 + (cnt + 1) * offSize - 1;
1570
1571 /* Allocate offset array */
1572 if (dnaSetCnt(offsets, DNA_ELEM_SIZE_(*offsets), cnt) < 0)
1573 fatal(h, cfrErrNoMemory);
1574
1575 /* Read charstring offsets */
1576 for (i = 0; i < cnt; i++)
1577 offsets->array[i] = dataoff + readN(h, offSize);
1578
1579 /* Save INDEX length */
1580 region->end = dataoff + readN(h, offSize);
1581 }
1582
1583 /* Read INDEX structure parameters and return offset of byte following INDEX.*/
1584 static void readINDEX(cfrCtx h, ctlRegion *region, INDEX *index) {
1585 OffSize cntSize;
1586
1587 /* Read INDEX count */
1588 srcSeek(h, region->begin);
1589
1590 if (h->flags & CFR_IS_CFF2) {
1591 cntSize = 4;
1592 index->count = readN(h, 4);
1593 } else {
1594 cntSize = 2;
1595 index->count = read2(h);
1596 }
1597
1598 index->offset = region->begin + cntSize + 1; /* Get offset array base */
1599 if (index->count == 0) {
1600 /* Empty INDEX */
1601 index->offSize = 0;
1602 region->end = region->begin + cntSize;
1603 return;
1604 }
1605
1606 /* Read and validate offset size */
1607 index->offSize = read1(h);
1608 if (index->offSize < 1 || index->offSize > 4)
1609 fatal(h, cfrErrINDEXHeader);
1610
1611 /* Read and validate first offset */
1612 if (readN(h, index->offSize) != 1)
1613 fatal(h, cfrErrINDEXOffset);
1614
1615 /* Set data reference */
1616 index->data = index->offset + (index->count + 1) * index->offSize - 1;
1617
1618 /* Read last offset and compute INDEX length */
1619 srcSeek(h, index->offset + index->count * index->offSize);
1620 region->end = index->data + readN(h, index->offSize);
1621 if (region->end < region->begin)
1622 fatal(h, cfrErrINDEXOffset);
1623 }
1624
1625 /* Get an element (offset and length) from INDEX structure. */
1626 static void INDEXGet(cfrCtx h, INDEX *index,
1627 unsigned element, ctlRegion *region) {
1628 long length;
1629
1630 if (index->count < element)
1631 /* Requested element out-of-bounds */
1632 fatal(h, cfrErrINDEXBounds);
1633
1634 /* Get offsets */
1635 srcSeek(h, index->offset + element * index->offSize);
1636 region->begin = index->data + readN(h, index->offSize);
1637 region->end = index->data + readN(h, index->offSize);
1638
1639 /* Validate length */
1640 length = region->end - region->begin;
1641 if (length < 0 || length > 65535)
1642 fatal(h, cfrErrINDEXOffset);
1643 }
1644
1645 /* Read Private DICT. */
1646 static void readPrivate(cfrCtx h, int iFD) {
1647 cfrFDInfo *fd = &h->FDArray.array[iFD];
1648
1649 if (fd->region.PrivateDICT.begin == -1)
1650 fatal(h, cfrErrNoPrivate);
1651
1652 readDICT(h, &fd->region.PrivateDICT, 0);
1653
1654 if (fd->region.LocalSubrINDEX.begin != -1) {
1655 readSubrINDEX(h, &fd->region.LocalSubrINDEX, &fd->Subrs);
1656 fd->aux.subrs.cnt = fd->Subrs.cnt;
1657 fd->aux.subrs.offset = fd->Subrs.array;
1658 fd->aux.subrsEnd = fd->region.LocalSubrINDEX.end;
1659 }
1660
1661 fd->aux.gsubrs.cnt = h->gsubrs.cnt;
1662 fd->aux.gsubrs.offset = h->gsubrs.array;
1663 fd->aux.gsubrsEnd = h->region.GlobalSubrINDEX.end;
1664 fd->aux.default_vsIndex = fd->fdict->Private.vsindex;
1665 fd->aux.varStore = h->cff2.varStore;
1666 fd->aux.scalars = h->cff2.scalars;
1667 }
1668
1669 /* Return the offset of a standard encoded glyph of -1 if none. */
1670 static long getStdEncGlyphOffset(void *ctx, int stdcode) {
1671 cfrCtx h = (cfrCtx)ctx;
1672 unsigned short gid = h->stdEnc2GID[stdcode];
1673 return (gid == 0) ? -1 : h->glyphs.array[gid].sup.begin;
1674 }
1675
1676 /* Initialize region. */
1677 static void initRegion(ctlRegion *region) {
1678 region->begin = -1;
1679 region->end = -1;
1680 }
1681
1682 /* Initialize FDArray element. */
1683 static void initFDInfo(cfrCtx h, int iFD) {
1684 cfrFDInfo *fd = h->fd = &h->FDArray.array[iFD];
1685 abfFontDict *fdict = &h->fdicts.array[iFD];
1686 fd->flags = 0;
1687 initRegion(&fd->region.PrivateDICT);
1688 initRegion(&fd->region.LocalSubrINDEX);
1689 fd->aux.flags = 0;
1690 if (h->flags & CFR_UPDATE_OPS)
1691 fd->aux.flags |= T2C_UPDATE_OPS;
1692 fd->aux.src = h->stm.src;
1693 fd->aux.dbg = h->stm.dbg;
1694 fd->aux.stm = &h->cb.stm;
1695 fd->aux.subrs.cnt = 0;
1696 fd->aux.gsubrs.cnt = 0;
1697 fd->aux.defaultWidthX = cff_DFLT_defaultWidthX;
1698 fd->aux.nominalWidthX = cff_DFLT_nominalWidthX;
1699 fd->aux.ctx = h;
1700 fd->aux.getStdEncGlyphOffset = getStdEncGlyphOffset;
1701 fd->aux.varStore = 0;
1702 fd->fdict = fdict;
1703 abfInitFontDict(fdict);
1704 }
1705
1706 /* Read FDArray. */
1707 static void readFDArray(cfrCtx h) {
1708 int i;
1709
1710 /* Read FDArray INDEX */
1711 if (h->region.FDArrayINDEX.begin == -1)
1712 fatal(h, cfrErrNoFDArray);
1713 readINDEX(h, &h->region.FDArrayINDEX, &h->index.FDArray);
1714 if (h->index.FDArray.count < 1 || h->index.FDArray.count > 65536)
1715 fatal(h, cfrErrBadFDArray);
1716
1717 /* Read FDArray */
1718 dnaSET_CNT(h->FDArray, h->index.FDArray.count);
1719 dnaSET_CNT(h->fdicts, h->index.FDArray.count);
1720 memset(h->fdicts.array, 0, sizeof(h->fdicts.array[0]) * h->index.FDArray.count);
1721 for (i = 0; i < h->FDArray.cnt; i++) {
1722 ctlRegion region;
1723 INDEXGet(h, &h->index.FDArray, i, &region);
1724 initFDInfo(h, i);
1725 readDICT(h, &region, 0);
1726 readPrivate(h, i);
1727 }
1728 }
1729
1730 /* Read FontName string and string INDEX strings. */
1731 static void readStrings(cfrCtx h) {
1732 Offset offset;
1733 unsigned long i;
1734 char *p;
1735 ctlRegion FontName;
1736 long lenFontName = 0;
1737 long lenStrings;
1738
1739 if (h->index.name.count != 1)
1740 fatal(h, cfrErrMultipleFont);
1741
1742 /* Get FontName data and compute its size */
1743 INDEXGet(h, &h->index.name, 0, &FontName);
1744 lenFontName = FontName.end - FontName.begin;
1745
1746 /* Compute string data size */
1747 lenStrings = (h->index.string.count == 0) ? 0 : (h->region.StringINDEX.end - h->index.string.data + 1 + /* String data bytes */
1748 h->index.string.count); /* Null termination */
1749
1750 /* Allocate buffers */
1751 dnaSET_CNT(h->string.offsets, h->index.string.count + 1);
1752 dnaSET_CNT(h->string.ptrs, h->index.string.count);
1753 dnaSET_CNT(h->string.buf, lenFontName + 1 + lenStrings);
1754
1755 p = h->string.buf.array;
1756 *p = '\0';
1757 if (h->header.major == 1) {
1758 /* Copy FontName into buffer */
1759 srcSeek(h, FontName.begin);
1760 srcRead(h, lenFontName, p);
1761 p += lenFontName;
1762 *p++ = '\0';
1763 }
1764
1765 if (h->index.string.count == 0)
1766 return; /* Empty string INDEX */
1767
1768 /* Read string offsets */
1769 srcSeek(h, h->index.string.offset);
1770 offset = readN(h, h->index.string.offSize);
1771 for (i = 0; i < h->index.string.count; i++) {
1772 long length;
1773 h->string.offsets.array[i] = offset;
1774 offset = readN(h, h->index.string.offSize);
1775
1776 /* Compute and validate object length */
1777 length = offset - h->string.offsets.array[i];
1778 if (length < 0 || length > 65535)
1779 fatal(h, cfrErrINDEXOffset);
1780 }
1781 h->string.offsets.array[i] = offset;
1782
1783 /* Read string data */
1784 for (i = 0; i < (unsigned long)h->string.ptrs.cnt; i++) {
1785 long length =
1786 h->string.offsets.array[i + 1] - h->string.offsets.array[i];
1787 srcRead(h, length, p);
1788 h->string.ptrs.array[i] = p;
1789 p += length;
1790 *p++ = '\0';
1791 }
1792 }
1793
1794 /* Read CharStrings INDEX. */
1795 static void readCharStringsINDEX(cfrCtx h, short flags) {
1796 long i;
1797 INDEX index;
1798 Offset offset;
1799
1800 /* Read INDEX */
1801 if (h->region.CharStringsINDEX.begin == -1)
1802 fatal(h, cfrErrNoCharStrings);
1803 readINDEX(h, &h->region.CharStringsINDEX, &index);
1804
1805 /* Check for case of CFF2 table containing more
1806 glyphs than other tables can handle. */
1807 if (index.count > 0xFFFF)
1808 fatal(h, cfrErrTooManyGlyphs);
1809
1810 /* Allocate and initialize glyphs array */
1811 dnaSET_CNT(h->glyphs, index.count);
1812 if (index.count == 0)
1813 return;
1814 srcSeek(h, index.offset);
1815 offset = index.data + readN(h, index.offSize);
1816 for (i = 0; i < h->glyphs.cnt; i++) {
1817 long length;
1818 abfGlyphInfo *info = &h->glyphs.array[i];
1819
1820 abfInitGlyphInfo(info);
1821 info->flags = flags;
1822 info->tag = (unsigned short)i;
1823 info->sup.begin = offset;
1824 info->sup.end = index.data + readN(h, index.offSize);
1825
1826 /* Validate object length */
1827 length = info->sup.end - info->sup.begin;
1828 if (length > 65535) {
1829 message(h,
1830 "Warning: CharString of GID %ld is %ld bytes long. "
1831 "CharStrings longer than 65535 bytes might not be "
1832 "supported by some implementations.",
1833 i, length);
1834 }
1835 offset = info->sup.end;
1836 }
1837 }
1838
1839 /* -------------------------------- Charset -------------------------------- */
1840
1841 /* Get glyph name from format 2.0 post table. */
1842 static char *post2GetName(cfrCtx h, SID gid) {
1843 if (gid >= h->post.fmt2.glyphNameIndex.cnt)
1844 return NULL; /* Out of bounds; .notdef */
1845 else if (h->post.format != 0x00020000)
1846 return (gid < h->post.fmt2.strings.cnt) ? h->post.fmt2.strings.array[gid] : NULL;
1847 else {
1848 long nid = (gid < h->post.fmt2.glyphNameIndex.cnt) ? h->post.fmt2.glyphNameIndex.array[gid] : 0;
1849 if (nid == 0)
1850 return stdstrs[nid]; /* .notdef */
1851 else if (nid < 258)
1852 return applestd[nid];
1853 else if (nid - 258 >= h->post.fmt2.strings.cnt) {
1854 return NULL; /* Out of bounds; .notdef */
1855 } else
1856 return h->post.fmt2.strings.array[nid - 258];
1857 }
1858 }
1859
1860 /* Add SID/CID to charset */
1861 static void addID(cfrCtx h, long gid, unsigned short id) {
1862 abfGlyphInfo *info;
1863 if (gid >= h->glyphs.cnt)
1864 fatal(h, cfrErrNoGlyph);
1865 info = &h->glyphs.array[gid];
1866 if (h->flags & CID_FONT)
1867 /* Save CID */
1868 info->cid = id;
1869 else {
1870 /* Save SID */
1871 info->gname.impl = id;
1872 info->gname.ptr = sid2str(h, id);
1873
1874 /* Non-CID font so select FD[0] */
1875 info->iFD = 0;
1876
1877 if (id < ARRAY_LEN(stdenc)) {
1878 /* Add GID of standard encoded info to table */
1879 int code = stdenc[id];
1880 if (code != 0) {
1881 h->stdEnc2GID[code] = (unsigned short)gid;
1882 }
1883 }
1884 }
1885 }
1886
1887 /* Read 2-byte signed number. */
1888 static int16_t sread2(cfrCtx h) {
1889 uint16_t value = (uint16_t)read1(h) << 8;
1890 value |= (uint16_t)read1(h);
1891 return (int16_t)value;
1892 }
1893
1894 /* Read 4-byte unsigned number. */
1895 static uint32_t read4(cfrCtx h) {
1896 uint32_t value = (uint32_t)read1(h) << 24;
1897 value |= (uint32_t)read1(h) << 16;
1898 value |= (uint32_t)read1(h) << 8;
1899 return value | (uint32_t)read1(h);
1900 }
1901
1902 /* Read 4-byte signed number. */
1903 static int32_t sread4(cfrCtx h) {
1904 uint32_t value = (uint32_t)read1(h) << 24;
1905 value |= (uint32_t)read1(h) << 16;
1906 value |= (uint32_t)read1(h) << 8;
1907 value |= (uint32_t)read1(h);
1908 return (int32_t)value;
1909 }
1910
1911 static int invalidStreamOffset(cfrCtx h, unsigned long offset) {
1912 h->src.length = 0; /* To force re-read after this test */
1913 h->cb.stm.seek(&h->cb.stm, h->stm.src, offset);
1914 return h->cb.stm.read(&h->cb.stm, h->stm.src, &h->src.buf) == 0;
1915 }
1916
1917 static void buildGIDNames(cfrCtx h) {
1918 char *p;
1919 long length;
1920 long numGlyphs = h->glyphs.cnt;
1921 long i;
1922
1923 if (numGlyphs <= 0)
1924 fatal(h, cfrErrNoGlyph);
1925 dnaSET_CNT(h->post.fmt2.glyphNameIndex, numGlyphs);
1926 for (i = 0; i < numGlyphs; i++) {
1927 h->post.fmt2.glyphNameIndex.array[i] = i;
1928 }
1929 /* Read string data */
1930 length = numGlyphs * 9; /* 3 for 'gid', 5 for GID, 1 for null termination. */
1931 dnaSET_CNT(h->post.fmt2.buf, length + 1);
1932 /* Build C strings array */
1933 dnaSET_CNT(h->post.fmt2.strings, numGlyphs);
1934 p = h->post.fmt2.buf.array;
1935 sprintf(p, ".notdef");
1936 length = (long)strlen(p);
1937 h->post.fmt2.strings.array[0] = p;
1938 p += length + 1;
1939 for (i = 1; i < numGlyphs; i++) {
1940 h->post.fmt2.strings.array[i] = p;
1941 sprintf(p, "gid%05ld", i);
1942 length = (long)strlen(p);
1943 p += length + 1;
1944 }
1945
1946 return; /* Success */
1947 }
1948
1949 /* Read post table. */
1950 static void postRead(cfrCtx h) {
1951 enum { POST_HEADER_SIZE = 4 * 7 + 2 * 2 };
1952 char *p;
1953 char *end;
1954 long i;
1955 long length;
1956 long numGlyphs;
1957 long strCount;
1958 sfrTable *table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('p', 'o', 's', 't'));
1959 if (table == NULL)
1960 return; /* Optional table missing */
1961
1962 if (invalidStreamOffset(h, table->offset + POST_HEADER_SIZE - 1)) {
1963 message(h, "post: header outside stream bounds");
1964 return;
1965 }
1966
1967 srcSeek(h, table->offset);
1968
1969 h->post.format = read4(h);
1970 h->post.italicAngle = sread4(h);
1971 h->post.underlinePosition = sread2(h);
1972 h->post.underlineThickness = sread2(h);
1973 h->post.isFixedPitch = read4(h);
1974 h->post.minMemType42 = read4(h);
1975 h->post.maxMemType42 = read4(h);
1976 h->post.minMemType1 = read4(h);
1977 h->post.maxMemType1 = read4(h);
1978
1979 if (h->flags & CID_FONT)
1980 return; /* Don't read glyph names for CID fonts */
1981
1982 if (h->post.format != 0x00020000) {
1983 buildGIDNames(h);
1984 return;
1985 }
1986
1987 if (invalidStreamOffset(h, table->offset + table->length - 1)) {
1988 message(h, "post: table truncated");
1989 goto parseError;
1990 }
1991
1992 srcSeek(h, table->offset + POST_HEADER_SIZE);
1993
1994 /* Parse format 2.0 data */
1995 numGlyphs = read2(h);
1996 if (numGlyphs != h->glyphs.cnt)
1997 message(h, "post 2.0: name index size doesn't match numGlyphs");
1998
1999 /* Validate table length against size of glyphNameIndex */
2000 length = (long)(table->length - (srcTell(h) - table->offset));
2001 if (length < numGlyphs * 2) {
2002 message(h, "post 2.0: table truncated (table ignored)");
2003 goto parseError;
2004 }
2005
2006 /* Read name index */
2007 dnaSET_CNT(h->post.fmt2.glyphNameIndex, numGlyphs);
2008 strCount = 0;
2009 for (i = 0; i < numGlyphs; i++) {
2010 unsigned short nid = read2(h);
2011 h->post.fmt2.glyphNameIndex.array[i] = nid;
2012 if (nid > 32767) {
2013 message(h, "post 2.0: invalid name id (table ignored)");
2014 goto parseError;
2015 } else if (nid > 257)
2016 strCount = MAX(strCount, nid-257);
2017 }
2018
2019 /* Read string data */
2020 length = (long)(table->length - (srcTell(h) - table->offset));
2021 dnaSET_CNT(h->post.fmt2.buf, length + 1);
2022 srcRead(h, length, h->post.fmt2.buf.array);
2023
2024 /* Build C strings array */
2025 dnaSET_CNT(h->post.fmt2.strings, strCount);
2026 p = h->post.fmt2.buf.array;
2027 end = p + length;
2028 for (i = 0; i < h->post.fmt2.strings.cnt; i++) {
2029 length = *(uint8_t *)p;
2030 *p++ = '\0';
2031 h->post.fmt2.strings.array[i] = p;
2032 p += length;
2033 if (p > end) {
2034 message(h, "post 2.0: invalid strings");
2035 goto parseError;
2036 }
2037 }
2038 *p = '\0';
2039 if (p != end)
2040 message(h, "post 2.0: string data didn't reach end of table");
2041
2042 return; /* Success */
2043
2044 parseError:
2045 /* We managed to read the header but the rest of the table had an error that
2046 prevented reading some (or all) glyph names. We set the the post format
2047 to a value that will allow us to use the header values but will prevent
2048 us from using any glyph name data which is likely missing or invalid */
2049 h->post.format = 0x00000001;
2050 buildGIDNames(h);
2051 }
2052
2053 /* Read MVAR table for font wide variable metrics. */
2054 static void MVARread(cfrCtx h) {
2055 abfTopDict *top = &h->top;
2056 float thickness, position;
2057
2058 if (!var_lookupMVAR(&h->cb.shstm, h->cff2.mvar, h->cff2.axisCount, h->cff2.ndv, MVAR_unds_tag, &thickness)) {
2059 top->UnderlineThickness += thickness;
2060 top->UnderlinePosition -= thickness / 2;
2061 }
2062 if (!var_lookupMVAR(&h->cb.shstm, h->cff2.mvar, h->cff2.axisCount, h->cff2.ndv, MVAR_undo_tag, &position)) {
2063 top->UnderlinePosition += position;
2064 }
2065 }
2066
2067 /* Initialize from predefined charset */
2068 static void predefCharset(cfrCtx h, int cnt, const SID *charset) {
2069 long gid;
2070
2071 if (cnt > h->glyphs.cnt)
2072 /* Font contains fewer glyphs than predef charset; adjust count */
2073 cnt = h->glyphs.cnt;
2074
2075 for (gid = 0; gid < cnt; gid++)
2076 addID(h, (unsigned short)gid, charset[gid]);
2077 }
2078
2079 static void readCharSetFromPost(cfrCtx h) {
2080 long gid;
2081 char *p;
2082 long lenStrings = ARRAY_LEN(stdstrs);
2083
2084 if (!(h->flags & CFR_IS_CFF2)) {
2085 Offset offset;
2086 unsigned long i;
2087
2088 /* init string.offsets and h->string.ptrs */
2089 h->index.string.count = (short)h->glyphs.cnt;
2090 dnaSET_CNT(h->string.offsets, h->index.string.count + 1);
2091 dnaSET_CNT(h->string.ptrs, h->index.string.count);
2092
2093 /* Compute string data size */
2094 lenStrings = (h->index.string.count == 0) ? 0 : (h->region.StringINDEX.end - h->index.string.data + 1 + /* String data bytes */
2095 h->index.string.count); /* Null termination */
2096
2097 /* Allocate buffers */
2098 dnaSET_CNT(h->string.offsets, h->index.string.count + 1);
2099 dnaSET_CNT(h->string.ptrs, h->index.string.count);
2100 /* Append char names after the font name already in the string buffer */
2101 p = &h->string.buf.array[h->string.buf.cnt];
2102 dnaSET_CNT(h->string.buf, h->string.buf.cnt + lenStrings);
2103
2104 if (h->index.string.count == 0)
2105 return; /* Empty string INDEX */
2106
2107 /* Read string offsets */
2108 srcSeek(h, h->index.string.offset);
2109 offset = readN(h, h->index.string.offSize);
2110 for (i = 0; i < h->index.string.count; i++) {
2111 long length;
2112 h->string.offsets.array[i] = offset;
2113 offset = readN(h, h->index.string.offSize);
2114
2115 /* Compute and validate object length */
2116 length = offset - h->string.offsets.array[i];
2117 if (length < 0 || length > 65535)
2118 fatal(h, cfrErrINDEXOffset);
2119 }
2120 h->string.offsets.array[i] = offset;
2121
2122 /* Read string data */
2123 for (i = 0; i < (unsigned long)h->string.ptrs.cnt; i++) {
2124 long length =
2125 h->string.offsets.array[i + 1] - h->string.offsets.array[i];
2126 srcRead(h, length, p);
2127 h->string.ptrs.array[i] = p;
2128 p += length;
2129 *p++ = '\0';
2130 }
2131 }
2132
2133 for (gid = 0; gid < h->glyphs.cnt; gid++) {
2134 abfGlyphInfo *info = &h->glyphs.array[gid];
2135 info->gname.ptr = post2GetName(h, (SID)gid);
2136 }
2137 }
2138
2139 /* Read charset */
2140 static void readCharset(cfrCtx h) {
2141 /* Predefined charsets */
2142 static const SID isocs[] =
2143 {
2144 0, /* .notdef */
2145 #include "isocs0.h"
2146 };
2147 static const SID excs[] =
2148 {
2149 0, /* .notdef */
2150 #include "excs0.h"
2151 };
2152 static const SID exsubcs[] =
2153 {
2154 0, /* .notdef */
2155 #include "exsubcs0.h"
2156 };
2157
2158 if (h->header.major == 2) {
2159 postRead(h);
2160 if (h->cff2.mvar)
2161 MVARread(h);
2162 if (!(h->flags & CID_FONT))
2163 readCharSetFromPost(h);
2164 else {
2165 long gid;
2166 for (gid = 0; gid < h->glyphs.cnt; gid++) {
2167 abfGlyphInfo *info = &h->glyphs.array[gid];
2168 info->cid = (unsigned short)gid;
2169 }
2170 }
2171 return;
2172 }
2173
2174 switch (h->region.Charset.begin) {
2175 case cff_ISOAdobeCharset:
2176 predefCharset(h, ARRAY_LEN(isocs), isocs);
2177 break;
2178 case cff_ExpertCharset:
2179 predefCharset(h, ARRAY_LEN(excs), excs);
2180 break;
2181 case cff_ExpertSubsetCharset:
2182 predefCharset(h, ARRAY_LEN(exsubcs), exsubcs);
2183 break;
2184 default: {
2185 /* Custom charset */
2186 long gid;
2187 int size = 2;
2188
2189 srcSeek(h, h->region.Charset.begin);
2190
2191 gid = 0;
2192 addID(h, gid++, 0); /* .notdef */
2193
2194 switch (read1(h)) {
2195 case 0:
2196 for (; gid < h->glyphs.cnt; gid++)
2197 addID(h, gid, read2(h));
2198 break;
2199 case 1:
2200 size = 1;
2201 /* Fall through */
2202 case 2:
2203 while (gid < h->glyphs.cnt) {
2204 unsigned short id = read2(h);
2205 long nLeft = readN(h, size);
2206 while (nLeft-- >= 0) {
2207 if (gid >= h->glyphs.cnt) {
2208 message(h, "extra mappings in Charset ignored");
2209 break;
2210 }
2211 addID(h, gid++, id++);
2212 }
2213 }
2214 break;
2215 default:
2216 fatal(h, cfrErrCharsetFmt);
2217 }
2218 h->region.Charset.end = (long)srcTell(h);
2219 } break;
2220 }
2221 }
2222
2223 /* -------------------------------- Encoding ------------------------------- */
2224
2225 /* Add encoding to glyph. */
2226 static void encAdd(cfrCtx h, abfGlyphInfo *info, unsigned short code) {
2227 abfEncoding *enc = &info->encoding;
2228 if (enc->code == ABF_GLYPH_UNENC) {
2229 /* First encoding; initialize */
2230 enc->code = code;
2231 enc->next = NULL;
2232 } else {
2233 /* Second or subsequent encoding; link new encoding */
2234 abfEncoding *_new = h->encfree;
2235 if (_new == NULL)
2236 /* Get node from heap */
2237 _new = (abfEncoding *)memNew(h, sizeof(abfEncoding));
2238 else
2239 /* Remove head node from free list */
2240 h->encfree = _new->next;
2241
2242 _new->code = code;
2243 _new->next = enc->next;
2244 enc->next = _new;
2245 h->flags |= FREE_ENCODINGS;
2246 }
2247 }
2248
2249 /* Put encoding node list on free list. */
2250 static void encReuse(cfrCtx h, abfEncoding *node) {
2251 if (node == NULL)
2252 return;
2253 encReuse(h, node->next);
2254 node->next = h->encfree;
2255 h->encfree = node;
2256 }
2257
2258 /* Reuse encoding node list. */
2259 static void encListReuse(cfrCtx h) {
2260 long i;
2261
2262 if (!(h->flags & FREE_ENCODINGS))
2263 return; /* Font has no multiple encodings */
2264
2265 /* Put multiple encodings back on free list */
2266 for (i = 0; i < h->glyphs.cnt; i++) {
2267 abfEncoding *enc = &h->glyphs.array[i].encoding;
2268 if (enc->code != ABF_GLYPH_UNENC)
2269 encReuse(h, enc->next);
2270 }
2271 h->flags &= ~FREE_ENCODINGS;
2272 }
2273
2274 /* Free encoding node list. */
2275 static void encListFree(cfrCtx h, abfEncoding *node) {
2276 if (node == NULL)
2277 return;
2278 encListFree(h, node->next);
2279 memFree(h, node);
2280 }
2281
2282 /* Initialize from predefined encoding */
2283 static void predefEncoding(cfrCtx h, int cnt, const uint8_t *encoding) {
2284 long gid;
2285 for (gid = 0; gid < h->glyphs.cnt; gid++) {
2286 abfGlyphInfo *info = &h->glyphs.array[gid];
2287 SID sid = (SID)info->gname.impl;
2288 if (sid >= cnt)
2289 break;
2290 if (encoding[sid] != 0)
2291 encAdd(h, info, encoding[sid]);
2292 }
2293 }
2294
2295 /* Read encoding */
2296 static void readEncoding(cfrCtx h) {
2297 switch (h->region.Encoding.begin) {
2298 case cff_StandardEncoding:
2299 predefEncoding(h, ARRAY_LEN(stdenc), stdenc);
2300 break;
2301 case cff_ExpertEncoding:
2302 predefEncoding(h, ARRAY_LEN(exenc), exenc);
2303 break;
2304 default: {
2305 /* Custom encoding */
2306 int i;
2307 int cnt;
2308 int fmt;
2309 long gid = 1; /* Skip glyph 0 (.notdef) */
2310
2311 /* Read format byte */
2312 srcSeek(h, h->region.Encoding.begin);
2313 fmt = read1(h);
2314
2315 switch (fmt & 0x7f) {
2316 case 0:
2317 cnt = read1(h);
2318 while (gid <= cnt) {
2319 if (gid >= h->glyphs.cnt)
2320 fatal(h, cfrErrEncodingFmt);
2321 encAdd(h, &h->glyphs.array[gid++], read1(h));
2322 }
2323 break;
2324 case 1:
2325 cnt = read1(h);
2326 while (cnt--) {
2327 short code = read1(h);
2328 int nLeft = read1(h);
2329 while (nLeft-- >= 0) {
2330 if (gid >= h->glyphs.cnt)
2331 fatal(h, cfrErrEncodingFmt);
2332 encAdd(h, &h->glyphs.array[gid++], code++);
2333 }
2334 }
2335 break;
2336 default:
2337 fatal(h, cfrErrEncodingFmt);
2338 }
2339 if (fmt & 0x80) {
2340 /* Read supplementary encoding */
2341 cnt = read1(h);
2342
2343 for (i = 0; i < cnt; i++) {
2344 unsigned short code = read1(h);
2345 SID sid = read2(h);
2346
2347 /* Search for glyph with this SID. Glyphs with multiple
2348 encodings are rare so linear search is acceptable */
2349 for (gid = 0; gid < h->glyphs.cnt; gid++) {
2350 abfGlyphInfo *info = &h->glyphs.array[gid];
2351 if (info->gname.impl == sid) {
2352 /* Found match: add encoding to list */
2353 encAdd(h, info, code);
2354 goto next;
2355 }
2356 }
2357
2358 fatal(h, cfrErrEncodingSupp);
2359
2360 next:;
2361 }
2362 }
2363 h->region.Encoding.end = (long)srcTell(h);
2364 } break;
2365 }
2366 }
2367
2368 /* -------------------------------- FDSelect ------------------------------- */
2369
2370 /* Read FDSelect */
2371 static void readFDSelect(cfrCtx h) {
2372 uint32_t gid;
2373
2374 if (h->region.FDSelect.begin == -1)
2375 fatal(h, cfrErrNoFDSelect);
2376
2377 srcSeek(h, h->region.FDSelect.begin);
2378 switch (read1(h)) {
2379 case 0: {
2380 for (gid = 0; gid < h->glyphs.cnt; gid++) {
2381 uint8_t fd = read1(h);
2382 if (fd >= h->FDArray.cnt)
2383 fatal(h, cfrErrFDSelectFmt);
2384 h->glyphs.array[gid].iFD = fd;
2385 }
2386 } break;
2387 case 3: {
2388 uint16_t nRanges = read2(h);
2389
2390 gid = read2(h);
2391 while (nRanges--) {
2392 uint8_t fd = read1(h);
2393 uint16_t next = read2(h);
2394
2395 while (gid < next) {
2396 if (gid >= h->glyphs.cnt || fd >= h->FDArray.cnt)
2397 fatal(h, cfrErrFDSelectFmt);
2398 h->glyphs.array[gid++].iFD = fd;
2399 }
2400 }
2401 } break;
2402 case 4: {
2403 uint32_t nRanges = read4(h);
2404
2405 gid = read4(h);
2406 while (nRanges--) {
2407 uint16_t fd = read2(h);
2408 uint32_t next = read4(h);
2409
2410 while (gid < next) {
2411 if (gid >= h->glyphs.cnt || fd >= h->FDArray.cnt)
2412 fatal(h, cfrErrFDSelectFmt);
2413 h->glyphs.array[gid++].iFD = fd;
2414 }
2415 }
2416 } break;
2417 default:
2418 fatal(h, cfrErrFDSelectFmt);
2419 }
2420 h->region.FDSelect.end = (long)srcTell(h);
2421 }
2422
2423 /* ------------------------------- CFF2 glyph callbacks ------------------------------- */
2424
2425 static float cff2GetWidth(cff2GlyphCallbacks *cb, unsigned short gid) {
2426 cfrCtx h = (cfrCtx)cb->direct_ctx;
2427 var_glyphMetrics metrics;
2428
2429 if (!var_lookuphmtx(&h->cb.shstm, h->cff2.hmtx, h->cff2.axisCount, h->cff2.ndv, gid, &metrics)) {
2430 return metrics.width;
2431 }
2432
2433 return .0f;
2434 }
2435
2436 /* ------------------------------- make up info missing from CFF2 ------------------------------- */
2437 typedef dnaDCL(abfString *, strPtrArray);
2438
2439 static void addString(cfrCtx h, strPtrArray *ptrs, abfString *abfStr, char *str) {
2440 long len = (long)strlen(str);
2441 long offset = h->string.buf.cnt;
2442
2443 *dnaNEXT(*ptrs) = abfStr;
2444 abfStr->impl = offset;
2445 dnaSET_CNT(h->string.buf, offset + len + 1);
2446 STRCPY_S(&h->string.buf.array[offset], len + 1, str);
2447
2448 abfStr->ptr = &h->string.buf.array[offset]; /* needs to be updated after adding all strings */
2449 }
2450
2451 /* Update string pointers that might have become stale due to buffer reallocation */
2452 static void resetStringPtrs(cfrCtx h, strPtrArray *ptrs) {
2453 long i;
2454
2455 for (i = 0; i < ptrs->cnt; i++) {
2456 abfString *abfStr = ptrs->array[i];
2457 abfStr->ptr = &h->string.buf.array[abfStr->impl];
2458 }
2459 }
2460
2461 static long generateInstancePSName(cfrCtx h, char *nameBuffer, long nameBufferLen) {
2462 long nameLen;
2463
2464 /* Get a named-instance name from the fvar table, if it is preferred and one is available */
2465 if (!(h->flags & CFR_UNUSE_VF_NAMED_INSTANCE)) {
2466 nameLen = nam_getNamedInstancePSName(h->cff2.name, h->cff2.axes, &h->cb.shstm,
2467 h->cff2.UDV, h->cff2.axisCount, -1,
2468 nameBuffer, nameBufferLen);
2469 if (nameLen > 0)
2470 return nameLen;
2471 }
2472
2473 /* Generate an instance name from the design vector */
2474 nameLen = nam_generateArbitraryInstancePSName(h->cff2.name, h->cff2.axes, &h->cb.shstm,
2475 h->cff2.UDV, h->cff2.axisCount,
2476 nameBuffer, nameBufferLen);
2477 if (nameLen > 0)
2478 return nameLen;
2479
2480 /* If above attempts failed, generate a last-resort name. If a naming callback
2481 is provided, try it first. */
2482 if (h->cff2.lastResortInstanceNameCallback) {
2483 char prefixBuffer[LONG_PS_NAME_LIMIT + 1];
2484 long prefixLen;
2485
2486 prefixLen = nam_getFamilyNamePrefix(h->cff2.name, &h->cb.shstm, prefixBuffer, LONG_PS_NAME_LIMIT + 1);
2487 if (prefixLen <= 0)
2488 return prefixLen;
2489
2490 nameLen = (*h->cff2.lastResortInstanceNameCallback)(h->cff2.lastResortInstanceNameClientCtx, h->cff2.UDV, h->cff2.axisCount, prefixBuffer, prefixLen, nameBuffer, nameBufferLen);
2491
2492 if (nameLen > 0)
2493 return nameLen;
2494 }
2495
2496 /* Use our own last resort name */
2497 nameLen = nam_generateLastResortInstancePSName(h->cff2.name, h->cff2.axes, &h->cb.shstm,
2498 h->cff2.UDV, h->cff2.axisCount,
2499 nameBuffer, nameBufferLen);
2500
2501 return nameLen;
2502 }
2503
2504 static void makeupCFF2Info(cfrCtx h) {
2505 abfTopDict *top = &h->top;
2506 sfrTable *table;
2507 long lenFontName;
2508 char postscriptName[LONG_PS_NAME_LIMIT + 1];
2509 char stringBuffer1[STRING_BUFFER_LIMIT + 1];
2510 char stringBuffer2[STRING_BUFFER_LIMIT + 1];
2511 unsigned long nameLengthLimit;
2512 long lenTrademark;
2513 strPtrArray strPtrs;
2514
2515 dnaINIT(h->ctx.dna, strPtrs, 10, 1);
2516
2517 DURING_EX(h->err.env)
2518
2519 /* read font version and fontBBox from head table */
2520 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('h', 'e', 'a', 'd'));
2521 if ((table != NULL) && !invalidStreamOffset(h, table->offset + 54 - 1)) {
2522 char buf[64];
2523 unsigned long version;
2524 unsigned short unitsPerEm;
2525
2526 srcSeek(h, table->offset + 4);
2527 version = read4(h);
2528 SPRINTF_S(buf, sizeof(buf), "%ld.%ld", version >> 16, (version >> 12) & 0xf); /* Apple style "fixed point" version number */
2529 addString(h, &strPtrs, &top->version, buf);
2530
2531 srcSeek(h, table->offset + 18);
2532 unitsPerEm = read2(h);
2533 if (!unitsPerEm) {
2534 message(h, "head: zero unitsPerEm (1000 assumed)");
2535 unitsPerEm = 1000;
2536 }
2537
2538 srcSeek(h, table->offset + 36);
2539 top->FontBBox[0] = (float)sread2(h);
2540 top->FontBBox[1] = (float)sread2(h);
2541 top->FontBBox[2] = (float)sread2(h);
2542 top->FontBBox[3] = (float)sread2(h);
2543
2544 /* FontMatrix has been deprecated in CFF2 font dicts
2545 * if unitsPerEm in the head table is non-standard and FontMatrix is unspecified,
2546 * synthesize one from unitsPerEm */
2547 if (unitsPerEm != 1000) {
2548 float invUPM = 1.0f / (float)unitsPerEm;
2549 long iFD;
2550
2551 for (iFD = 0; iFD < h->fdicts.cnt; iFD++) {
2552 abfFontDict *fdict = &h->fdicts.array[iFD];
2553
2554 if (fdict->FontMatrix.cnt == ABF_EMPTY_ARRAY) {
2555 fdict->FontMatrix.cnt = 6;
2556
2557 fdict->FontMatrix.array[0] = invUPM;
2558 fdict->FontMatrix.array[1] = 0.0f;
2559 fdict->FontMatrix.array[2] = 0.0f;
2560 fdict->FontMatrix.array[3] = invUPM;
2561 fdict->FontMatrix.array[4] = 0.0f;
2562 fdict->FontMatrix.array[5] = 0.0f;
2563
2564 h->top.sup.UnitsPerEm = unitsPerEm;
2565
2566 if (h->flags & CFR_USE_MATRIX) {
2567 cfrFDInfo *fd = &h->FDArray.array[iFD];
2568
2569 /* Prepare charstring transformation matrix */
2570 fd->aux.matrix[0] = 1.0f;
2571 fd->aux.matrix[1] = 0.0f;
2572 fd->aux.matrix[2] = 0.0f;
2573 fd->aux.matrix[3] = 1.0f;
2574 fd->aux.matrix[4] = 0.0f;
2575 fd->aux.matrix[5] = 0.0f;
2576 h->fd->aux.flags |= T2C_USE_MATRIX;
2577 }
2578 }
2579 }
2580 }
2581 }
2582
2583 /* read isFixedPitch, ItalicAngle, UnderlinePosition, UnderlineThickness from post table */
2584 table = sfrGetTableByTag(h->ctx.sfr, CTL_TAG('p', 'o', 's', 't'));
2585 if ((table != NULL) && !invalidStreamOffset(h, table->offset + 32 - 1)) {
2586 srcSeek(h, table->offset + 4);
2587 top->ItalicAngle = (float)(sread4(h) / 65536.0);
2588 top->UnderlinePosition = (float)sread2(h);
2589 top->UnderlineThickness = (float)sread2(h);
2590 top->UnderlinePosition -= top->UnderlineThickness / 2;
2591 top->isFixedPitch = read4(h) != 0;
2592 }
2593
2594 /* read Notice, FullName, FamilyName, Copyright from name table */
2595 lenFontName = nam_getASCIIName(h->cff2.name, &h->cb.shstm, stringBuffer1, sizeof(stringBuffer1), NAME_ID_FULL, 0);
2596 if (lenFontName > 0)
2597 addString(h, &strPtrs, &h->top.FullName, stringBuffer1);
2598 lenFontName = nam_getASCIIName(h->cff2.name, &h->cb.shstm, stringBuffer1, sizeof(stringBuffer1), NAME_ID_FAMILY, 0);
2599 if (lenFontName > 0)
2600 addString(h, &strPtrs, &h->top.FamilyName, stringBuffer1);
2601 lenFontName = nam_getASCIIName(h->cff2.name, &h->cb.shstm, stringBuffer1, sizeof(stringBuffer1), NAME_ID_COPYRIGHT, 0);
2602 if (lenFontName > 0)
2603 addString(h, &strPtrs, &h->top.Copyright, stringBuffer1);
2604 lenTrademark = nam_getASCIIName(h->cff2.name, &h->cb.shstm, stringBuffer2, sizeof(stringBuffer2), NAME_ID_TRADEMARK, 0);
2605 if (lenFontName > 0 && lenTrademark > 0 && ((unsigned long)(lenFontName + lenTrademark) + 2 < sizeof(stringBuffer1))) { /* concatenate copyright and trademark strings */
2606 STRCAT_S(stringBuffer1, STRING_BUFFER_LIMIT, " ");
2607 STRCAT_S(stringBuffer1, STRING_BUFFER_LIMIT, stringBuffer2);
2608 }
2609 if (lenFontName > 0)
2610 addString(h, &strPtrs, &h->top.Notice, stringBuffer1);
2611
2612 /* generate PostScript name for the instance */
2613 if (h->flags & CFR_SHORT_VF_NAME)
2614 nameLengthLimit = SHORT_PS_NAME_LIMIT;
2615 else
2616 nameLengthLimit = LONG_PS_NAME_LIMIT;
2617
2618 /* generate an instance PostScript name */
2619 lenFontName = generateInstancePSName(h, postscriptName, nameLengthLimit + 1);
2620
2621 if (lenFontName > 0) {
2622 addString(h, &strPtrs, &h->fdicts.array[0].FontName, postscriptName);
2623 }
2624
2625 /* Load CIDFontName from name table and make up CID font ROS */
2626 if (h->flags & CID_FONT) {
2627 lenFontName = nam_getASCIIName(h->cff2.name, &h->cb.shstm, postscriptName, sizeof(postscriptName), NAME_ID_CIDFONTNAME, 1);
2628 if (lenFontName <= 0) /* if no CID font name in the name table, put PS name instead */
2629 lenFontName = nam_getASCIIName(h->cff2.name, &h->cb.shstm, postscriptName, sizeof(postscriptName), NAME_ID_POSTSCRIPT, 1);
2630
2631 if (lenFontName > 0)
2632 addString(h, &strPtrs, &h->top.cid.CIDFontName, postscriptName);
2633 addString(h, &strPtrs, &h->top.cid.Registry, "Adobe");
2634 addString(h, &strPtrs, &h->top.cid.Ordering, "Identity");
2635 h->top.cid.Supplement = 1;
2636 }
2637
2638 resetStringPtrs(h, &strPtrs);
2639 dnaFREE(strPtrs);
2640 HANDLER
2641 dnaFREE(strPtrs);
2642 RERAISE;
2643 END_HANDLER
2644 }
2645
2646 void cfrSetLastResortInstanceNameCallback(cfrCtx h, cfrlastResortInstanceNameCallback cb, void *clientCtx) {
2647 h->cff2.lastResortInstanceNameClientCtx = clientCtx;
2648 h->cff2.lastResortInstanceNameCallback = cb;
2649 }
2650
2651 /* ------------------------------- Interface ------------------------------- */
2652
2653 /* Report absfont error message to debug stream. */
2654 static void report_error(abfErrCallbacks *cb, int err_code, int iFD) {
2655 cfrCtx h = (cfrCtx)cb->ctx;
2656 if (iFD == -1)
2657 message(h, "%s (ignored)", abfErrStr(err_code));
2658 else
2659 message(h, "%s FD[%d] (ignored)", abfErrStr(err_code), iFD);
2660 }
2661
2662 /* Begin reading new font. */
2663 int cfrBegFont(cfrCtx h, long flags, long origin, int ttcIndex, abfTopDict **top, float *UDV) {
2664 long i;
2665 ctlRegion region;
2666 short gi_flags; /* abfGlyphInfo flags */
2667
2668 if (flags & CFR_FLATTEN_VF)
2669 flags |= CFR_CFF2_ONLY;
2670
2671 /* Set error handler */
2672 DURING_EX(h->err.env)
2673
2674 /* Initialize top DICT */
2675 abfInitTopDict(&h->top);
2676
2677 srcOpen(h, flags, origin, ttcIndex);
2678
2679 /* Initialize */
2680 h->flags = flags & 0xffff;
2681 h->fd = NULL;
2682 h->glyphsByName.cnt = 0;
2683 h->glyphsByCID.cnt = 0;
2684 memset(h->stdEnc2GID, 0, sizeof(h->stdEnc2GID));
2685 dnaSET_CNT(h->FDArray, 1);
2686 dnaSET_CNT(h->fdicts, 1);
2687 memset(h->fdicts.array, 0, sizeof(h->fdicts.array[0]));
2688 initRegion(&h->region.NameINDEX);
2689 initRegion(&h->region.StringINDEX);
2690 initRegion(&h->region.Charset);
2691 initRegion(&h->region.Encoding);
2692 initRegion(&h->region.FDSelect);
2693 initRegion(&h->region.VarStore);
2694 initRegion(&h->region.CharStringsINDEX);
2695 initRegion(&h->region.FDArrayINDEX);
2696 initFDInfo(h, 0);
2697 h->region.Encoding.begin = cff_ISOAdobeCharset;
2698 h->region.Encoding.end = -1;
2699 h->region.Charset.begin = cff_StandardEncoding;
2700 h->region.Charset.end = -1;
2701
2702 /* Read header */
2703 h->region.Header.begin = h->src.origin;
2704 h->header.major = read1(h);
2705 h->header.minor = read1(h);
2706 h->header.hdrSize = read1(h);
2707
2708 if ((h->header.major != 1) && (h->header.major != 2))
2709 fatal(h, cfrErrBadFont);
2710 h->region.Header.end = h->src.origin + h->header.hdrSize;
2711
2712 if (h->header.major == 1) {
2713 h->header.offSize = read1(h);
2714 /* Read name INDEX */
2715 h->region.NameINDEX.begin = h->region.Header.end;
2716
2717 readINDEX(h, &h->region.NameINDEX, &h->index.name);
2718 /* Read top INDEX */
2719
2720 h->region.TopDICTINDEX.begin = h->region.NameINDEX.end;
2721 readINDEX(h, &h->region.TopDICTINDEX, &h->index.top);
2722 } else {
2723 /* We use the TopDICTINDEX region to just hold the TopDict data block. */
2724 h->header.offSize = (OffSize)read2(h); /* In CFF2, this is the size of the Top Dict. */
2725 h->region.TopDICTINDEX.begin = h->region.Header.end;
2726 h->region.TopDICTINDEX.end = h->region.TopDICTINDEX.begin + h->header.offSize;
2727 h->flags |= CFR_IS_CFF2;
2728
2729 h->cb.cff2.direct_ctx = h;
2730 h->cb.cff2.getWidth = cff2GetWidth;
2731
2732 /* Load CFF2 font tables */
2733 if (!(flags & CFR_SHALLOW_READ)) {
2734 unsigned short axis;
2735
2736 h->cff2.axes = var_loadaxes(h->ctx.sfr, &h->cb.shstm);
2737 h->cff2.hmtx = var_loadhmtx(h->ctx.sfr, &h->cb.shstm);
2738 h->cff2.mvar = var_loadMVAR(h->ctx.sfr, &h->cb.shstm);
2739 h->cff2.axisCount = var_getAxisCount(h->cff2.axes);
2740 if (h->cff2.axisCount > CFF2_MAX_AXES)
2741 fatal(h, cfrErrGeometry);
2742
2743 h->cff2.UDV = UDV;
2744
2745 /* normalize the variable font design vector */
2746 for (axis = 0; axis < h->cff2.axisCount; axis++) {
2747 h->cff2.ndv[axis] = 0;
2748 }
2749 if (h->cff2.UDV != NULL) {
2750 Fixed userCoords[CFF2_MAX_AXES];
2751
2752 for (axis = 0; axis < h->cff2.axisCount; axis++) {
2753 userCoords[axis] = pflttofix(&h->cff2.UDV[axis]);
2754 }
2755
2756 if (var_normalizeCoords(&h->cb.shstm, h->cff2.axes, userCoords, h->cff2.ndv)) {
2757 fatal(h, cfrErrGeometry);
2758 }
2759 }
2760
2761 /* name table */
2762 h->cff2.name = nam_loadname(h->ctx.sfr, &h->cb.shstm);
2763 }
2764 }
2765
2766 /* Read string INDEX */
2767 if (h->header.major == 1) {
2768 h->region.StringINDEX.begin = h->region.TopDICTINDEX.end;
2769 if (h->region.StringINDEX.begin > 0) {
2770 readINDEX(h, &h->region.StringINDEX, &h->index.string);
2771 /* Read strings */
2772 readStrings(h);
2773 }
2774 /* Read gsubrs INDEX */
2775 h->region.GlobalSubrINDEX.begin = h->region.StringINDEX.end;
2776 readSubrINDEX(h, &h->region.GlobalSubrINDEX, &h->gsubrs);
2777 } else {
2778 h->index.string.count = 0;
2779
2780 /* Read gsubrs INDEX */
2781 h->region.GlobalSubrINDEX.begin = h->region.TopDICTINDEX.end;
2782 readSubrINDEX(h, &h->region.GlobalSubrINDEX, &h->gsubrs);
2783 }
2784
2785 /* Read top DICT */
2786 if (h->header.major == 1) {
2787 h->top.maxstack = T2_MAX_OP_STACK;
2788 INDEXGet(h, &h->index.top, 0, &region);
2789 readDICT(h, &region, 1);
2790 } else {
2791 h->top.maxstack = CFF2_MAX_OP_STACK;
2792 /* h->index.top.begin/end already marks the span of the TopDict data. */
2793 readDICT(h, &h->region.TopDICTINDEX, 1);
2794 if (h->region.VarStore.begin > 0) {
2795 readVarStore(h);
2796 }
2797 }
2798
2799 gi_flags = 0;
2800 if (h->flags & CID_FONT) {
2801 if (!(flags & CFR_SHALLOW_READ))
2802 readFDArray(h);
2803 if (h->header.major == 1)
2804 h->top.cid.CIDFontName.ptr = h->string.buf.array;
2805 else
2806 makeupCFF2Info(h);
2807 h->top.sup.srcFontType = abfSrcFontTypeCFFCID;
2808 h->top.sup.flags |= ABF_CID_FONT;
2809 gi_flags |= ABF_GLYPH_CID;
2810 } else {
2811 if (h->header.major == 1) {
2812 readPrivate(h, 0);
2813 h->fd->fdict->FontName.ptr = h->string.buf.array;
2814 } else {
2815 if (!(flags & CFR_SHALLOW_READ)) {
2816 readFDArray(h);
2817 }
2818 makeupCFF2Info(h);
2819 }
2820 h->top.sup.srcFontType = abfSrcFontTypeCFFName;
2821 }
2822
2823 if (!(flags & CFR_SHALLOW_READ))
2824 readCharStringsINDEX(h, gi_flags);
2825
2826 /* Prepare client data */
2827 h->top.FDArray.cnt = h->fdicts.cnt;
2828 h->top.FDArray.array = h->fdicts.array;
2829 h->top.sup.nGlyphs = h->glyphs.cnt;
2830 *top = &h->top;
2831
2832 /* Validate dictionaries */
2833 if (h->stm.dbg == NULL)
2834 abfCheckAllDicts(NULL, &h->top);
2835 else {
2836 abfErrCallbacks cb;
2837 cb.ctx = h;
2838 cb.report_error = report_error;
2839 abfCheckAllDicts(&cb, &h->top);
2840 }
2841
2842 /* Fill glyphs array */
2843 if (!(flags & CFR_SHALLOW_READ)) {
2844 readCharset(h);
2845 if (h->flags & CID_FONT) {
2846 readFDSelect(h);
2847
2848 /* Mark LanguageGroup 1 glyphs */
2849 for (i = 0; i < h->glyphs.cnt; i++) {
2850 abfGlyphInfo *info = &h->glyphs.array[i];
2851 if (h->fdicts.array[info->iFD].Private.LanguageGroup == 1)
2852 info->flags |= ABF_GLYPH_LANG_1;
2853 }
2854
2855 /* We pre-multiplied the FontMatrix's in the FDArray with the one in
2856 the top dict FontMatrix so we can discard it */
2857 h->top.cid.FontMatrix.cnt = ABF_EMPTY_ARRAY;
2858 } else {
2859 if ((!(flags & CFR_NO_ENCODING)) && (h->header.major == 1))
2860 readEncoding(h);
2861
2862 if (h->fdicts.array[0].Private.LanguageGroup == 1)
2863 /* Mark all glyphs LanguageGroup 1 */
2864 for (i = 0; i < h->glyphs.cnt; i++)
2865 h->glyphs.array[i].flags |= ABF_GLYPH_LANG_1;
2866 }
2867 }
2868
2869 /* Check each Private dict contained a BlueValues operator */
2870 for (i = 0; i < h->fdicts.cnt; i++)
2871 if (!(h->FDArray.array[i].flags & SEEN_BLUE_VALUES))
2872 message(h, "/BlueValues missing: FD[%ld]", i);
2873
2874 HANDLER
2875 return Exception.Code;
2876 END_HANDLER
2877
2878 return cfrSuccess;
2879 }
2880
2881 /* Read charstring. */
2882 static void readGlyph(cfrCtx h,
2883 unsigned short gid, abfGlyphCallbacks *glyph_cb) {
2884 int result;
2885 abfGlyphInfo *info = &h->glyphs.array[gid];
2886 t2cAuxData *aux = &h->FDArray.array[info->iFD].aux;
2887 cff2GlyphCallbacks *cff2_cb = NULL;
2888
2889 /* Begin glyph and mark it as seen */
2890 result = glyph_cb->beg(glyph_cb, info);
2891 info->flags |= ABF_GLYPH_SEEN;
2892 info->blendInfo.vsindex = aux->default_vsIndex;
2893
2894 /* Check result */
2895 switch (result) {
2896 case ABF_CONT_RET:
2897 aux->flags &= ~T2C_WIDTH_ONLY;
2898 break;
2899 case ABF_WIDTH_RET:
2900 aux->flags |= T2C_WIDTH_ONLY;
2901 break;
2902 case ABF_SKIP_RET:
2903 return;
2904 case ABF_QUIT_RET:
2905 fatal(h, cfrErrCstrQuit);
2906 case ABF_FAIL_RET:
2907 fatal(h, cfrErrCstrFail);
2908 }
2909
2910 if (h->flags & CFR_IS_CFF2) {
2911 aux->flags |= T2C_IS_CFF2;
2912 cff2_cb = &h->cb.cff2;
2913 }
2914 if (h->flags & CFR_FLATTEN_VF)
2915 aux->flags |= T2C_FLATTEN_BLEND;
2916
2917 /* Parse charstring */
2918 info->blendInfo.vsindex = aux->default_vsIndex;
2919 info->blendInfo.maxstack = CFF2_MAX_OP_STACK;
2920 result = t2cParse(info->sup.begin, info->sup.end, aux, gid, cff2_cb, glyph_cb, &h->cb.mem);
2921 if (result) {
2922 if (info->flags & ABF_GLYPH_CID)
2923 message(h, "(t2c) %s <cid-%hu>", t2cErrStr(result), info->cid);
2924 else
2925 message(h, "(t2c) %s <%s>", t2cErrStr(result), info->gname.ptr);
2926 fatal(h, cfrErrCstrParse);
2927 }
2928
2929 /* End glyph */
2930 glyph_cb->end(glyph_cb);
2931 }
2932
2933 /* Iterate through all glyphs in font. */
2934 int cfrIterateGlyphs(cfrCtx h, abfGlyphCallbacks *glyph_cb)
2935
2936 {
2937 long i;
2938
2939 /* Set error handler */
2940 DURING_EX(h->err.env)
2941
2942 for (i = 0; i < h->glyphs.cnt; i++)
2943 readGlyph(h, (unsigned short)i, glyph_cb);
2944
2945 HANDLER
2946 return Exception.Code;
2947 END_HANDLER
2948
2949 return cfrSuccess;
2950 }
2951
2952 /* Get glyph from font by its tag. */
2953 int cfrGetGlyphByTag(cfrCtx h,
2954 unsigned short tag, abfGlyphCallbacks *glyph_cb) {
2955 if (tag >= h->glyphs.cnt)
2956 return cfrErrNoGlyph;
2957
2958 /* Set error handler */
2959 DURING_EX(h->err.env)
2960
2961 readGlyph(h, tag, glyph_cb);
2962
2963 HANDLER
2964 return Exception.Code;
2965 END_HANDLER
2966
2967 return cfrSuccess;
2968 }
2969
2970 /* Compare glyph names. */
2971 static int CTL_CDECL cmpNames(const void *first, const void *second, void *ctx) {
2972 cfrCtx h = (cfrCtx)ctx;
2973 return strcmp(h->glyphs.array[*(unsigned short *)first].gname.ptr,
2974 h->glyphs.array[*(unsigned short *)second].gname.ptr);
2975 }
2976
2977 /* Match glyph name. */
2978 static int CTL_CDECL matchName(const void *key, const void *value, void *ctx) {
2979 cfrCtx h = (cfrCtx)ctx;
2980 return strcmp((char *)key,
2981 h->glyphs.array[*(unsigned short *)value].gname.ptr);
2982 }
2983
2984 /* Get glyph from font by its name. */
2985 int cfrGetGlyphByName(cfrCtx h, char *gname, abfGlyphCallbacks *glyph_cb) {
2986 size_t index;
2987
2988 if (h->flags & CID_FONT)
2989 return cfrErrNoGlyph;
2990
2991 if (h->glyphsByName.cnt == 0) {
2992 /* Make lookup array */
2993 long i;
2994 dnaSET_CNT(h->glyphsByName, h->glyphs.cnt);
2995 for (i = 0; i < h->glyphsByName.cnt; i++)
2996 h->glyphsByName.array[i] = (unsigned short)i;
2997 ctuQSort(h->glyphsByName.array, h->glyphsByName.cnt,
2998 sizeof(h->glyphsByName.array[0]), cmpNames, h);
2999 }
3000
3001 if (!ctuLookup(gname, h->glyphsByName.array, h->glyphsByName.cnt,
3002 sizeof(h->glyphsByName.array[0]), matchName, &index, h))
3003 return cfrErrNoGlyph;
3004
3005 /* Set error handler */
3006 DURING_EX(h->err.env)
3007
3008 readGlyph(h, (unsigned short)h->glyphsByName.array[index], glyph_cb);
3009
3010 HANDLER
3011 return Exception.Code;
3012 END_HANDLER
3013
3014 return cfrSuccess;
3015 }
3016
3017 /* Compare cids. */
3018 static int CTL_CDECL cmpCIDs(const void *first, const void *second, void *ctx) {
3019 cfrCtx h = (cfrCtx)ctx;
3020 unsigned short a = h->glyphs.array[*(unsigned short *)first].cid;
3021 unsigned short b = h->glyphs.array[*(unsigned short *)second].cid;
3022 if (a < b)
3023 return -1;
3024 else if (a > b)
3025 return 1;
3026 else
3027 return 0;
3028 }
3029
3030 /* Match CID value. */
3031 static int CTL_CDECL matchCID(const void *key, const void *value, void *ctx) {
3032 cfrCtx h = (cfrCtx)ctx;
3033 unsigned short a = *(unsigned short *)key;
3034 unsigned short b = h->glyphs.array[*(unsigned short *)value].cid;
3035 if (a < b)
3036 return -1;
3037 else if (a > b)
3038 return 1;
3039 else
3040 return 0;
3041 }
3042
3043 /* Get glyph from font by its CID. */
3044 int cfrGetGlyphByCID(cfrCtx h, unsigned short cid, abfGlyphCallbacks *glyph_cb) {
3045 volatile unsigned short gid; /* volatile suppresses optimizer warning */
3046 size_t index;
3047
3048 if (!(h->flags & CID_FONT))
3049 return cfrErrNoGlyph;
3050
3051 if (h->glyphs.array[h->glyphs.cnt - 1].cid == h->glyphs.cnt - 1) {
3052 /* Non-subset font; index by CID */
3053 if (cid >= h->glyphs.cnt)
3054 return cfrErrNoGlyph;
3055 else
3056 gid = cid;
3057 } else {
3058 /* Subset font; search for matching CID */
3059 if (h->glyphsByCID.cnt == 0) {
3060 /* Make lookup array */
3061 long i;
3062 dnaSET_CNT(h->glyphsByCID, h->glyphs.cnt);
3063 for (i = 0; i < h->glyphsByCID.cnt; i++)
3064 h->glyphsByCID.array[i] = (unsigned short)i;
3065 /* Sort glyphs array by cid before doing search. */
3066 ctuQSort(h->glyphsByCID.array, h->glyphsByCID.cnt,
3067 sizeof(h->glyphsByCID.array[0]), cmpCIDs, h);
3068 }
3069
3070 if (!ctuLookup(&cid, h->glyphsByCID.array, h->glyphsByCID.cnt,
3071 sizeof(h->glyphsByCID.array[0]), matchCID, &index, h))
3072 return cfrErrNoGlyph;
3073
3074 gid = h->glyphsByCID.array[index];
3075 }
3076
3077 /* Set error handler */
3078 DURING_EX(h->err.env)
3079
3080 readGlyph(h, gid, glyph_cb);
3081
3082 HANDLER
3083 return Exception.Code;
3084 END_HANDLER
3085
3086 return cfrSuccess;
3087 }
3088
3089 /* Get standard-encoded glyph from font. */
3090 int cfrGetGlyphByStdEnc(cfrCtx h, int stdcode, abfGlyphCallbacks *glyph_cb) {
3091 unsigned short gid;
3092
3093 if (stdcode < 0 || stdcode >= 256 || (gid = h->stdEnc2GID[stdcode]) == 0)
3094 return cfrErrNoGlyph;
3095
3096 /* Set error handler */
3097 DURING_EX(h->err.env)
3098
3099 readGlyph(h, gid, glyph_cb);
3100
3101 HANDLER
3102 return Exception.Code;
3103 END_HANDLER
3104
3105 return cfrSuccess;
3106 }
3107
3108 /* Clear record of glyphs seen by client. */
3109 int cfrResetGlyphs(cfrCtx h) {
3110 long i;
3111
3112 for (i = 0; i < h->glyphs.cnt; i++)
3113 h->glyphs.array[i].flags &= ~ABF_GLYPH_SEEN;
3114
3115 return cfrSuccess;
3116 }
3117
3118 /* Return single regions. */
3119 const cfrSingleRegions *cfrGetSingleRegions(cfrCtx h) {
3120 return &h->region;
3121 }
3122
3123 /* Return repeat regions. */
3124 const cfrRepeatRegions *cfrGetRepeatRegions(cfrCtx h, int iFD) {
3125 return (iFD < 0 || iFD >= h->FDArray.cnt) ? NULL : &h->FDArray.array[iFD].region;
3126 }
3127
3128 /* Return font DICT widths. */
3129 int cfrGetWidths(cfrCtx h, int iFD,
3130 float *defaultWidthX, float *nominalWidthX) {
3131 t2cAuxData *aux;
3132 if (iFD < 0 || iFD >= h->FDArray.cnt)
3133 return 1;
3134 aux = &h->FDArray.array[iFD].aux;
3135 *defaultWidthX = aux->defaultWidthX;
3136 *nominalWidthX = aux->nominalWidthX;
3137 return 0;
3138 }
3139
3140 /* Return table mapping standard encoding and glyph index. */
3141 const uint8_t *cfrGetStdEnc2GIDMap(cfrCtx h) {
3142 return (uint8_t *)h->stdEnc2GID;
3143 }
3144
3145 /* Finish reading font. */
3146 int cfrEndFont(cfrCtx h) {
3147 /* Close source stream */
3148 if (h->cb.stm.close(&h->cb.stm, h->stm.src) == -1)
3149 return cfrErrSrcStream;
3150
3151 encListReuse(h);
3152
3153 if (h->header.major != 1) {
3154 var_freeaxes(&h->cb.shstm, h->cff2.axes);
3155 var_freehmtx(&h->cb.shstm, h->cff2.hmtx);
3156 var_freeMVAR(&h->cb.shstm, h->cff2.mvar);
3157 nam_freename(&h->cb.shstm, h->cff2.name);
3158 }
3159
3160 return cfrSuccess;
3161 }
3162
3163 /* --------------------------- Shared source stream -------------------------- */
3164
3165 static void *sharedSrcMemNew(ctlSharedStmCallbacks *h, size_t size) {
3166 return memNew((cfrCtx)h->direct_ctx, size);
3167 }
3168
3169 static void sharedSrcMemFree(ctlSharedStmCallbacks *h, void *ptr) {
3170 memFree((cfrCtx)h->direct_ctx, ptr);
3171 }
3172
3173 static void sharedSrcSeek(ctlSharedStmCallbacks *h, long offset) {
3174 srcSeek((cfrCtx)h->direct_ctx, offset);
3175 }
3176
3177 static long sharedSrcTell(ctlSharedStmCallbacks *h) {
3178 return (long)srcTell(((cfrCtx)h->direct_ctx));
3179 }
3180
3181 static void sharedSrcRead(ctlSharedStmCallbacks *h, size_t count, char *ptr) {
3182 srcRead((cfrCtx)h->direct_ctx, count, ptr);
3183 }
3184
3185 static uint8_t sharedSrcRead1(ctlSharedStmCallbacks *h) {
3186 return read1(((cfrCtx)h->direct_ctx));
3187 }
3188
3189 static uint16_t sharedSrcRead2(ctlSharedStmCallbacks *h) {
3190 return read2(((cfrCtx)h->direct_ctx));
3191 }
3192
3193 static uint32_t sharedSrcRead4(ctlSharedStmCallbacks *h) {
3194 return read4(((cfrCtx)h->direct_ctx));
3195 }
3196
3197 void sharedSrcMessage(ctlSharedStmCallbacks *h, char *fmt, ...) {
3198 va_list ap;
3199 va_start(ap, fmt);
3200 vmessage((cfrCtx)h->direct_ctx, fmt, ap);
3201 va_end(ap);
3202 }
3203
3204 static void setupSharedStream(cfrCtx h) {
3205 h->cb.shstm.direct_ctx = h;
3206 h->cb.shstm.dna = h->ctx.dna;
3207 h->cb.shstm.memNew = sharedSrcMemNew;
3208 h->cb.shstm.memFree = sharedSrcMemFree;
3209 h->cb.shstm.seek = sharedSrcSeek;
3210 h->cb.shstm.tell = sharedSrcTell;
3211 h->cb.shstm.read = sharedSrcRead;
3212 h->cb.shstm.read1 = sharedSrcRead1;
3213 h->cb.shstm.read2 = sharedSrcRead2;
3214 h->cb.shstm.read4 = sharedSrcRead4;
3215 h->cb.shstm.message = sharedSrcMessage;
3216 }
3217
3218 /* Get version numbers of libraries. */
3219 void cfrGetVersion(ctlVersionCallbacks *cb) {
3220 if (cb->called & 1 << CFR_LIB_ID)
3221 return; /* Already enumerated */
3222
3223 /* Support libraries */
3224 abfGetVersion(cb);
3225 ctuGetVersion(cb);
3226 dnaGetVersion(cb);
3227 sfrGetVersion(cb);
3228 t2cGetVersion(cb);
3229
3230 /* This library */
3231 cb->getversion(cb, CFR_VERSION, "cffread");
3232
3233 /* Record this call */
3234 cb->called |= 1 << CFR_LIB_ID;
3235 }
3236
3237 /* Convert error code to error string. */
3238 char *cfrErrStr(int err_code) {
3239 static char *errstrs[] =
3240 {
3241 #undef CTL_DCL_ERR
3242 #define CTL_DCL_ERR(name, string) string,
3243 #include "cfrerr.h"
3244 };
3245 return (err_code < 0 || err_code >= (int)ARRAY_LEN(errstrs)) ? "unknown error" : errstrs[err_code];
3246 }
3247
3248 /* ----------------------------- Debug Support ----------------------------- */
3249
3250 #if CFR_DEBUG
3251
3252 #include <stdio.h>
3253 static void dbt2cstack(cfrCtx h) {
3254 printf("--- stack\n");
3255 if (h->stack.cnt == 0)
3256 printf("empty\n");
3257 else {
3258 int i;
3259 for (i = 0; i < h->stack.cnt; i++)
3260 printf("[%d]=%g ", i, INDEX_REAL(i));
3261 printf("\n");
3262 }
3263 }
3264
3265 /* This function just serves to suppress annoying "defined but not used"
3266 compiler messages when debugging */
3267 static void CTL_CDECL dbuse(int arg, ...) {
3268 dbuse(0, dbt2cstack);
3269 }
3270
3271 #endif /* CFR_DEBUG */