Fix svace issue
[platform/core/graphics/cairo.git] / src / cairo-cff-subset.c
1 /* -*- Mode: c; tab-width: 8; c-basic-offset: 4; indent-tabs-mode: t; -*- */
2 /* cairo - a vector graphics library with display and print output
3  *
4  * Copyright © 2006 Adrian Johnson
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it either under the terms of the GNU Lesser General Public
8  * License version 2.1 as published by the Free Software Foundation
9  * (the "LGPL") or, at your option, under the terms of the Mozilla
10  * Public License Version 1.1 (the "MPL"). If you do not alter this
11  * notice, a recipient may use your version of this file under either
12  * the MPL or the LGPL.
13  *
14  * You should have received a copy of the LGPL along with this library
15  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
17  * You should have received a copy of the MPL along with this library
18  * in the file COPYING-MPL-1.1
19  *
20  * The contents of this file are subject to the Mozilla Public License
21  * Version 1.1 (the "License"); you may not use this file except in
22  * compliance with the License. You may obtain a copy of the License at
23  * http://www.mozilla.org/MPL/
24  *
25  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
26  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
27  * the specific language governing rights and limitations.
28  *
29  * The Original Code is the cairo graphics library.
30  *
31  * The Initial Developer of the Original Code is Adrian Johnson.
32  *
33  * Contributor(s):
34  *      Adrian Johnson <ajohnson@redneon.com>
35  *      Eugeniy Meshcheryakov <eugen@debian.org>
36  */
37
38 /*
39  * Useful links:
40  * http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf
41  * http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5177.Type2.pdf
42  */
43
44 #define _BSD_SOURCE /* for snprintf(), strdup() */
45 #include "cairoint.h"
46
47 #include "cairo-array-private.h"
48 #include "cairo-error-private.h"
49
50 #if CAIRO_HAS_FONT_SUBSET
51
52 #include "cairo-scaled-font-subsets-private.h"
53 #include "cairo-truetype-subset-private.h"
54 #include <stdio.h>
55 #include <string.h>
56 #include <locale.h>
57
58 /* CFF Dict Operators. If the high byte is 0 the command is encoded
59  * with a single byte. */
60 #define BASEFONTNAME_OP  0x0c16
61 #define CIDCOUNT_OP      0x0c22
62 #define CHARSET_OP       0x000f
63 #define CHARSTRINGS_OP   0x0011
64 #define COPYRIGHT_OP     0x0c00
65 #define DEFAULTWIDTH_OP  0x0014
66 #define ENCODING_OP      0x0010
67 #define FAMILYNAME_OP    0x0003
68 #define FDARRAY_OP       0x0c24
69 #define FDSELECT_OP      0x0c25
70 #define FONTBBOX_OP      0x0005
71 #define FONTMATRIX_OP    0x0c07
72 #define FONTNAME_OP      0x0c26
73 #define FULLNAME_OP      0x0002
74 #define LOCAL_SUB_OP     0x0013
75 #define NOMINALWIDTH_OP  0x0015
76 #define NOTICE_OP        0x0001
77 #define POSTSCRIPT_OP    0x0c15
78 #define PRIVATE_OP       0x0012
79 #define ROS_OP           0x0c1e
80 #define UNIQUEID_OP      0x000d
81 #define VERSION_OP       0x0000
82 #define WEIGHT_OP        0x0004
83 #define XUID_OP          0x000e
84
85 #define NUM_STD_STRINGS 391
86
87 /* Type 2 Charstring operators */
88 #define TYPE2_hstem     0x0001
89 #define TYPE2_vstem     0x0003
90 #define TYPE2_callsubr  0x000a
91
92 #define TYPE2_return    0x000b
93 #define TYPE2_endchar   0x000e
94
95 #define TYPE2_hstemhm   0x0012
96 #define TYPE2_hintmask  0x0013
97 #define TYPE2_cntrmask  0x0014
98 #define TYPE2_vstemhm   0x0017
99 #define TYPE2_callgsubr 0x001d
100
101 #define TYPE2_rmoveto   0x0015
102 #define TYPE2_hmoveto   0x0016
103 #define TYPE2_vmoveto   0x0004
104
105
106 #define MAX_SUBROUTINE_NESTING 10 /* From Type2 Charstring spec */
107
108
109 typedef struct _cff_header {
110     uint8_t major;
111     uint8_t minor;
112     uint8_t header_size;
113     uint8_t offset_size;
114 } cff_header_t;
115
116 typedef struct _cff_index_element {
117     cairo_bool_t   is_copy;
118     unsigned char *data;
119     int            length;
120 } cff_index_element_t;
121
122 typedef struct _cff_dict_operator {
123     cairo_hash_entry_t base;
124
125     unsigned short operator;
126     unsigned char *operand;
127     int            operand_length;
128     int            operand_offset;
129 } cff_dict_operator_t;
130
131 typedef struct _cairo_cff_font {
132
133     cairo_scaled_font_subset_t *scaled_font_subset;
134     const cairo_scaled_font_backend_t *backend;
135
136     /* Font Data */
137     unsigned char       *data;
138     unsigned long        data_length;
139     unsigned char       *current_ptr;
140     unsigned char       *data_end;
141     cff_header_t        *header;
142     char                *font_name;
143     char                *ps_name;
144     cairo_hash_table_t  *top_dict;
145     cairo_hash_table_t  *private_dict;
146     cairo_array_t        strings_index;
147     cairo_array_t        charstrings_index;
148     cairo_array_t        global_sub_index;
149     cairo_array_t        local_sub_index;
150     unsigned char       *charset;
151     int                  num_glyphs;
152     cairo_bool_t         is_cid;
153     cairo_bool_t         is_opentype;
154     int                  units_per_em;
155     int                  global_sub_bias;
156     int                  local_sub_bias;
157     double               default_width;
158     double               nominal_width;
159
160     /* CID Font Data */
161     int                 *fdselect;
162     unsigned int         num_fontdicts;
163     cairo_hash_table_t **fd_dict;
164     cairo_hash_table_t **fd_private_dict;
165     cairo_array_t       *fd_local_sub_index;
166     int                 *fd_local_sub_bias;
167     double              *fd_default_width;
168     double              *fd_nominal_width;
169
170     /* Subsetted Font Data */
171     char                *subset_font_name;
172     cairo_array_t        charstrings_subset_index;
173     cairo_array_t        strings_subset_index;
174     int                  euro_sid;
175     int                 *fdselect_subset;
176     unsigned int         num_subset_fontdicts;
177     int                 *fd_subset_map;
178     int                 *private_dict_offset;
179     cairo_bool_t         subset_subroutines;
180     cairo_bool_t        *global_subs_used;
181     cairo_bool_t        *local_subs_used;
182     cairo_bool_t       **fd_local_subs_used;
183     cairo_array_t        output;
184
185     /* Subset Metrics */
186     int                 *widths;
187     int                  x_min, y_min, x_max, y_max;
188     int                  ascent, descent;
189
190     /* Type 2 charstring data */
191     int                  type2_stack_size;
192     int                  type2_stack_top_value;
193     cairo_bool_t         type2_stack_top_is_int;
194     int                  type2_num_hints;
195     int                  type2_hintmask_bytes;
196     int                  type2_nesting_level;
197     cairo_bool_t         type2_seen_first_int;
198     cairo_bool_t         type2_find_width;
199     cairo_bool_t         type2_found_width;
200     int                  type2_width;
201     cairo_bool_t         type2_has_path;
202
203 } cairo_cff_font_t;
204
205 /* Encoded integer using maximum sized encoding. This is required for
206  * operands that are later modified after encoding. */
207 static unsigned char *
208 encode_integer_max (unsigned char *p, int i)
209 {
210     *p++ = 29;
211     *p++ = i >> 24;
212     *p++ = (i >> 16) & 0xff;
213     *p++ = (i >> 8)  & 0xff;
214     *p++ = i & 0xff;
215     return p;
216 }
217
218 static unsigned char *
219 encode_integer (unsigned char *p, int i)
220 {
221     if (i >= -107 && i <= 107) {
222         *p++ = i + 139;
223     } else if (i >= 108 && i <= 1131) {
224         i -= 108;
225         *p++ = (i >> 8)+ 247;
226         *p++ = i & 0xff;
227     } else if (i >= -1131 && i <= -108) {
228         i = -i - 108;
229         *p++ = (i >> 8)+ 251;
230         *p++ = i & 0xff;
231     } else if (i >= -32768 && i <= 32767) {
232         *p++ = 28;
233         *p++ = (i >> 8)  & 0xff;
234         *p++ = i & 0xff;
235     } else {
236         p = encode_integer_max (p, i);
237     }
238     return p;
239 }
240
241 static unsigned char *
242 decode_integer (unsigned char *p, int *integer)
243 {
244     if (*p == 28) {
245         *integer = (int)(p[1]<<8 | p[2]);
246         p += 3;
247     } else if (*p == 29) {
248         *integer = (int)((p[1] << 24) | (p[2] << 16) | (p[3] << 8) | p[4]);
249         p += 5;
250     } else if (*p >= 32 && *p <= 246) {
251         *integer = *p++ - 139;
252     } else if (*p <= 250) {
253         *integer = (p[0] - 247) * 256 + p[1] + 108;
254         p += 2;
255     } else if (*p <= 254) {
256         *integer = -(p[0] - 251) * 256 - p[1] - 108;
257         p += 2;
258     } else {
259         *integer = 0;
260         p += 1;
261     }
262     return p;
263 }
264
265 static char *
266 decode_nibble (int n, char *buf)
267 {
268     switch (n)
269     {
270     case 0xa:
271         *buf++ = '.';
272         break;
273     case 0xb:
274         *buf++ = 'E';
275         break;
276     case 0xc:
277         *buf++ = 'E';
278         *buf++ = '-';
279         break;
280     case 0xd:
281         *buf++ = '-';
282         break;
283     case 0xe:
284         *buf++ = '-';
285         break;
286     case 0xf:
287         break;
288     default:
289         *buf++ = '0' + n;
290         break;
291     }
292
293     return buf;
294 }
295
296 static unsigned char *
297 decode_real (unsigned char *p, double *real)
298 {
299     const char *decimal_point;
300     int decimal_point_len;
301     int n;
302     char buffer[100];
303     char buffer2[200];
304     char *q;
305     char *buf = buffer;
306     char *buf_end = buffer + sizeof (buffer);
307
308     decimal_point = cairo_get_locale_decimal_point ();
309     decimal_point_len = strlen (decimal_point);
310
311     assert (decimal_point_len != 0);
312     assert (sizeof(buffer) + decimal_point_len < sizeof(buffer2));
313
314     p++;
315     while (buf + 2 < buf_end) {
316         n = *p >> 4;
317         buf = decode_nibble (n, buf);
318         n = *p & 0x0f;
319         buf = decode_nibble (n, buf);
320         if ((*p & 0x0f) == 0x0f) {
321             p++;
322             break;
323         }
324         p++;
325     };
326     *buf = 0;
327
328     buf = buffer;
329     if (strchr (buffer, '.')) {
330          q = strchr (buffer, '.');
331          strncpy (buffer2, buffer, q - buffer);
332          buf = buffer2 + (q - buffer);
333          strncpy (buf, decimal_point, decimal_point_len);
334          buf += decimal_point_len;
335
336         //(2017.04.17) Since securitY issue, replace strcpy to strncpy.
337         //strcpy (buf, q + 1);
338          strncpy (buf, q + 1, (buffer + sizeof(buffer)/sizeof(buffer[0])) - (q + 1));
339         //same as strncpy (buf, q + 1, 100 - (q + 1));
340
341          buf = buffer2;
342     }
343
344     if (sscanf(buf, "%lf", real) != 1)
345         *real = 0.0;
346
347     return p;
348 }
349
350 static unsigned char *
351 decode_number (unsigned char *p, double *number)
352 {
353     if (*p == 30) {
354         p = decode_real (p, number);
355     } else {
356         int i;
357         p = decode_integer (p, &i);
358         *number = i;
359     }
360     return p;
361 }
362
363 static unsigned char *
364 decode_operator (unsigned char *p, unsigned short *operator)
365 {
366     unsigned short op = 0;
367
368     op = *p++;
369     if (op == 12) {
370         op <<= 8;
371         op |= *p++;
372     }
373     *operator = op;
374     return p;
375 }
376
377 /* return 0 if not an operand */
378 static int
379 operand_length (unsigned char *p)
380 {
381     unsigned char *begin = p;
382
383     if (*p == 28)
384         return 3;
385
386     if (*p == 29)
387         return 5;
388
389     if (*p >= 32 && *p <= 246)
390         return 1;
391
392     if (*p >= 247 && *p <= 254)
393         return 2;
394
395     if (*p == 30) {
396         while ((*p & 0x0f) != 0x0f)
397             p++;
398         return p - begin + 1;
399     }
400
401     return 0;
402 }
403
404 static unsigned char *
405 encode_index_offset (unsigned char *p, int offset_size, unsigned long offset)
406 {
407     while (--offset_size >= 0) {
408         p[offset_size] = (unsigned char) (offset & 0xff);
409         offset >>= 8;
410     }
411     return p + offset_size;
412 }
413
414 static unsigned long
415 decode_index_offset(unsigned char *p, int off_size)
416 {
417     unsigned long offset = 0;
418
419     while (off_size-- > 0)
420         offset = offset*256 + *p++;
421     return offset;
422 }
423
424 static void
425 cff_index_init (cairo_array_t *index)
426 {
427     _cairo_array_init (index, sizeof (cff_index_element_t));
428 }
429
430 static cairo_int_status_t
431 cff_index_read (cairo_array_t *index, unsigned char **ptr, unsigned char *end_ptr)
432 {
433     cff_index_element_t element;
434     unsigned char *data, *p;
435     cairo_status_t status;
436     int offset_size, count, start, i;
437     int end = 0;
438
439     p = *ptr;
440     if (p + 2 > end_ptr)
441         return CAIRO_INT_STATUS_UNSUPPORTED;
442     count = get_unaligned_be16 (p);
443     p += 2;
444     if (count > 0) {
445         offset_size = *p++;
446         if (p + (count + 1)*offset_size > end_ptr)
447             return CAIRO_INT_STATUS_UNSUPPORTED;
448         data = p + offset_size*(count + 1) - 1;
449         start = decode_index_offset (p, offset_size);
450         p += offset_size;
451         for (i = 0; i < count; i++) {
452             end = decode_index_offset (p, offset_size);
453             p += offset_size;
454             if (p > end_ptr)
455                 return CAIRO_INT_STATUS_UNSUPPORTED;
456             element.length = end - start;
457             element.is_copy = FALSE;
458             element.data = data + start;
459             status = _cairo_array_append (index, &element);
460             if (unlikely (status))
461                 return status;
462             start = end;
463         }
464         p = data + end;
465     }
466     *ptr = p;
467
468     return CAIRO_STATUS_SUCCESS;
469 }
470
471 static cairo_status_t
472 cff_index_write (cairo_array_t *index, cairo_array_t *output)
473 {
474     int offset_size;
475     int offset;
476     int num_elem;
477     int i;
478     cff_index_element_t *element;
479     uint16_t count;
480     unsigned char buf[5];
481     cairo_status_t status;
482
483     num_elem = _cairo_array_num_elements (index);
484     count = cpu_to_be16 ((uint16_t) num_elem);
485     status = _cairo_array_append_multiple (output, &count, 2);
486     if (unlikely (status))
487         return status;
488
489     if (num_elem == 0)
490         return CAIRO_STATUS_SUCCESS;
491
492     /* Find maximum offset to determine offset size */
493     offset = 1;
494     for (i = 0; i < num_elem; i++) {
495         element = _cairo_array_index (index, i);
496         offset += element->length;
497     }
498     if (offset < 0x100)
499         offset_size = 1;
500     else if (offset < 0x10000)
501         offset_size = 2;
502     else if (offset < 0x1000000)
503         offset_size = 3;
504     else
505         offset_size = 4;
506
507     buf[0] = (unsigned char) offset_size;
508     status = _cairo_array_append (output, buf);
509     if (unlikely (status))
510         return status;
511
512     offset = 1;
513     encode_index_offset (buf, offset_size, offset);
514     status = _cairo_array_append_multiple (output, buf, offset_size);
515     if (unlikely (status))
516         return status;
517
518     for (i = 0; i < num_elem; i++) {
519         element = _cairo_array_index (index, i);
520         offset += element->length;
521         encode_index_offset (buf, offset_size, offset);
522         status = _cairo_array_append_multiple (output, buf, offset_size);
523         if (unlikely (status))
524             return status;
525     }
526
527     for (i = 0; i < num_elem; i++) {
528         element = _cairo_array_index (index, i);
529         if (element->length > 0) {
530             status = _cairo_array_append_multiple (output,
531                                                    element->data,
532                                                    element->length);
533         }
534         if (unlikely (status))
535             return status;
536     }
537     return CAIRO_STATUS_SUCCESS;
538 }
539
540 static void
541 cff_index_set_object (cairo_array_t *index, int obj_index,
542                       unsigned char *object , int length)
543 {
544     cff_index_element_t *element;
545
546     element = _cairo_array_index (index, obj_index);
547     if (element == NULL)
548         return;
549
550     if (element->is_copy)
551         free (element->data);
552
553     element->data = object;
554     element->length = length;
555     element->is_copy = FALSE;
556 }
557
558 static cairo_status_t
559 cff_index_append (cairo_array_t *index, unsigned char *object , int length)
560 {
561     cff_index_element_t element;
562
563     element.length = length;
564     element.is_copy = FALSE;
565     element.data = object;
566
567     return _cairo_array_append (index, &element);
568 }
569
570 static cairo_status_t
571 cff_index_append_copy (cairo_array_t *index,
572                        const unsigned char *object,
573                        unsigned int length)
574 {
575     cff_index_element_t element;
576     cairo_status_t status;
577
578     element.length = length;
579     element.is_copy = TRUE;
580     element.data = _cairo_malloc (element.length);
581     if (unlikely (element.data == NULL))
582         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
583
584     memcpy (element.data, object, element.length);
585
586     status = _cairo_array_append (index, &element);
587     if (unlikely (status)) {
588         free (element.data);
589         return status;
590     }
591
592     return CAIRO_STATUS_SUCCESS;
593 }
594
595 static void
596 cff_index_fini (cairo_array_t *index)
597 {
598     cff_index_element_t *element;
599     unsigned int i;
600
601     for (i = 0; i < _cairo_array_num_elements (index); i++) {
602         element = _cairo_array_index (index, i);
603         if (element->is_copy && element->data)
604             free (element->data);
605     }
606     _cairo_array_fini (index);
607 }
608
609 static cairo_bool_t
610 _cairo_cff_dict_equal (const void *key_a, const void *key_b)
611 {
612     const cff_dict_operator_t *op_a = key_a;
613     const cff_dict_operator_t *op_b = key_b;
614
615     return op_a->operator == op_b->operator;
616 }
617
618 static cairo_status_t
619 cff_dict_init (cairo_hash_table_t **dict)
620 {
621     *dict = _cairo_hash_table_create (_cairo_cff_dict_equal);
622     if (unlikely (*dict == NULL))
623         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
624
625     return CAIRO_STATUS_SUCCESS;
626 }
627
628 static void
629 _cairo_dict_init_key (cff_dict_operator_t *key, int operator)
630 {
631     key->base.hash = (unsigned long) operator;
632     key->operator = operator;
633 }
634
635 static cairo_status_t
636 cff_dict_create_operator (int            operator,
637                           unsigned char *operand,
638                           int            size,
639                           cff_dict_operator_t **out)
640 {
641     cff_dict_operator_t *op;
642
643     op = _cairo_malloc (sizeof (cff_dict_operator_t));
644     if (unlikely (op == NULL))
645         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
646
647     _cairo_dict_init_key (op, operator);
648     op->operand = _cairo_malloc (size);
649     if (unlikely (op->operand == NULL)) {
650         free (op);
651         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
652     }
653
654     memcpy (op->operand, operand, size);
655     op->operand_length = size;
656     op->operand_offset = -1;
657
658     *out = op;
659     return CAIRO_STATUS_SUCCESS;
660 }
661
662 static cairo_status_t
663 cff_dict_read (cairo_hash_table_t *dict, unsigned char *p, int dict_size)
664 {
665     unsigned char *end;
666     cairo_array_t operands;
667     cff_dict_operator_t *op;
668     unsigned short operator;
669     cairo_status_t status = CAIRO_STATUS_SUCCESS;
670     int size;
671
672     end = p + dict_size;
673     _cairo_array_init (&operands, 1);
674     while (p < end) {
675         size = operand_length (p);
676         if (size != 0) {
677             status = _cairo_array_append_multiple (&operands, p, size);
678             if (unlikely (status))
679                 goto fail;
680
681             p += size;
682         } else {
683             p = decode_operator (p, &operator);
684             status = cff_dict_create_operator (operator,
685                                           _cairo_array_index (&operands, 0),
686                                           _cairo_array_num_elements (&operands),
687                                           &op);
688             if (unlikely (status))
689                 goto fail;
690
691             status = _cairo_hash_table_insert (dict, &op->base);
692             if (unlikely (status))
693                 goto fail;
694
695             _cairo_array_truncate (&operands, 0);
696         }
697     }
698
699 fail:
700     _cairo_array_fini (&operands);
701
702     return status;
703 }
704
705 static void
706 cff_dict_remove (cairo_hash_table_t *dict, unsigned short operator)
707 {
708     cff_dict_operator_t key, *op;
709
710     _cairo_dict_init_key (&key, operator);
711     op = _cairo_hash_table_lookup (dict, &key.base);
712     if (op != NULL) {
713         free (op->operand);
714         _cairo_hash_table_remove (dict, (cairo_hash_entry_t *) op);
715         free (op);
716     }
717 }
718
719 static unsigned char *
720 cff_dict_get_operands (cairo_hash_table_t *dict,
721                        unsigned short      operator,
722                        int                *size)
723 {
724     cff_dict_operator_t key, *op;
725
726     _cairo_dict_init_key (&key, operator);
727     op = _cairo_hash_table_lookup (dict, &key.base);
728     if (op != NULL) {
729         *size = op->operand_length;
730         return op->operand;
731     }
732
733     return NULL;
734 }
735
736 static cairo_status_t
737 cff_dict_set_operands (cairo_hash_table_t *dict,
738                        unsigned short      operator,
739                        unsigned char      *operand,
740                        int                 size)
741 {
742     cff_dict_operator_t key, *op;
743     cairo_status_t status;
744
745     _cairo_dict_init_key (&key, operator);
746     op = _cairo_hash_table_lookup (dict, &key.base);
747     if (op != NULL) {
748         free (op->operand);
749         op->operand = _cairo_malloc (size);
750         if (unlikely (op->operand == NULL))
751             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
752
753         memcpy (op->operand, operand, size);
754         op->operand_length = size;
755     }
756     else
757     {
758         status = cff_dict_create_operator (operator, operand, size, &op);
759         if (unlikely (status))
760             return status;
761
762         status = _cairo_hash_table_insert (dict, &op->base);
763         if (unlikely (status))
764             return status;
765     }
766
767     return CAIRO_STATUS_SUCCESS;
768 }
769
770 static int
771 cff_dict_get_location (cairo_hash_table_t *dict,
772                        unsigned short      operator,
773                        int                *size)
774 {
775     cff_dict_operator_t key, *op;
776
777     _cairo_dict_init_key (&key, operator);
778     op = _cairo_hash_table_lookup (dict, &key.base);
779     if (op != NULL) {
780         *size = op->operand_length;
781         return op->operand_offset;
782     }
783
784     return -1;
785 }
786
787 typedef struct _dict_write_info {
788     cairo_array_t *output;
789     cairo_status_t status;
790 } dict_write_info_t;
791
792 static void
793 cairo_dict_write_operator (cff_dict_operator_t *op, dict_write_info_t *write_info)
794 {
795     unsigned char data;
796
797     op->operand_offset = _cairo_array_num_elements (write_info->output);
798     write_info->status = _cairo_array_append_multiple (write_info->output, op->operand, op->operand_length);
799     if (write_info->status)
800         return;
801
802     if (op->operator & 0xff00) {
803         data = op->operator >> 8;
804         write_info->status = _cairo_array_append (write_info->output, &data);
805         if (write_info->status)
806             return;
807     }
808     data = op->operator & 0xff;
809     write_info->status = _cairo_array_append (write_info->output, &data);
810 }
811
812 static void
813 _cairo_dict_collect (void *entry, void *closure)
814 {
815     dict_write_info_t   *write_info = closure;
816     cff_dict_operator_t *op = entry;
817
818     if (write_info->status)
819         return;
820
821     /* The ROS operator is handled separately in cff_dict_write() */
822     if (op->operator != ROS_OP)
823         cairo_dict_write_operator (op, write_info);
824 }
825
826 static cairo_status_t
827 cff_dict_write (cairo_hash_table_t *dict, cairo_array_t *output)
828 {
829     dict_write_info_t write_info;
830     cff_dict_operator_t key, *op;
831
832     write_info.output = output;
833     write_info.status = CAIRO_STATUS_SUCCESS;
834
835     /* The CFF specification requires that the Top Dict of CID fonts
836      * begin with the ROS operator. */
837     _cairo_dict_init_key (&key, ROS_OP);
838     op = _cairo_hash_table_lookup (dict, &key.base);
839     if (op != NULL)
840         cairo_dict_write_operator (op, &write_info);
841
842     _cairo_hash_table_foreach (dict, _cairo_dict_collect, &write_info);
843
844     return write_info.status;
845 }
846
847 static void
848 _cff_dict_entry_pluck (void *_entry, void *dict)
849 {
850     cff_dict_operator_t *entry = _entry;
851
852     _cairo_hash_table_remove (dict, &entry->base);
853     free (entry->operand);
854     free (entry);
855 }
856
857 static void
858 cff_dict_fini (cairo_hash_table_t *dict)
859 {
860     _cairo_hash_table_foreach (dict, _cff_dict_entry_pluck, dict);
861     _cairo_hash_table_destroy (dict);
862 }
863
864 static cairo_int_status_t
865 cairo_cff_font_read_header (cairo_cff_font_t *font)
866 {
867     if (font->data_length < sizeof (cff_header_t))
868         return CAIRO_INT_STATUS_UNSUPPORTED;
869
870
871     font->header = (cff_header_t *) font->data;
872     font->current_ptr = font->data + font->header->header_size;
873
874     return CAIRO_STATUS_SUCCESS;
875 }
876
877 static cairo_int_status_t
878 cairo_cff_font_read_name (cairo_cff_font_t *font)
879 {
880     cairo_array_t index;
881     cairo_int_status_t status;
882     cff_index_element_t *element;
883     unsigned char *p;
884     int i, len;
885
886     cff_index_init (&index);
887     status = cff_index_read (&index, &font->current_ptr, font->data_end);
888     if (!font->is_opentype) {
889         element = _cairo_array_index (&index, 0);
890         if (element == NULL)
891             return _cairo_error (CAIRO_STATUS_NULL_POINTER);
892
893     p = element->data;
894         len = element->length;
895
896         /* If font name is prefixed with a subset tag, strip it off. */
897         if (len > 7 && p[6] == '+') {
898             for (i = 0; i < 6; i++)
899                 if (p[i] < 'A' || p[i] > 'Z')
900                     break;
901             if (i == 6) {
902                 p += 7;
903                 len -= 7;
904             }
905         }
906         font->ps_name = _cairo_malloc (len + 1);
907         if (unlikely (font->ps_name == NULL))
908             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
909
910         memcpy (font->ps_name, p, len);
911         font->ps_name[len] = 0;
912
913         status = _cairo_escape_ps_name (&font->ps_name);
914     }
915     cff_index_fini (&index);
916
917     return status;
918 }
919
920 static cairo_int_status_t
921 cairo_cff_font_read_private_dict (cairo_cff_font_t   *font,
922                                   cairo_hash_table_t *private_dict,
923                                   cairo_array_t      *local_sub_index,
924                                   int                *local_sub_bias,
925                                   cairo_bool_t      **local_subs_used,
926                                   double             *default_width,
927                                   double             *nominal_width,
928                                   unsigned char      *ptr,
929                                   int                 size)
930 {
931     cairo_int_status_t status;
932     unsigned char buf[10];
933     unsigned char *end_buf;
934     int offset;
935     int i;
936     unsigned char *operand;
937     unsigned char *p;
938     int num_subs;
939
940     status = cff_dict_read (private_dict, ptr, size);
941     if (unlikely (status))
942         return status;
943
944     operand = cff_dict_get_operands (private_dict, LOCAL_SUB_OP, &i);
945     if (operand) {
946         decode_integer (operand, &offset);
947         p = ptr + offset;
948         status = cff_index_read (local_sub_index, &p, font->data_end);
949         if (unlikely (status))
950             return status;
951
952         /* Use maximum sized encoding to reserve space for later modification. */
953         end_buf = encode_integer_max (buf, 0);
954         status = cff_dict_set_operands (private_dict, LOCAL_SUB_OP, buf, end_buf - buf);
955         if (unlikely (status))
956             return status;
957     }
958
959     *default_width = 0;
960     operand = cff_dict_get_operands (private_dict, DEFAULTWIDTH_OP, &i);
961     if (operand)
962         decode_number (operand, default_width);
963
964     *nominal_width = 0;
965     operand = cff_dict_get_operands (private_dict, NOMINALWIDTH_OP, &i);
966     if (operand)
967          decode_number (operand, nominal_width);
968
969     num_subs = _cairo_array_num_elements (local_sub_index);
970     *local_subs_used = calloc (num_subs, sizeof (cairo_bool_t));
971     if (unlikely (*local_subs_used == NULL))
972         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
973
974     if (num_subs < 1240)
975         *local_sub_bias = 107;
976     else if (num_subs < 33900)
977         *local_sub_bias = 1131;
978     else
979         *local_sub_bias = 32768;
980
981     return CAIRO_STATUS_SUCCESS;
982 }
983
984 static cairo_int_status_t
985 cairo_cff_font_read_fdselect (cairo_cff_font_t *font, unsigned char *p)
986 {
987     int type, num_ranges, first, last, fd, i, j;
988
989     font->fdselect = calloc (font->num_glyphs, sizeof (int));
990     if (unlikely (font->fdselect == NULL))
991         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
992
993     type = *p++;
994     if (type == 0)
995     {
996         for (i = 0; i < font->num_glyphs; i++)
997             font->fdselect[i] = *p++;
998     } else if (type == 3) {
999         num_ranges = get_unaligned_be16 (p);
1000         p += 2;
1001         for  (i = 0; i < num_ranges; i++)
1002         {
1003             first = get_unaligned_be16 (p);
1004             p += 2;
1005             fd = *p++;
1006             last = get_unaligned_be16 (p);
1007             for (j = first; j < last; j++)
1008                 font->fdselect[j] = fd;
1009         }
1010     } else {
1011         return CAIRO_INT_STATUS_UNSUPPORTED;
1012     }
1013
1014     return CAIRO_STATUS_SUCCESS;
1015 }
1016
1017 static cairo_int_status_t
1018 cairo_cff_font_read_cid_fontdict (cairo_cff_font_t *font, unsigned char *ptr)
1019 {
1020     cairo_array_t index;
1021     cff_index_element_t *element;
1022     unsigned int i;
1023     int size;
1024     unsigned char *operand;
1025     int offset;
1026     cairo_int_status_t status;
1027     unsigned char buf[100];
1028     unsigned char *end_buf;
1029
1030     cff_index_init (&index);
1031     status = cff_index_read (&index, &ptr, font->data_end);
1032     if (unlikely (status))
1033         goto fail;
1034
1035     font->num_fontdicts = _cairo_array_num_elements (&index);
1036
1037     font->fd_dict = calloc (sizeof (cairo_hash_table_t *), font->num_fontdicts);
1038     if (unlikely (font->fd_dict == NULL)) {
1039         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1040         goto fail;
1041     }
1042
1043     font->fd_private_dict = calloc (sizeof (cairo_hash_table_t *), font->num_fontdicts);
1044     if (unlikely (font->fd_private_dict == NULL)) {
1045         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1046         goto fail;
1047     }
1048
1049     font->fd_local_sub_index = calloc (sizeof (cairo_array_t), font->num_fontdicts);
1050     if (unlikely (font->fd_local_sub_index == NULL)) {
1051         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1052         goto fail;
1053     }
1054
1055     font->fd_local_sub_bias = calloc (sizeof (int), font->num_fontdicts);
1056     if (unlikely (font->fd_local_sub_bias == NULL)) {
1057         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1058         goto fail;
1059     }
1060
1061     font->fd_local_subs_used = calloc (sizeof (cairo_bool_t *), font->num_fontdicts);
1062     if (unlikely (font->fd_local_subs_used == NULL)) {
1063         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1064         goto fail;
1065     }
1066
1067     font->fd_default_width = calloc (font->num_fontdicts, sizeof (double));
1068     if (unlikely (font->fd_default_width == NULL)) {
1069         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1070         goto fail;
1071     }
1072
1073     font->fd_nominal_width = calloc (font->num_fontdicts, sizeof (double));
1074     if (unlikely (font->fd_nominal_width == NULL)) {
1075         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1076         goto fail;
1077     }
1078
1079     for (i = 0; i < font->num_fontdicts; i++) {
1080         status = cff_dict_init (&font->fd_dict[i]);
1081         if (unlikely (status))
1082             goto fail;
1083
1084         element = _cairo_array_index (&index, i);
1085         status = cff_dict_read (font->fd_dict[i], element->data, element->length);
1086         if (unlikely (status))
1087             goto fail;
1088
1089         operand = cff_dict_get_operands (font->fd_dict[i], PRIVATE_OP, &size);
1090         if (operand == NULL) {
1091             status = CAIRO_INT_STATUS_UNSUPPORTED;
1092             goto fail;
1093         }
1094         operand = decode_integer (operand, &size);
1095         decode_integer (operand, &offset);
1096         status = cff_dict_init (&font->fd_private_dict[i]);
1097         if (unlikely (status))
1098             goto fail;
1099
1100         cff_index_init (&font->fd_local_sub_index[i]);
1101         status = cairo_cff_font_read_private_dict (font,
1102                                                    font->fd_private_dict[i],
1103                                                    &font->fd_local_sub_index[i],
1104                                                    &font->fd_local_sub_bias[i],
1105                                                    &font->fd_local_subs_used[i],
1106                                                    &font->fd_default_width[i],
1107                                                    &font->fd_nominal_width[i],
1108                                                    font->data + offset,
1109                                                    size);
1110         if (unlikely (status))
1111             goto fail;
1112
1113         /* Set integer operand to max value to use max size encoding to reserve
1114          * space for any value later */
1115         end_buf = encode_integer_max (buf, 0);
1116         end_buf = encode_integer_max (end_buf, 0);
1117         status = cff_dict_set_operands (font->fd_dict[i], PRIVATE_OP, buf, end_buf - buf);
1118         if (unlikely (status))
1119             goto fail;
1120     }
1121
1122     return CAIRO_STATUS_SUCCESS;
1123
1124 fail:
1125     cff_index_fini (&index);
1126
1127     return status;
1128 }
1129
1130 static void
1131 cairo_cff_font_read_font_metrics (cairo_cff_font_t *font, cairo_hash_table_t  *top_dict)
1132 {
1133     unsigned char *p;
1134     unsigned char *end;
1135     int size;
1136     double x_min, y_min, x_max, y_max;
1137     double xx, yx, xy, yy;
1138
1139     x_min = 0.0;
1140     y_min = 0.0;
1141     x_max = 0.0;
1142     y_max = 0.0;
1143     p = cff_dict_get_operands (font->top_dict, FONTBBOX_OP, &size);
1144     if (p) {
1145         end = p + size;
1146         if (p < end)
1147             p = decode_number (p, &x_min);
1148         if (p < end)
1149             p = decode_number (p, &y_min);
1150         if (p < end)
1151             p = decode_number (p, &x_max);
1152         if (p < end)
1153             p = decode_number (p, &y_max);
1154     }
1155     font->x_min = floor (x_min);
1156     font->y_min = floor (y_min);
1157     font->x_max = floor (x_max);
1158     font->y_max = floor (y_max);
1159     font->ascent = font->y_max;
1160     font->descent = font->y_min;
1161
1162     xx = 0.001;
1163     yx = 0.0;
1164     xy = 0.0;
1165     yy = 0.001;
1166     p = cff_dict_get_operands (font->top_dict, FONTMATRIX_OP, &size);
1167     if (p) {
1168         end = p + size;
1169         if (p < end)
1170             p = decode_number (p, &xx);
1171         if (p < end)
1172             p = decode_number (p, &yx);
1173         if (p < end)
1174             p = decode_number (p, &xy);
1175         if (p < end)
1176             p = decode_number (p, &yy);
1177     }
1178     /* Freetype uses 1/yy to get units per EM */
1179     font->units_per_em = _cairo_round(1.0/yy);
1180 }
1181
1182 static cairo_int_status_t
1183 cairo_cff_font_read_top_dict (cairo_cff_font_t *font)
1184 {
1185     cairo_array_t index;
1186     cff_index_element_t *element;
1187     unsigned char buf[20];
1188     unsigned char *end_buf;
1189     unsigned char *operand;
1190     cairo_int_status_t status;
1191     unsigned char *p;
1192     int size;
1193     int offset;
1194
1195     cff_index_init (&index);
1196     status = cff_index_read (&index, &font->current_ptr, font->data_end);
1197     if (unlikely (status))
1198         goto fail;
1199
1200     element = _cairo_array_index (&index, 0);
1201     if (element == NULL) {
1202         status = CAIRO_STATUS_NULL_POINTER;
1203         goto fail;
1204     }
1205
1206     status = cff_dict_read (font->top_dict, element->data, element->length);
1207     if (unlikely (status))
1208         goto fail;
1209
1210     if (cff_dict_get_operands (font->top_dict, ROS_OP, &size) != NULL)
1211         font->is_cid = TRUE;
1212     else
1213         font->is_cid = FALSE;
1214
1215     operand = cff_dict_get_operands (font->top_dict, CHARSTRINGS_OP, &size);
1216     if (operand == NULL) {
1217         status = CAIRO_STATUS_NULL_POINTER;
1218         goto fail;
1219     }
1220
1221     decode_integer (operand, &offset);
1222     p = font->data + offset;
1223     status = cff_index_read (&font->charstrings_index, &p, font->data_end);
1224     if (unlikely (status))
1225         goto fail;
1226     font->num_glyphs = _cairo_array_num_elements (&font->charstrings_index);
1227
1228     if (font->is_cid) {
1229          operand = cff_dict_get_operands (font->top_dict, CHARSET_OP, &size);
1230          if (!operand)
1231               return CAIRO_INT_STATUS_UNSUPPORTED;
1232
1233          decode_integer (operand, &offset);
1234          font->charset = font->data + offset;
1235          if (font->charset >= font->data_end)
1236               return CAIRO_INT_STATUS_UNSUPPORTED;
1237     }
1238
1239     if (!font->is_opentype)
1240         cairo_cff_font_read_font_metrics (font, font->top_dict);
1241
1242     if (font->is_cid) {
1243         operand = cff_dict_get_operands (font->top_dict, FDSELECT_OP, &size);
1244         if (operand == NULL) {
1245             status = CAIRO_STATUS_NULL_POINTER;
1246             goto fail;
1247         }
1248         decode_integer (operand, &offset);
1249         status = cairo_cff_font_read_fdselect (font, font->data + offset);
1250         if (unlikely (status))
1251             goto fail;
1252
1253         operand = cff_dict_get_operands (font->top_dict, FDARRAY_OP, &size);
1254         if (operand == NULL) {
1255             status = _cairo_error (CAIRO_STATUS_NULL_POINTER);
1256             goto fail;
1257         }
1258
1259         decode_integer (operand, &offset);
1260         status = cairo_cff_font_read_cid_fontdict (font, font->data + offset);
1261         if (unlikely (status))
1262             goto fail;
1263     } else {
1264         operand = cff_dict_get_operands (font->top_dict, PRIVATE_OP, &size);
1265         operand = decode_integer (operand, &size);
1266         decode_integer (operand, &offset);
1267         status = cairo_cff_font_read_private_dict (font,
1268                                                    font->private_dict,
1269                                                    &font->local_sub_index,
1270                                                    &font->local_sub_bias,
1271                                                    &font->local_subs_used,
1272                                                    &font->default_width,
1273                                                    &font->nominal_width,
1274                                                    font->data + offset,
1275                                                    size);
1276         if (unlikely (status))
1277             goto fail;
1278     }
1279
1280     /* Use maximum sized encoding to reserve space for later modification. */
1281     end_buf = encode_integer_max (buf, 0);
1282     status = cff_dict_set_operands (font->top_dict,
1283                                     CHARSTRINGS_OP, buf, end_buf - buf);
1284     if (unlikely (status))
1285         goto fail;
1286
1287     status = cff_dict_set_operands (font->top_dict,
1288                                     CHARSET_OP, buf, end_buf - buf);
1289     if (unlikely (status))
1290         goto fail;
1291
1292     if (font->scaled_font_subset->is_latin) {
1293         status = cff_dict_set_operands (font->top_dict,
1294                                         ENCODING_OP, buf, end_buf - buf);
1295         if (unlikely (status))
1296             goto fail;
1297
1298         /* Private has two operands - size and offset */
1299         end_buf = encode_integer_max (end_buf, 0);
1300         cff_dict_set_operands (font->top_dict, PRIVATE_OP, buf, end_buf - buf);
1301
1302     } else {
1303         status = cff_dict_set_operands (font->top_dict,
1304                                         FDSELECT_OP, buf, end_buf - buf);
1305         if (unlikely (status))
1306             goto fail;
1307
1308         status = cff_dict_set_operands (font->top_dict,
1309                                         FDARRAY_OP, buf, end_buf - buf);
1310         if (unlikely (status))
1311             goto fail;
1312
1313         cff_dict_remove (font->top_dict, ENCODING_OP);
1314         cff_dict_remove (font->top_dict, PRIVATE_OP);
1315     }
1316
1317     /* Remove the unique identifier operators as the subsetted font is
1318      * not the same is the original font. */
1319     cff_dict_remove (font->top_dict, UNIQUEID_OP);
1320     cff_dict_remove (font->top_dict, XUID_OP);
1321
1322 fail:
1323     cff_index_fini (&index);
1324
1325     return status;
1326 }
1327
1328 static cairo_int_status_t
1329 cairo_cff_font_read_strings (cairo_cff_font_t *font)
1330 {
1331     return cff_index_read (&font->strings_index, &font->current_ptr, font->data_end);
1332 }
1333
1334 static cairo_int_status_t
1335 cairo_cff_font_read_global_subroutines (cairo_cff_font_t *font)
1336 {
1337     cairo_int_status_t status;
1338     int num_subs;
1339
1340     status = cff_index_read (&font->global_sub_index, &font->current_ptr, font->data_end);
1341     if (unlikely (status))
1342         return status;
1343
1344     num_subs = _cairo_array_num_elements (&font->global_sub_index);
1345     font->global_subs_used = calloc (num_subs, sizeof(cairo_bool_t));
1346     if (unlikely (font->global_subs_used == NULL))
1347         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1348
1349     if (num_subs < 1240)
1350         font->global_sub_bias = 107;
1351     else if (num_subs < 33900)
1352         font->global_sub_bias = 1131;
1353     else
1354         font->global_sub_bias = 32768;
1355
1356     return CAIRO_STATUS_SUCCESS;
1357 }
1358
1359 typedef cairo_int_status_t
1360 (*font_read_t) (cairo_cff_font_t *font);
1361
1362 static const font_read_t font_read_funcs[] = {
1363     cairo_cff_font_read_header,
1364     cairo_cff_font_read_name,
1365     cairo_cff_font_read_top_dict,
1366     cairo_cff_font_read_strings,
1367     cairo_cff_font_read_global_subroutines,
1368 };
1369
1370 static cairo_int_status_t
1371 cairo_cff_font_read_font (cairo_cff_font_t *font)
1372 {
1373     cairo_int_status_t status;
1374     unsigned int i;
1375
1376     for (i = 0; i < ARRAY_LENGTH (font_read_funcs); i++) {
1377         status = font_read_funcs[i] (font);
1378         if (unlikely (status))
1379             return status;
1380     }
1381
1382     return CAIRO_STATUS_SUCCESS;
1383 }
1384
1385 static cairo_status_t
1386 cairo_cff_font_set_ros_strings (cairo_cff_font_t *font)
1387 {
1388     cairo_status_t status;
1389     unsigned char buf[30];
1390     unsigned char *p;
1391     int sid1, sid2;
1392     const char *registry = "Adobe";
1393     const char *ordering = "Identity";
1394
1395     sid1 = NUM_STD_STRINGS + _cairo_array_num_elements (&font->strings_subset_index);
1396     status = cff_index_append_copy (&font->strings_subset_index,
1397                                     (unsigned char *)registry,
1398                                     strlen(registry));
1399     if (unlikely (status))
1400         return status;
1401
1402     sid2 = NUM_STD_STRINGS + _cairo_array_num_elements (&font->strings_subset_index);
1403     status = cff_index_append_copy (&font->strings_subset_index,
1404                                     (unsigned char *)ordering,
1405                                     strlen(ordering));
1406     if (unlikely (status))
1407         return status;
1408
1409     p = encode_integer (buf, sid1);
1410     p = encode_integer (p, sid2);
1411     p = encode_integer (p, 0);
1412     status = cff_dict_set_operands (font->top_dict, ROS_OP, buf, p - buf);
1413     if (unlikely (status))
1414         return status;
1415
1416     p = encode_integer (buf, font->scaled_font_subset->num_glyphs);
1417     status = cff_dict_set_operands (font->top_dict, CIDCOUNT_OP, buf, p - buf);
1418     if (unlikely (status))
1419         return status;
1420
1421     return CAIRO_STATUS_SUCCESS;
1422 }
1423
1424 static cairo_status_t
1425 cairo_cff_font_subset_dict_string(cairo_cff_font_t   *font,
1426                                   cairo_hash_table_t *dict,
1427                                   int                 operator)
1428 {
1429     int size;
1430     unsigned char *p;
1431     int sid;
1432     unsigned char buf[100];
1433     cff_index_element_t *element;
1434     cairo_status_t status;
1435
1436     p = cff_dict_get_operands (dict, operator, &size);
1437     if (!p)
1438         return CAIRO_STATUS_SUCCESS;
1439
1440     decode_integer (p, &sid);
1441     if (sid < NUM_STD_STRINGS)
1442         return CAIRO_STATUS_SUCCESS;
1443
1444     element = _cairo_array_index (&font->strings_index, sid - NUM_STD_STRINGS);
1445     if(element == NULL)
1446         return _cairo_error (CAIRO_STATUS_INVALID_INDEX);
1447
1448     sid = NUM_STD_STRINGS + _cairo_array_num_elements (&font->strings_subset_index);
1449     status = cff_index_append (&font->strings_subset_index, element->data, element->length);
1450     if (unlikely (status))
1451         return status;
1452
1453     p = encode_integer (buf, sid);
1454     status = cff_dict_set_operands (dict, operator, buf, p - buf);
1455     if (unlikely (status))
1456         return status;
1457
1458     return CAIRO_STATUS_SUCCESS;
1459 }
1460
1461 static const int dict_strings[] = {
1462     VERSION_OP,
1463     NOTICE_OP,
1464     COPYRIGHT_OP,
1465     FULLNAME_OP,
1466     FAMILYNAME_OP,
1467     WEIGHT_OP,
1468     POSTSCRIPT_OP,
1469     BASEFONTNAME_OP,
1470     FONTNAME_OP,
1471 };
1472
1473 static cairo_status_t
1474 cairo_cff_font_subset_dict_strings (cairo_cff_font_t   *font,
1475                                     cairo_hash_table_t *dict)
1476 {
1477     cairo_status_t status;
1478     unsigned int i;
1479
1480     for (i = 0; i < ARRAY_LENGTH (dict_strings); i++) {
1481         status = cairo_cff_font_subset_dict_string (font, dict, dict_strings[i]);
1482         if (unlikely (status))
1483             return status;
1484     }
1485
1486     return CAIRO_STATUS_SUCCESS;
1487 }
1488
1489 static unsigned char *
1490 type2_decode_integer (unsigned char *p, int *integer)
1491 {
1492     if (*p == 28) {
1493         *integer = p[1] << 8 | p[2];
1494         p += 3;
1495     } else if (*p <= 246) {
1496         *integer = *p++ - 139;
1497     } else if (*p <= 250) {
1498         *integer = (p[0] - 247) * 256 + p[1] + 108;
1499         p += 2;
1500     } else if (*p <= 254) {
1501         *integer = -(p[0] - 251) * 256 - p[1] - 108;
1502         p += 2;
1503     } else { /* *p == 255 */
1504          /* 16.16 fixed-point number. The fraction is ignored. */
1505          *integer = (int16_t)((p[1] << 8) | p[2]);
1506         p += 5;
1507     }
1508     return p;
1509 }
1510
1511 /* Type 2 charstring parser for finding calls to local or global
1512  * subroutines. For non Opentype CFF fonts it also gets the glyph
1513  * widths.
1514  *
1515  * When we find a subroutine operator, the subroutine is marked as in
1516  * use and recursively followed. The subroutine number is the value on
1517  * the top of the stack when the subroutine operator is executed. In
1518  * most fonts the subroutine number is encoded in an integer
1519  * immediately preceding the subroutine operator. However it is
1520  * possible for the subroutine number on the stack to be the result of
1521  * a computation (in which case there will be an operator preceding
1522  * the subroutine operator). If this occurs, subroutine subsetting is
1523  * disabled since we can't easily determine which subroutines are
1524  * used.
1525  *
1526  * The width, if present, is the first integer in the charstring. The
1527  * only way to confirm if the integer at the start of the charstring is
1528  * the width is when the first stack clearing operator is parsed,
1529  * check if there is an extra integer left over on the stack.
1530  *
1531  * When the first stack clearing operator is encountered
1532  * type2_find_width is set to FALSE and type2_found_width is set to
1533  * TRUE if an extra argument is found, otherwise FALSE.
1534  */
1535 static cairo_status_t
1536 cairo_cff_parse_charstring (cairo_cff_font_t *font,
1537                             unsigned char *charstring, int length,
1538                             int glyph_id,
1539                             cairo_bool_t need_width)
1540 {
1541     unsigned char *p = charstring;
1542     unsigned char *end = charstring + length;
1543     int integer;
1544     int hint_bytes;
1545     int sub_num;
1546     cff_index_element_t *element;
1547     int fd;
1548
1549     while (p < end) {
1550         if (*p == 28 || *p >= 32) {
1551             /* Integer value */
1552             p = type2_decode_integer (p, &integer);
1553             font->type2_stack_size++;
1554             font->type2_stack_top_value = integer;
1555             font->type2_stack_top_is_int = TRUE;
1556             if (!font->type2_seen_first_int) {
1557                 font->type2_width = integer;
1558                 font->type2_seen_first_int = TRUE;
1559             }
1560         } else if (*p == TYPE2_hstem || *p == TYPE2_vstem ||
1561                    *p == TYPE2_hstemhm || *p == TYPE2_vstemhm) {
1562             /* Hint operator. The number of hints declared by the
1563              * operator depends on the size of the stack. */
1564             font->type2_stack_top_is_int = FALSE;
1565             font->type2_num_hints += font->type2_stack_size/2;
1566             if (font->type2_find_width && font->type2_stack_size % 2)
1567                 font->type2_found_width = TRUE;
1568
1569             font->type2_stack_size = 0;
1570             font->type2_find_width = FALSE;
1571             p++;
1572         } else if (*p == TYPE2_hintmask || *p == TYPE2_cntrmask) {
1573             /* Hintmask operator. These operators are followed by a
1574              * variable length mask where the length depends on the
1575              * number of hints declared. The first time this is called
1576              * it is also an implicit vstem if there are arguments on
1577              * the stack. */
1578             if (font->type2_hintmask_bytes == 0) {
1579                 font->type2_stack_top_is_int = FALSE;
1580                 font->type2_num_hints += font->type2_stack_size/2;
1581                 if (font->type2_find_width && font->type2_stack_size % 2)
1582                     font->type2_found_width = TRUE;
1583
1584                 font->type2_stack_size = 0;
1585                 font->type2_find_width = FALSE;
1586                 font->type2_hintmask_bytes = (font->type2_num_hints+7)/8;
1587             }
1588
1589             hint_bytes = font->type2_hintmask_bytes;
1590             p++;
1591             p += hint_bytes;
1592         } else if (*p == TYPE2_rmoveto) {
1593             if (font->type2_find_width && font->type2_stack_size > 2)
1594                 font->type2_found_width = TRUE;
1595
1596             font->type2_stack_size = 0;
1597             font->type2_find_width = FALSE;
1598             font->type2_has_path = TRUE;
1599             p++;
1600         } else if (*p == TYPE2_hmoveto || *p == TYPE2_vmoveto) {
1601             if (font->type2_find_width && font->type2_stack_size > 1)
1602                 font->type2_found_width = TRUE;
1603
1604             font->type2_stack_size = 0;
1605             font->type2_find_width = FALSE;
1606             font->type2_has_path = TRUE;
1607             p++;
1608         } else if (*p == TYPE2_endchar) {
1609             if (!font->type2_has_path && font->type2_stack_size > 3)
1610                 return CAIRO_INT_STATUS_UNSUPPORTED; /* seac (Ref Appendix C of Type 2 Charstring Format */
1611
1612             if (font->type2_find_width && font->type2_stack_size > 0)
1613                 font->type2_found_width = TRUE;
1614
1615             return CAIRO_STATUS_SUCCESS;
1616         } else if (*p == TYPE2_callsubr) {
1617             /* call to local subroutine */
1618             if (! font->type2_stack_top_is_int)
1619                 return CAIRO_INT_STATUS_UNSUPPORTED;
1620
1621             if (++font->type2_nesting_level > MAX_SUBROUTINE_NESTING)
1622                 return CAIRO_INT_STATUS_UNSUPPORTED;
1623
1624             p++;
1625             font->type2_stack_top_is_int = FALSE;
1626             font->type2_stack_size--;
1627             if (font->type2_find_width && font->type2_stack_size == 0)
1628                 font->type2_seen_first_int = FALSE;
1629
1630             if (font->is_cid) {
1631                 fd = font->fdselect[glyph_id];
1632                 sub_num = font->type2_stack_top_value + font->fd_local_sub_bias[fd];
1633                 element = _cairo_array_index (&font->fd_local_sub_index[fd], sub_num);
1634                 if (element == NULL)
1635                     return _cairo_error (CAIRO_STATUS_NULL_POINTER);
1636
1637                 if (! font->fd_local_subs_used[fd][sub_num]) {
1638                     font->fd_local_subs_used[fd][sub_num] = TRUE;
1639                     cairo_cff_parse_charstring (font, element->data, element->length, glyph_id, need_width);
1640                 }
1641             } else {
1642                 sub_num = font->type2_stack_top_value + font->local_sub_bias;
1643                 element = _cairo_array_index (&font->local_sub_index, sub_num);
1644                 if (element == NULL)
1645                     return _cairo_error (CAIRO_STATUS_NULL_POINTER);
1646
1647                 if (! font->local_subs_used[sub_num] ||
1648                     (need_width && !font->type2_found_width))
1649                 {
1650                     font->local_subs_used[sub_num] = TRUE;
1651                     cairo_cff_parse_charstring (font, element->data, element->length, glyph_id, need_width);
1652                 }
1653             }
1654             font->type2_nesting_level--;
1655         } else if (*p == TYPE2_callgsubr) {
1656             /* call to global subroutine */
1657             if (! font->type2_stack_top_is_int)
1658                 return CAIRO_INT_STATUS_UNSUPPORTED;
1659
1660             if (++font->type2_nesting_level > MAX_SUBROUTINE_NESTING)
1661                 return CAIRO_INT_STATUS_UNSUPPORTED;
1662
1663             p++;
1664             font->type2_stack_size--;
1665             font->type2_stack_top_is_int = FALSE;
1666             if (font->type2_find_width && font->type2_stack_size == 0)
1667                 font->type2_seen_first_int = FALSE;
1668
1669             sub_num = font->type2_stack_top_value + font->global_sub_bias;
1670             element = _cairo_array_index (&font->global_sub_index, sub_num);
1671             if (element == NULL)
1672                 return _cairo_error (CAIRO_STATUS_NULL_POINTER);
1673
1674             if (! font->global_subs_used[sub_num] ||
1675                 (need_width && !font->type2_found_width))
1676             {
1677                 font->global_subs_used[sub_num] = TRUE;
1678                 cairo_cff_parse_charstring (font, element->data, element->length, glyph_id, need_width);
1679             }
1680             font->type2_nesting_level--;
1681         } else if (*p == 12) {
1682             /* 2 byte instruction */
1683
1684             /* All the 2 byte operators are either not valid before a
1685              * stack clearing operator or they are one of the
1686              * arithmetic, storage, or conditional operators. */
1687             if (need_width && font->type2_find_width)
1688                 return CAIRO_INT_STATUS_UNSUPPORTED;
1689
1690             p += 2;
1691             font->type2_stack_top_is_int = FALSE;
1692         } else {
1693             /* 1 byte instruction */
1694             p++;
1695             font->type2_stack_top_is_int = FALSE;
1696         }
1697     }
1698
1699     return CAIRO_STATUS_SUCCESS;
1700 }
1701
1702 static cairo_status_t
1703 cairo_cff_find_width_and_subroutines_used (cairo_cff_font_t  *font,
1704                                            unsigned char *charstring, int length,
1705                                            int glyph_id, int subset_id)
1706 {
1707     cairo_status_t status;
1708     int width;
1709     int fd;
1710
1711     font->type2_stack_size = 0;
1712     font->type2_stack_top_value = 0;;
1713     font->type2_stack_top_is_int = FALSE;
1714     font->type2_num_hints = 0;
1715     font->type2_hintmask_bytes = 0;
1716     font->type2_nesting_level = 0;
1717     font->type2_seen_first_int = FALSE;
1718     font->type2_find_width = TRUE;
1719     font->type2_found_width = FALSE;
1720     font->type2_width = 0;
1721     font->type2_has_path = FALSE;
1722
1723     status = cairo_cff_parse_charstring (font, charstring, length, glyph_id, TRUE);
1724     if (status)
1725         return status;
1726
1727     if (!font->is_opentype) {
1728         if (font->is_cid) {
1729             fd = font->fdselect[glyph_id];
1730             if (font->type2_found_width)
1731                 width = font->fd_nominal_width[fd] + font->type2_width;
1732             else
1733                 width = font->fd_default_width[fd];
1734         } else {
1735             if (font->type2_found_width)
1736                 width = font->nominal_width + font->type2_width;
1737             else
1738                 width = font->default_width;
1739         }
1740         font->widths[subset_id] = width;
1741     }
1742
1743     return CAIRO_STATUS_SUCCESS;
1744 }
1745
1746 static cairo_int_status_t
1747 cairo_cff_font_get_gid_for_cid (cairo_cff_font_t  *font, unsigned long cid, unsigned long *gid)
1748 {
1749     unsigned char *p;
1750     unsigned long first_gid;
1751     unsigned long first_cid;
1752     int num_left;
1753     unsigned long c, g;
1754
1755     if (cid == 0) {
1756         *gid = 0;
1757         return CAIRO_STATUS_SUCCESS;
1758     }
1759
1760     switch (font->charset[0]) {
1761         /* Format 0 */
1762         case 0:
1763             p = font->charset + 1;
1764             g = 1;
1765             while (g <= (unsigned)font->num_glyphs && p < font->data_end) {
1766                 c = get_unaligned_be16 (p);
1767                 if (c == cid) {
1768                     *gid = g;
1769                     return CAIRO_STATUS_SUCCESS;
1770                 }
1771                 g++;
1772                 p += 2;
1773             }
1774             break;
1775
1776         /* Format 1 */
1777         case 1:
1778             first_gid = 1;
1779             p = font->charset + 1;
1780             while (first_gid <= (unsigned)font->num_glyphs && p + 2 < font->data_end) {
1781                 first_cid = get_unaligned_be16 (p);
1782                 num_left = p[2];
1783                 if (cid >= first_cid && cid <= first_cid + num_left) {
1784                     *gid = first_gid + cid - first_cid;
1785                     return CAIRO_STATUS_SUCCESS;
1786                 }
1787                 first_gid += num_left + 1;
1788                 p += 3;
1789             }
1790             break;
1791
1792         /* Format 2 */
1793         case 2:
1794             first_gid = 1;
1795             p = font->charset + 1;
1796             while (first_gid <= (unsigned)font->num_glyphs && p + 3 < font->data_end) {
1797                 first_cid = get_unaligned_be16 (p);
1798                 num_left = get_unaligned_be16 (p+2);
1799                 if (cid >= first_cid && cid <= first_cid + num_left) {
1800                     *gid = first_gid + cid - first_cid;
1801                     return CAIRO_STATUS_SUCCESS;
1802                 }
1803                 first_gid += num_left + 1;
1804                 p += 4;
1805             }
1806             break;
1807
1808         default:
1809             break;
1810     }
1811     return CAIRO_INT_STATUS_UNSUPPORTED;
1812 }
1813
1814 static cairo_int_status_t
1815 cairo_cff_font_subset_charstrings_and_subroutines (cairo_cff_font_t  *font)
1816 {
1817     cff_index_element_t *element;
1818     unsigned int i;
1819     cairo_int_status_t status;
1820     unsigned long glyph, cid;
1821
1822     font->subset_subroutines = TRUE;
1823     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++) {
1824         if (font->is_cid) {
1825             cid = font->scaled_font_subset->glyphs[i];
1826             status = cairo_cff_font_get_gid_for_cid (font, cid, &glyph);
1827             if (unlikely (status))
1828                 return status;
1829         } else {
1830             glyph = font->scaled_font_subset->glyphs[i];
1831         }
1832         element = _cairo_array_index (&font->charstrings_index, glyph);
1833         if (element == NULL)
1834             return CAIRO_STATUS_NULL_POINTER;
1835
1836         status = cff_index_append (&font->charstrings_subset_index,
1837                                    element->data,
1838                                    element->length);
1839         if (unlikely (status))
1840             return status;
1841
1842         if (font->subset_subroutines) {
1843             status = cairo_cff_find_width_and_subroutines_used (font,
1844                                                                 element->data, element->length,
1845                                                                 glyph, i);
1846             if (status == CAIRO_INT_STATUS_UNSUPPORTED) {
1847                 /* If parsing the charstrings fails we embed all the
1848                  * subroutines. But if the font is not opentype we
1849                  * need to successfully parse all charstrings to get
1850                  * the widths. */
1851                 font->subset_subroutines = FALSE;
1852                 if (!font->is_opentype)
1853                     return status;
1854             } else if (unlikely (status)) {
1855                 return status;
1856             }
1857         }
1858     }
1859
1860     return CAIRO_STATUS_SUCCESS;
1861 }
1862
1863 static cairo_status_t
1864 cairo_cff_font_subset_fontdict (cairo_cff_font_t  *font)
1865 {
1866     unsigned int i;
1867     int fd;
1868     int *reverse_map;
1869     unsigned long cid, gid;
1870     cairo_int_status_t status;
1871
1872     font->fdselect_subset = calloc (font->scaled_font_subset->num_glyphs,
1873                                      sizeof (int));
1874     if (unlikely (font->fdselect_subset == NULL))
1875         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1876
1877     font->fd_subset_map = calloc (font->num_fontdicts, sizeof (int));
1878     if (unlikely (font->fd_subset_map == NULL))
1879         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1880
1881     font->private_dict_offset = calloc (font->num_fontdicts, sizeof (int));
1882     if (unlikely (font->private_dict_offset == NULL))
1883         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1884
1885     reverse_map = calloc (font->num_fontdicts, sizeof (int));
1886     if (unlikely (reverse_map == NULL))
1887         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1888
1889     for (i = 0; i < font->num_fontdicts; i++)
1890         reverse_map[i] = -1;
1891
1892     font->num_subset_fontdicts = 0;
1893     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++) {
1894         cid = font->scaled_font_subset->glyphs[i];
1895         status = cairo_cff_font_get_gid_for_cid (font, cid, &gid);
1896         if (unlikely (status)) {
1897             free (reverse_map);
1898             return status;
1899         }
1900
1901         fd = font->fdselect[gid];
1902         if (reverse_map[fd] < 0) {
1903             font->fd_subset_map[font->num_subset_fontdicts] = fd;
1904             reverse_map[fd] = font->num_subset_fontdicts++;
1905         }
1906         font->fdselect_subset[i] = reverse_map[fd];
1907     }
1908
1909     free (reverse_map);
1910
1911     return CAIRO_STATUS_SUCCESS;
1912 }
1913
1914 static cairo_status_t
1915 cairo_cff_font_create_cid_fontdict (cairo_cff_font_t *font)
1916 {
1917     unsigned char buf[100];
1918     unsigned char *end_buf;
1919     cairo_status_t status;
1920
1921     font->num_fontdicts = 1;
1922     font->fd_dict = _cairo_malloc (sizeof (cairo_hash_table_t *));
1923     if (unlikely (font->fd_dict == NULL))
1924         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1925
1926     if (cff_dict_init (&font->fd_dict[0])) {
1927         free (font->fd_dict);
1928         font->fd_dict = NULL;
1929         font->num_fontdicts = 0;
1930         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1931     }
1932
1933     font->fd_subset_map = _cairo_malloc (sizeof (int));
1934     if (unlikely (font->fd_subset_map == NULL))
1935         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1936
1937     font->private_dict_offset = _cairo_malloc (sizeof (int));
1938     if (unlikely (font->private_dict_offset == NULL))
1939         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1940
1941     font->fd_subset_map[0] = 0;
1942     font->num_subset_fontdicts = 1;
1943
1944     /* Set integer operand to max value to use max size encoding to reserve
1945      * space for any value later */
1946     end_buf = encode_integer_max (buf, 0);
1947     end_buf = encode_integer_max (end_buf, 0);
1948     status = cff_dict_set_operands (font->fd_dict[0], PRIVATE_OP, buf, end_buf - buf);
1949     if (unlikely (status))
1950         return status;
1951
1952     return CAIRO_STATUS_SUCCESS;
1953 }
1954
1955 static cairo_status_t
1956 cairo_cff_font_subset_strings (cairo_cff_font_t *font)
1957 {
1958     cairo_status_t status;
1959     unsigned int i;
1960
1961     status = cairo_cff_font_subset_dict_strings (font, font->top_dict);
1962     if (unlikely (status))
1963         return status;
1964
1965     if (font->is_cid) {
1966         for (i = 0; i < font->num_subset_fontdicts; i++) {
1967             status = cairo_cff_font_subset_dict_strings (font, font->fd_dict[font->fd_subset_map[i]]);
1968             if (unlikely (status))
1969                 return status;
1970
1971             status = cairo_cff_font_subset_dict_strings (font, font->fd_private_dict[font->fd_subset_map[i]]);
1972             if (unlikely (status))
1973                 return status;
1974         }
1975     } else {
1976         status = cairo_cff_font_subset_dict_strings (font, font->private_dict);
1977     }
1978
1979     return status;
1980 }
1981
1982 /* The Euro is the only the only character in the winansi encoding
1983  * with a glyph name that is not a CFF standard string. As the strings
1984  * are written before the charset, we need to check during the
1985  * subsetting phase if the Euro glyph is required and add the
1986  * glyphname to the list of strings to write out.
1987  */
1988 static cairo_status_t
1989 cairo_cff_font_add_euro_charset_string (cairo_cff_font_t *font)
1990 {
1991     cairo_status_t status;
1992     unsigned int i;
1993     int ch;
1994     const char *euro = "Euro";
1995
1996     for (i = 1; i < font->scaled_font_subset->num_glyphs; i++) {
1997         ch = font->scaled_font_subset->to_latin_char[i];
1998         if (ch == 128) {
1999             font->euro_sid = NUM_STD_STRINGS + _cairo_array_num_elements (&font->strings_subset_index);
2000             status = cff_index_append_copy (&font->strings_subset_index,
2001                                             (unsigned char *)euro, strlen(euro));
2002             return status;
2003         }
2004     }
2005
2006     return CAIRO_STATUS_SUCCESS;
2007 }
2008
2009 static cairo_status_t
2010 cairo_cff_font_subset_font (cairo_cff_font_t  *font)
2011 {
2012     cairo_status_t status;
2013
2014     if (!font->scaled_font_subset->is_latin) {
2015         status = cairo_cff_font_set_ros_strings (font);
2016         if (unlikely (status))
2017             return status;
2018     }
2019
2020     status = cairo_cff_font_subset_charstrings_and_subroutines (font);
2021     if (unlikely (status))
2022         return status;
2023
2024     if (!font->scaled_font_subset->is_latin) {
2025         if (font->is_cid)
2026             status = cairo_cff_font_subset_fontdict (font);
2027         else
2028             status = cairo_cff_font_create_cid_fontdict (font);
2029         if (unlikely (status))
2030             return status;
2031     }  else {
2032         font->private_dict_offset = _cairo_malloc (sizeof (int));
2033         if (unlikely (font->private_dict_offset == NULL))
2034             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2035     }
2036
2037     status = cairo_cff_font_subset_strings (font);
2038     if (unlikely (status))
2039         return status;
2040
2041     if (font->scaled_font_subset->is_latin)
2042         status = cairo_cff_font_add_euro_charset_string (font);
2043
2044     return status;
2045 }
2046
2047 /* Set the operand of the specified operator in the (already written)
2048  * top dict to point to the current position in the output
2049  * array. Operands updated with this function must have previously
2050  * been encoded with the 5-byte (max) integer encoding. */
2051 static void
2052 cairo_cff_font_set_topdict_operator_to_cur_pos (cairo_cff_font_t  *font,
2053                                                 int                operator)
2054 {
2055     int cur_pos;
2056     int offset;
2057     int size;
2058     unsigned char buf[10];
2059     unsigned char *buf_end;
2060     unsigned char *op_ptr;
2061
2062     cur_pos = _cairo_array_num_elements (&font->output);
2063     buf_end = encode_integer_max (buf, cur_pos);
2064     offset = cff_dict_get_location (font->top_dict, operator, &size);
2065     assert (offset > 0);
2066     op_ptr = _cairo_array_index (&font->output, offset);
2067     memcpy (op_ptr, buf, buf_end - buf);
2068 }
2069
2070 static cairo_status_t
2071 cairo_cff_font_write_header (cairo_cff_font_t *font)
2072 {
2073     return _cairo_array_append_multiple (&font->output,
2074                                          font->header,
2075                                          font->header->header_size);
2076 }
2077
2078 static cairo_status_t
2079 cairo_cff_font_write_name (cairo_cff_font_t *font)
2080 {
2081     cairo_status_t status = CAIRO_STATUS_SUCCESS;
2082     cairo_array_t index;
2083
2084     cff_index_init (&index);
2085
2086     status = cff_index_append_copy (&index,
2087                                     (unsigned char *) font->ps_name,
2088                                     strlen(font->ps_name));
2089     if (unlikely (status))
2090         goto FAIL;
2091
2092     status = cff_index_write (&index, &font->output);
2093     if (unlikely (status))
2094         goto FAIL;
2095
2096 FAIL:
2097     cff_index_fini (&index);
2098
2099     return status;
2100 }
2101
2102 static cairo_status_t
2103 cairo_cff_font_write_top_dict (cairo_cff_font_t *font)
2104 {
2105     uint16_t count;
2106     unsigned char buf[10];
2107     unsigned char *p;
2108     int offset_index;
2109     int dict_start, dict_size;
2110     int offset_size = 4;
2111     cairo_status_t status;
2112
2113     /* Write an index containing the top dict */
2114
2115     count = cpu_to_be16 (1);
2116     status = _cairo_array_append_multiple (&font->output, &count, 2);
2117     if (unlikely (status))
2118         return status;
2119     buf[0] = offset_size;
2120     status = _cairo_array_append (&font->output, buf);
2121     if (unlikely (status))
2122         return status;
2123     encode_index_offset (buf, offset_size, 1);
2124     status = _cairo_array_append_multiple (&font->output, buf, offset_size);
2125     if (unlikely (status))
2126         return status;
2127
2128     /* Reserve space for last element of offset array and update after
2129      * dict is written */
2130     offset_index = _cairo_array_num_elements (&font->output);
2131     status = _cairo_array_append_multiple (&font->output, buf, offset_size);
2132     if (unlikely (status))
2133         return status;
2134
2135     dict_start = _cairo_array_num_elements (&font->output);
2136     status = cff_dict_write (font->top_dict, &font->output);
2137     if (unlikely (status))
2138         return status;
2139     dict_size = _cairo_array_num_elements (&font->output) - dict_start;
2140
2141     encode_index_offset (buf, offset_size, dict_size + 1);
2142     p = _cairo_array_index (&font->output, offset_index);
2143     if (p == NULL)
2144         return CAIRO_STATUS_NULL_POINTER;
2145     memcpy (p, buf, offset_size);
2146
2147     return CAIRO_STATUS_SUCCESS;
2148 }
2149
2150 static cairo_status_t
2151 cairo_cff_font_write_strings (cairo_cff_font_t  *font)
2152 {
2153     return cff_index_write (&font->strings_subset_index, &font->output);
2154 }
2155
2156 static cairo_status_t
2157 cairo_cff_font_write_global_subrs (cairo_cff_font_t  *font)
2158 {
2159     unsigned int i;
2160     unsigned char return_op = TYPE2_return;
2161
2162     /* poppler and fontforge don't like zero length subroutines so we
2163      * replace unused subroutines with a 'return' instruction. */
2164     if (font->subset_subroutines) {
2165         for (i = 0; i < _cairo_array_num_elements (&font->global_sub_index); i++) {
2166             if (! font->global_subs_used[i])
2167                 cff_index_set_object (&font->global_sub_index, i, &return_op, 1);
2168         }
2169     }
2170
2171     return cff_index_write (&font->global_sub_index, &font->output);
2172 }
2173
2174 static cairo_status_t
2175 cairo_cff_font_write_encoding (cairo_cff_font_t  *font)
2176 {
2177     unsigned char buf[2];
2178     cairo_status_t status;
2179     unsigned int i;
2180
2181     cairo_cff_font_set_topdict_operator_to_cur_pos (font, ENCODING_OP);
2182     buf[0] = 0; /* Format 0 */
2183     buf[1] = font->scaled_font_subset->num_glyphs - 1;
2184     status = _cairo_array_append_multiple (&font->output, buf, 2);
2185     if (unlikely (status))
2186         return status;
2187
2188     for (i = 1; i < font->scaled_font_subset->num_glyphs; i++) {
2189         unsigned char ch = font->scaled_font_subset->to_latin_char[i];
2190         status = _cairo_array_append (&font->output, &ch);
2191         if (unlikely (status))
2192             return status;
2193     }
2194
2195     return CAIRO_STATUS_SUCCESS;
2196 }
2197
2198 static cairo_status_t
2199 cairo_cff_font_write_fdselect (cairo_cff_font_t  *font)
2200 {
2201     unsigned char data;
2202     unsigned int i;
2203     cairo_int_status_t status;
2204
2205     cairo_cff_font_set_topdict_operator_to_cur_pos (font, FDSELECT_OP);
2206
2207     if (font->is_cid) {
2208         data = 0;
2209         status = _cairo_array_append (&font->output, &data);
2210         if (unlikely (status))
2211             return status;
2212
2213         for (i = 0; i < font->scaled_font_subset->num_glyphs; i++) {
2214             data = font->fdselect_subset[i];
2215             status = _cairo_array_append (&font->output, &data);
2216             if (unlikely (status))
2217                 return status;
2218         }
2219     } else {
2220         unsigned char byte;
2221         uint16_t word;
2222
2223         status = _cairo_array_grow_by (&font->output, 9);
2224         if (unlikely (status))
2225             return status;
2226
2227         byte = 3;
2228         status = _cairo_array_append (&font->output, &byte);
2229         assert (status == CAIRO_INT_STATUS_SUCCESS);
2230
2231         word = cpu_to_be16 (1);
2232         status = _cairo_array_append_multiple (&font->output, &word, 2);
2233         assert (status == CAIRO_INT_STATUS_SUCCESS);
2234
2235         word = cpu_to_be16 (0);
2236         status = _cairo_array_append_multiple (&font->output, &word, 2);
2237         assert (status == CAIRO_INT_STATUS_SUCCESS);
2238
2239         byte = 0;
2240         status = _cairo_array_append (&font->output, &byte);
2241         assert (status == CAIRO_INT_STATUS_SUCCESS);
2242
2243         word = cpu_to_be16 (font->scaled_font_subset->num_glyphs);
2244         status = _cairo_array_append_multiple (&font->output, &word, 2);
2245         assert (status == CAIRO_INT_STATUS_SUCCESS);
2246     }
2247
2248     return CAIRO_STATUS_SUCCESS;
2249 }
2250
2251 /* Winansi to CFF standard strings mapping for characters 128 to 255 */
2252 static const int winansi_to_cff_std_string[] = {
2253         /* 128 */
2254       0,   0, 117, 101, 118, 121, 112, 113,
2255     126, 122, 192, 107, 142,   0, 199,   0,
2256         /* 144 */
2257       0,  65,   8, 105, 119, 116, 111, 137,
2258     127, 153, 221, 108, 148,   0, 228, 198,
2259         /* 160 */
2260       0,  96,  97,  98, 103, 100, 160, 102,
2261     131, 170, 139, 106, 151,   0, 165, 128,
2262         /* 176 */
2263     161, 156, 164, 169, 125, 152, 115, 114,
2264     133, 150, 143, 120, 158, 155, 163, 123,
2265         /* 192 */
2266     174, 171, 172, 176, 173, 175, 138, 177,
2267     181, 178, 179, 180, 185, 182, 183, 184,
2268         /* 208 */
2269     154, 186, 190, 187, 188, 191, 189, 168,
2270     141, 196, 193, 194, 195, 197, 157, 149,
2271         /* 224 */
2272     203, 200, 201, 205, 202, 204, 144, 206,
2273     210, 207, 208, 209, 214, 211, 212, 213,
2274         /* 240 */
2275     167, 215, 219, 216, 217, 220, 218, 159,
2276     147, 225, 222, 223, 224, 226, 162, 227,
2277 };
2278
2279 static int
2280 cairo_cff_font_get_sid_for_winansi_char (cairo_cff_font_t  *font, int ch)
2281 {
2282     int sid;
2283
2284     if (ch == 39) {
2285         sid = 104;
2286
2287     } else if (ch == 96) {
2288         sid = 124;
2289
2290     } else if (ch >= 32 && ch <= 126) {
2291         sid = ch - 31;
2292
2293     } else if (ch == 128) {
2294         assert (font->euro_sid >= NUM_STD_STRINGS);
2295         sid = font->euro_sid;
2296
2297     } else if (ch >= 128 && ch <= 255) {
2298         sid = winansi_to_cff_std_string[ch - 128];
2299
2300     } else {
2301         sid = 0;
2302     }
2303
2304     return sid;
2305 }
2306
2307 static cairo_status_t
2308 cairo_cff_font_write_type1_charset (cairo_cff_font_t  *font)
2309 {
2310     unsigned char format = 0;
2311     unsigned int i;
2312     int ch, sid;
2313     cairo_status_t status;
2314     uint16_t sid_be16;
2315
2316     cairo_cff_font_set_topdict_operator_to_cur_pos (font, CHARSET_OP);
2317     status = _cairo_array_append (&font->output, &format);
2318     if (unlikely (status))
2319         return status;
2320
2321     for (i = 1; i < font->scaled_font_subset->num_glyphs; i++) {
2322         ch = font->scaled_font_subset->to_latin_char[i];
2323         sid = cairo_cff_font_get_sid_for_winansi_char (font, ch);
2324
2325         sid_be16 = cpu_to_be16(sid);
2326         status = _cairo_array_append_multiple (&font->output, &sid_be16, sizeof(sid_be16));
2327         if (unlikely (status))
2328             return status;
2329     }
2330
2331     return CAIRO_STATUS_SUCCESS;
2332 }
2333
2334 static cairo_status_t
2335 cairo_cff_font_write_cid_charset (cairo_cff_font_t  *font)
2336 {
2337     unsigned char byte;
2338     uint16_t word;
2339     cairo_status_t status;
2340
2341     cairo_cff_font_set_topdict_operator_to_cur_pos (font, CHARSET_OP);
2342     status = _cairo_array_grow_by (&font->output, 5);
2343     if (unlikely (status))
2344         return status;
2345
2346     byte = 2;
2347     status = _cairo_array_append (&font->output, &byte);
2348     assert (status == CAIRO_STATUS_SUCCESS);
2349
2350     word = cpu_to_be16 (1);
2351     status = _cairo_array_append_multiple (&font->output, &word, 2);
2352     assert (status == CAIRO_STATUS_SUCCESS);
2353
2354     word = cpu_to_be16 (font->scaled_font_subset->num_glyphs - 2);
2355     status = _cairo_array_append_multiple (&font->output, &word, 2);
2356     assert (status == CAIRO_STATUS_SUCCESS);
2357
2358     return CAIRO_STATUS_SUCCESS;
2359 }
2360
2361 static cairo_status_t
2362 cairo_cff_font_write_charstrings (cairo_cff_font_t  *font)
2363 {
2364     cairo_cff_font_set_topdict_operator_to_cur_pos (font, CHARSTRINGS_OP);
2365
2366     return cff_index_write (&font->charstrings_subset_index, &font->output);
2367 }
2368
2369 static cairo_status_t
2370 cairo_cff_font_write_cid_fontdict (cairo_cff_font_t *font)
2371 {
2372     unsigned int i;
2373     cairo_int_status_t status;
2374     unsigned int offset_array;
2375     unsigned char *offset_array_ptr;
2376     int offset_base;
2377     uint16_t count;
2378     uint8_t offset_size = 4;
2379
2380     cairo_cff_font_set_topdict_operator_to_cur_pos (font, FDARRAY_OP);
2381     count = cpu_to_be16 (font->num_subset_fontdicts);
2382     status = _cairo_array_append_multiple (&font->output, &count, sizeof (uint16_t));
2383     if (unlikely (status))
2384         return status;
2385     status = _cairo_array_append (&font->output, &offset_size);
2386     if (unlikely (status))
2387         return status;
2388
2389     offset_array = _cairo_array_num_elements (&font->output);
2390     status = _cairo_array_allocate (&font->output,
2391                                     (font->num_subset_fontdicts + 1)*offset_size,
2392                                     (void **) &offset_array_ptr);
2393     if (unlikely (status))
2394         return status;
2395     offset_base = _cairo_array_num_elements (&font->output) - 1;
2396     put_unaligned_be32(1, offset_array_ptr);
2397     offset_array += sizeof(uint32_t);
2398     for (i = 0; i < font->num_subset_fontdicts; i++) {
2399         status = cff_dict_write (font->fd_dict[font->fd_subset_map[i]],
2400                                  &font->output);
2401         if (unlikely (status))
2402             return status;
2403
2404         offset_array_ptr = _cairo_array_index (&font->output, offset_array);
2405         put_unaligned_be32 (_cairo_array_num_elements (&font->output) - offset_base,
2406                             offset_array_ptr);
2407         offset_array += sizeof(uint32_t);
2408     }
2409
2410     return CAIRO_STATUS_SUCCESS;
2411 }
2412
2413 static cairo_status_t
2414 cairo_cff_font_write_private_dict (cairo_cff_font_t   *font,
2415                                    int                 dict_num,
2416                                    cairo_hash_table_t *parent_dict,
2417                                    cairo_hash_table_t *private_dict)
2418 {
2419     int offset;
2420     int size;
2421     unsigned char buf[10];
2422     unsigned char *buf_end;
2423     unsigned char *p;
2424     cairo_status_t status;
2425
2426     /* Write private dict and update offset and size in top dict */
2427     font->private_dict_offset[dict_num] = _cairo_array_num_elements (&font->output);
2428     status = cff_dict_write (private_dict, &font->output);
2429     if (unlikely (status))
2430         return status;
2431
2432     size = _cairo_array_num_elements (&font->output) - font->private_dict_offset[dict_num];
2433     /* private entry has two operands - size and offset */
2434     buf_end = encode_integer_max (buf, size);
2435     buf_end = encode_integer_max (buf_end, font->private_dict_offset[dict_num]);
2436     offset = cff_dict_get_location (parent_dict, PRIVATE_OP, &size);
2437     assert (offset > 0);
2438     p = _cairo_array_index (&font->output, offset);
2439     memcpy (p, buf, buf_end - buf);
2440
2441     return CAIRO_STATUS_SUCCESS;
2442 }
2443
2444 static cairo_status_t
2445 cairo_cff_font_write_local_sub (cairo_cff_font_t   *font,
2446                                 int                 dict_num,
2447                                 cairo_hash_table_t *private_dict,
2448                                 cairo_array_t      *local_sub_index,
2449                                 cairo_bool_t       *local_subs_used)
2450 {
2451     int offset;
2452     int size;
2453     unsigned char buf[10];
2454     unsigned char *buf_end;
2455     unsigned char *p;
2456     cairo_status_t status;
2457     unsigned int i;
2458     unsigned char return_op = TYPE2_return;
2459
2460     if (_cairo_array_num_elements (local_sub_index) > 0) {
2461         /* Write local subroutines and update offset in private
2462          * dict. Local subroutines offset is relative to start of
2463          * private dict */
2464         offset = _cairo_array_num_elements (&font->output) - font->private_dict_offset[dict_num];
2465         buf_end = encode_integer_max (buf, offset);
2466         offset = cff_dict_get_location (private_dict, LOCAL_SUB_OP, &size);
2467         assert (offset > 0);
2468         p = _cairo_array_index (&font->output, offset);
2469         memcpy (p, buf, buf_end - buf);
2470
2471         /* poppler and fontforge don't like zero length subroutines so
2472          * we replace unused subroutines with a 'return' instruction.
2473          */
2474         if (font->subset_subroutines) {
2475             for (i = 0; i < _cairo_array_num_elements (local_sub_index); i++) {
2476                 if (! local_subs_used[i])
2477                     cff_index_set_object (local_sub_index, i, &return_op, 1);
2478             }
2479         }
2480         status = cff_index_write (local_sub_index, &font->output);
2481         if (unlikely (status))
2482             return status;
2483     }
2484
2485     return CAIRO_STATUS_SUCCESS;
2486 }
2487
2488
2489 static cairo_status_t
2490 cairo_cff_font_write_cid_private_dict_and_local_sub (cairo_cff_font_t  *font)
2491 {
2492     unsigned int i;
2493     cairo_int_status_t status;
2494
2495     if (font->is_cid) {
2496         for (i = 0; i < font->num_subset_fontdicts; i++) {
2497             status = cairo_cff_font_write_private_dict (
2498                             font,
2499                             i,
2500                             font->fd_dict[font->fd_subset_map[i]],
2501                             font->fd_private_dict[font->fd_subset_map[i]]);
2502             if (unlikely (status))
2503                 return status;
2504         }
2505
2506         for (i = 0; i < font->num_subset_fontdicts; i++) {
2507             status = cairo_cff_font_write_local_sub (
2508                             font,
2509                             i,
2510                             font->fd_private_dict[font->fd_subset_map[i]],
2511                             &font->fd_local_sub_index[font->fd_subset_map[i]],
2512                             font->fd_local_subs_used[font->fd_subset_map[i]]);
2513             if (unlikely (status))
2514                 return status;
2515         }
2516     } else {
2517         status = cairo_cff_font_write_private_dict (font,
2518                                                     0,
2519                                                     font->fd_dict[0],
2520                                                     font->private_dict);
2521         if (unlikely (status))
2522             return status;
2523
2524         status = cairo_cff_font_write_local_sub (font,
2525                                                  0,
2526                                                  font->private_dict,
2527                                                  &font->local_sub_index,
2528                                                  font->local_subs_used);
2529         if (unlikely (status))
2530             return status;
2531     }
2532
2533     return CAIRO_STATUS_SUCCESS;
2534 }
2535
2536 static cairo_status_t
2537 cairo_cff_font_write_type1_private_dict_and_local_sub (cairo_cff_font_t  *font)
2538 {
2539     cairo_int_status_t status;
2540
2541     status = cairo_cff_font_write_private_dict (font,
2542                                                 0,
2543                                                 font->top_dict,
2544                                                 font->private_dict);
2545     if (unlikely (status))
2546         return status;
2547
2548     status = cairo_cff_font_write_local_sub (font,
2549                                              0,
2550                                              font->private_dict,
2551                                              &font->local_sub_index,
2552                                              font->local_subs_used);
2553     if (unlikely (status))
2554         return status;
2555
2556     return CAIRO_STATUS_SUCCESS;
2557 }
2558
2559
2560 typedef cairo_status_t
2561 (*font_write_t) (cairo_cff_font_t *font);
2562
2563 static const font_write_t font_write_cid_funcs[] = {
2564     cairo_cff_font_write_header,
2565     cairo_cff_font_write_name,
2566     cairo_cff_font_write_top_dict,
2567     cairo_cff_font_write_strings,
2568     cairo_cff_font_write_global_subrs,
2569     cairo_cff_font_write_cid_charset,
2570     cairo_cff_font_write_fdselect,
2571     cairo_cff_font_write_charstrings,
2572     cairo_cff_font_write_cid_fontdict,
2573     cairo_cff_font_write_cid_private_dict_and_local_sub,
2574 };
2575
2576 static const font_write_t font_write_type1_funcs[] = {
2577     cairo_cff_font_write_header,
2578     cairo_cff_font_write_name,
2579     cairo_cff_font_write_top_dict,
2580     cairo_cff_font_write_strings,
2581     cairo_cff_font_write_global_subrs,
2582     cairo_cff_font_write_encoding,
2583     cairo_cff_font_write_type1_charset,
2584     cairo_cff_font_write_charstrings,
2585     cairo_cff_font_write_type1_private_dict_and_local_sub,
2586 };
2587
2588 static cairo_status_t
2589 cairo_cff_font_write_subset (cairo_cff_font_t *font)
2590 {
2591     cairo_int_status_t status;
2592     unsigned int i;
2593
2594     if (font->scaled_font_subset->is_latin) {
2595         for (i = 0; i < ARRAY_LENGTH (font_write_type1_funcs); i++) {
2596             status = font_write_type1_funcs[i] (font);
2597             if (unlikely (status))
2598                 return status;
2599         }
2600     } else {
2601         for (i = 0; i < ARRAY_LENGTH (font_write_cid_funcs); i++) {
2602             status = font_write_cid_funcs[i] (font);
2603             if (unlikely (status))
2604                 return status;
2605         }
2606     }
2607
2608     return CAIRO_STATUS_SUCCESS;
2609 }
2610
2611 static cairo_int_status_t
2612 cairo_cff_font_generate (cairo_cff_font_t  *font,
2613                          const char       **data,
2614                          unsigned long     *length)
2615 {
2616     cairo_int_status_t status;
2617
2618     status = cairo_cff_font_read_font (font);
2619     if (unlikely (status))
2620         return status;
2621
2622     /* If the PS name is not found, create a CairoFont-x-y name. */
2623     if (font->ps_name == NULL) {
2624         font->ps_name = _cairo_malloc (30);
2625         if (unlikely (font->ps_name == NULL))
2626             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2627
2628         snprintf(font->ps_name, 30, "CairoFont-%u-%u",
2629                  font->scaled_font_subset->font_id,
2630                  font->scaled_font_subset->subset_id);
2631     }
2632
2633     status = cairo_cff_font_subset_font (font);
2634     if (unlikely (status))
2635         return status;
2636
2637     status = cairo_cff_font_write_subset (font);
2638     if (unlikely (status))
2639         return status;
2640
2641
2642     *data = _cairo_array_index (&font->output, 0);
2643     *length = _cairo_array_num_elements (&font->output);
2644
2645     return CAIRO_STATUS_SUCCESS;
2646 }
2647
2648 static cairo_int_status_t
2649 cairo_cff_font_create_set_widths (cairo_cff_font_t *font)
2650 {
2651     unsigned long size;
2652     unsigned long long_entry_size;
2653     unsigned long short_entry_size;
2654     unsigned int i;
2655     tt_hhea_t hhea;
2656     int num_hmetrics;
2657     uint16_t short_entry;
2658     int glyph_index;
2659     cairo_int_status_t status;
2660
2661     size = sizeof (tt_hhea_t);
2662     status = font->backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2663                                                  TT_TAG_hhea, 0,
2664                                                  (unsigned char*) &hhea, &size);
2665     if (unlikely (status))
2666         return status;
2667     num_hmetrics = be16_to_cpu (hhea.num_hmetrics);
2668
2669     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++) {
2670         glyph_index = font->scaled_font_subset->glyphs[i];
2671         long_entry_size = 2 * sizeof (int16_t);
2672         short_entry_size = sizeof (int16_t);
2673         if (glyph_index < num_hmetrics) {
2674             status = font->backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2675                                                          TT_TAG_hmtx,
2676                                                          glyph_index * long_entry_size,
2677                                                          (unsigned char *) &short_entry,
2678                                                          &short_entry_size);
2679             if (unlikely (status))
2680                 return status;
2681         }
2682         else
2683         {
2684             status = font->backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2685                                                          TT_TAG_hmtx,
2686                                                          (num_hmetrics - 1) * long_entry_size,
2687                                                          (unsigned char *) &short_entry,
2688                                                          &short_entry_size);
2689             if (unlikely (status))
2690                 return status;
2691         }
2692         font->widths[i] = be16_to_cpu (short_entry);
2693     }
2694
2695     return CAIRO_STATUS_SUCCESS;
2696 }
2697
2698 static cairo_bool_t
2699 check_fontdata_is_cff (const unsigned char *data, long length)
2700 {
2701     cff_header_t *header;
2702
2703     if (length < (long)sizeof (cff_header_t))
2704         return FALSE;
2705
2706     header = (cff_header_t *) data;
2707     if (header->major == 1 &&
2708         header->minor == 0 &&
2709         header->header_size == 4)
2710     {
2711         return TRUE;
2712     }
2713
2714     return FALSE;
2715 }
2716
2717 static cairo_int_status_t
2718 _cairo_cff_font_load_opentype_cff (cairo_cff_font_t  *font)
2719 {
2720     const cairo_scaled_font_backend_t *backend = font->backend;
2721     cairo_status_t status;
2722     tt_head_t head;
2723     tt_hhea_t hhea;
2724     unsigned long size, data_length;
2725
2726     if (!backend->load_truetype_table)
2727         return CAIRO_INT_STATUS_UNSUPPORTED;
2728
2729     data_length = 0;
2730     status = backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2731                                            TT_TAG_CFF, 0, NULL, &data_length);
2732     if (status)
2733         return status;
2734
2735     size = sizeof (tt_head_t);
2736     status = backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2737                                            TT_TAG_head, 0,
2738                                            (unsigned char *) &head, &size);
2739     if (unlikely (status))
2740         return status;
2741
2742     size = sizeof (tt_hhea_t);
2743     status = backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2744                                            TT_TAG_hhea, 0,
2745                                            (unsigned char *) &hhea, &size);
2746     if (unlikely (status))
2747         return status;
2748
2749     size = 0;
2750     status = backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2751                                            TT_TAG_hmtx, 0, NULL, &size);
2752     if (unlikely (status))
2753         return status;
2754
2755     font->x_min = (int16_t) be16_to_cpu (head.x_min);
2756     font->y_min = (int16_t) be16_to_cpu (head.y_min);
2757     font->x_max = (int16_t) be16_to_cpu (head.x_max);
2758     font->y_max = (int16_t) be16_to_cpu (head.y_max);
2759     font->ascent = (int16_t) be16_to_cpu (hhea.ascender);
2760     font->descent = (int16_t) be16_to_cpu (hhea.descender);
2761     font->units_per_em = (int16_t) be16_to_cpu (head.units_per_em);
2762     if (font->units_per_em == 0)
2763         font->units_per_em = 1000;
2764
2765     font->font_name = NULL;
2766     status = _cairo_truetype_read_font_name (font->scaled_font_subset->scaled_font,
2767                                              &font->ps_name,
2768                                              &font->font_name);
2769     if (_cairo_status_is_error (status))
2770         return status;
2771
2772     font->is_opentype = TRUE;
2773     font->data_length = data_length;
2774     font->data = malloc (data_length);
2775     if (unlikely (font->data == NULL))
2776         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2777
2778     status = font->backend->load_truetype_table (font->scaled_font_subset->scaled_font,
2779                                                  TT_TAG_CFF, 0, font->data,
2780                                                  &font->data_length);
2781     if (unlikely (status))
2782         return status;
2783
2784     if (!check_fontdata_is_cff (font->data, data_length))
2785         return CAIRO_INT_STATUS_UNSUPPORTED;
2786
2787     return CAIRO_STATUS_SUCCESS;
2788 }
2789
2790 static cairo_int_status_t
2791 _cairo_cff_font_load_cff (cairo_cff_font_t  *font)
2792 {
2793     const cairo_scaled_font_backend_t *backend = font->backend;
2794     cairo_status_t status;
2795     unsigned long data_length;
2796
2797     if (!backend->load_type1_data)
2798         return CAIRO_INT_STATUS_UNSUPPORTED;
2799
2800     data_length = 0;
2801     status = backend->load_type1_data (font->scaled_font_subset->scaled_font,
2802                                       0, NULL, &data_length);
2803     if (unlikely (status))
2804         return status;
2805
2806     font->font_name = NULL;
2807     font->is_opentype = FALSE;
2808     font->data_length = data_length;
2809     font->data = _cairo_malloc (data_length);
2810     if (unlikely (font->data == NULL))
2811         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2812
2813     status = font->backend->load_type1_data (font->scaled_font_subset->scaled_font,
2814                                              0, font->data, &font->data_length);
2815     if (unlikely (status))
2816         return status;
2817
2818     if (!check_fontdata_is_cff (font->data, data_length))
2819         return CAIRO_INT_STATUS_UNSUPPORTED;
2820
2821     return CAIRO_STATUS_SUCCESS;
2822 }
2823
2824 static cairo_int_status_t
2825 _cairo_cff_font_create (cairo_scaled_font_subset_t  *scaled_font_subset,
2826                         cairo_cff_font_t           **font_return,
2827                         const char                  *subset_name)
2828 {
2829     const cairo_scaled_font_backend_t *backend;
2830     cairo_int_status_t status;
2831     cairo_cff_font_t *font;
2832
2833     backend = scaled_font_subset->scaled_font->backend;
2834
2835     /* We need to use a fallback font generated from the synthesized outlines. */
2836     if (backend->is_synthetic && backend->is_synthetic (scaled_font_subset->scaled_font))
2837         return CAIRO_INT_STATUS_UNSUPPORTED;
2838
2839     font = calloc (1, sizeof (cairo_cff_font_t));
2840     if (unlikely (font == NULL))
2841         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2842
2843     font->backend = backend;
2844     font->scaled_font_subset = scaled_font_subset;
2845
2846     status = _cairo_cff_font_load_opentype_cff (font);
2847     if (status == CAIRO_INT_STATUS_UNSUPPORTED)
2848         status = _cairo_cff_font_load_cff (font);
2849     if (status)
2850         goto fail1;
2851
2852     font->data_end = font->data + font->data_length;
2853     _cairo_array_init (&font->output, sizeof (char));
2854     status = _cairo_array_grow_by (&font->output, 4096);
2855     if (unlikely (status))
2856         goto fail2;
2857
2858     font->subset_font_name = strdup (subset_name);
2859     if (unlikely (font->subset_font_name == NULL)) {
2860         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2861         goto fail2;
2862     }
2863
2864     font->widths = calloc (font->scaled_font_subset->num_glyphs, sizeof (int));
2865     if (unlikely (font->widths == NULL)) {
2866         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2867         goto fail3;
2868     }
2869
2870     if (font->is_opentype) {
2871         status = cairo_cff_font_create_set_widths (font);
2872         if (unlikely (status))
2873             goto fail4;
2874     }
2875
2876     status = cff_dict_init (&font->top_dict);
2877     if (unlikely (status))
2878         goto fail4;
2879
2880     status = cff_dict_init (&font->private_dict);
2881     if (unlikely (status))
2882         goto fail5;
2883
2884     cff_index_init (&font->strings_index);
2885     cff_index_init (&font->charstrings_index);
2886     cff_index_init (&font->global_sub_index);
2887     cff_index_init (&font->local_sub_index);
2888     cff_index_init (&font->charstrings_subset_index);
2889     cff_index_init (&font->strings_subset_index);
2890     font->euro_sid = 0;
2891     font->fdselect = NULL;
2892     font->fd_dict = NULL;
2893     font->fd_private_dict = NULL;
2894     font->fd_local_sub_index = NULL;
2895     font->fd_local_sub_bias = NULL;
2896     font->fdselect_subset = NULL;
2897     font->fd_subset_map = NULL;
2898     font->private_dict_offset = NULL;
2899     font->global_subs_used = NULL;
2900     font->local_subs_used = NULL;
2901     font->fd_local_subs_used = NULL;
2902
2903     *font_return = font;
2904
2905     return CAIRO_STATUS_SUCCESS;
2906
2907 fail5:
2908     _cairo_hash_table_destroy (font->top_dict);
2909 fail4:
2910     free (font->widths);
2911 fail3:
2912     free (font->subset_font_name);
2913 fail2:
2914     free (font->ps_name);
2915     _cairo_array_fini (&font->output);
2916 fail1:
2917     free (font->data);
2918     free (font->font_name);
2919     free (font);
2920
2921     return status;
2922 }
2923
2924 static void
2925 cairo_cff_font_destroy (cairo_cff_font_t *font)
2926 {
2927     unsigned int i;
2928
2929     free (font->widths);
2930     free (font->font_name);
2931     free (font->ps_name);
2932     free (font->subset_font_name);
2933     _cairo_array_fini (&font->output);
2934     cff_dict_fini (font->top_dict);
2935     cff_dict_fini (font->private_dict);
2936     cff_index_fini (&font->strings_index);
2937     cff_index_fini (&font->charstrings_index);
2938     cff_index_fini (&font->global_sub_index);
2939     cff_index_fini (&font->local_sub_index);
2940     cff_index_fini (&font->charstrings_subset_index);
2941     cff_index_fini (&font->strings_subset_index);
2942
2943     /* If we bailed out early as a result of an error some of the
2944      * following cairo_cff_font_t members may still be NULL */
2945     if (font->fd_dict) {
2946         for (i = 0; i < font->num_fontdicts; i++) {
2947             if (font->fd_dict[i])
2948                 cff_dict_fini (font->fd_dict[i]);
2949         }
2950         free (font->fd_dict);
2951     }
2952     free (font->global_subs_used);
2953     free (font->local_subs_used);
2954     free (font->fd_subset_map);
2955     free (font->private_dict_offset);
2956
2957     if (font->is_cid) {
2958         free (font->fdselect);
2959         free (font->fdselect_subset);
2960         if (font->fd_private_dict) {
2961             for (i = 0; i < font->num_fontdicts; i++) {
2962                 if (font->fd_private_dict[i])
2963                     cff_dict_fini (font->fd_private_dict[i]);
2964             }
2965             free (font->fd_private_dict);
2966         }
2967         if (font->fd_local_sub_index) {
2968             for (i = 0; i < font->num_fontdicts; i++)
2969                 cff_index_fini (&font->fd_local_sub_index[i]);
2970             free (font->fd_local_sub_index);
2971         }
2972         free (font->fd_local_sub_bias);
2973         if (font->fd_local_subs_used) {
2974             for (i = 0; i < font->num_fontdicts; i++) {
2975                 free (font->fd_local_subs_used[i]);
2976             }
2977             free (font->fd_local_subs_used);
2978         }
2979         free (font->fd_default_width);
2980         free (font->fd_nominal_width);
2981     }
2982
2983     free (font->data);
2984
2985     free (font);
2986 }
2987
2988 cairo_status_t
2989 _cairo_cff_subset_init (cairo_cff_subset_t          *cff_subset,
2990                         const char                  *subset_name,
2991                         cairo_scaled_font_subset_t  *font_subset)
2992 {
2993     cairo_cff_font_t *font = NULL; /* squelch bogus compiler warning */
2994     cairo_status_t status;
2995     const char *data = NULL; /* squelch bogus compiler warning */
2996     unsigned long length = 0; /* squelch bogus compiler warning */
2997     unsigned int i;
2998
2999     status = _cairo_cff_font_create (font_subset, &font, subset_name);
3000     if (unlikely (status))
3001         return status;
3002
3003     status = cairo_cff_font_generate (font, &data, &length);
3004     if (unlikely (status))
3005         goto fail1;
3006
3007     cff_subset->ps_name = strdup (font->ps_name);
3008     if (unlikely (cff_subset->ps_name == NULL)) {
3009         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3010         goto fail1;
3011     }
3012
3013     if (font->font_name) {
3014         cff_subset->family_name_utf8 = strdup (font->font_name);
3015         if (cff_subset->family_name_utf8 == NULL) {
3016             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3017             goto fail2;
3018         }
3019     } else {
3020         cff_subset->family_name_utf8 = NULL;
3021     }
3022
3023     cff_subset->widths = calloc (sizeof (double), font->scaled_font_subset->num_glyphs);
3024     if (unlikely (cff_subset->widths == NULL)) {
3025         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3026         goto fail3;
3027     }
3028     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++)
3029         cff_subset->widths[i] = (double)font->widths[i]/font->units_per_em;
3030
3031     cff_subset->x_min = (double)font->x_min/font->units_per_em;
3032     cff_subset->y_min = (double)font->y_min/font->units_per_em;
3033     cff_subset->x_max = (double)font->x_max/font->units_per_em;
3034     cff_subset->y_max = (double)font->y_max/font->units_per_em;
3035     cff_subset->ascent = (double)font->ascent/font->units_per_em;
3036     cff_subset->descent = (double)font->descent/font->units_per_em;
3037
3038     cff_subset->data = _cairo_malloc (length);
3039     if (unlikely (cff_subset->data == NULL)) {
3040         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3041         goto fail4;
3042     }
3043
3044     memcpy (cff_subset->data, data, length);
3045     cff_subset->data_length = length;
3046
3047     cairo_cff_font_destroy (font);
3048
3049     return CAIRO_STATUS_SUCCESS;
3050
3051  fail4:
3052     free (cff_subset->widths);
3053  fail3:
3054     free (cff_subset->family_name_utf8);
3055  fail2:
3056     free (cff_subset->ps_name);
3057  fail1:
3058     cairo_cff_font_destroy (font);
3059
3060     return status;
3061 }
3062
3063 void
3064 _cairo_cff_subset_fini (cairo_cff_subset_t *subset)
3065 {
3066     free (subset->ps_name);
3067     free (subset->family_name_utf8);
3068     free (subset->widths);
3069     free (subset->data);
3070 }
3071
3072 cairo_bool_t
3073 _cairo_cff_scaled_font_is_cid_cff (cairo_scaled_font_t *scaled_font)
3074 {
3075     const cairo_scaled_font_backend_t *backend;
3076     cairo_int_status_t status;
3077     unsigned char *data;
3078     unsigned long data_length;
3079     unsigned char *current_ptr;
3080     unsigned char *data_end;
3081     cff_header_t  *header;
3082     cff_index_element_t *element;
3083     cairo_hash_table_t  *top_dict;
3084     cairo_array_t index;
3085     int size;
3086     cairo_bool_t is_cid = FALSE;
3087
3088     backend = scaled_font->backend;
3089     data = NULL;
3090     data_length = 0;
3091     status = CAIRO_INT_STATUS_UNSUPPORTED;
3092     /* Try to load an OpenType/CFF font */
3093     if (backend->load_truetype_table &&
3094         (status = backend->load_truetype_table (scaled_font, TT_TAG_CFF,
3095                                                 0, NULL, &data_length)) == CAIRO_INT_STATUS_SUCCESS)
3096     {
3097         data = _cairo_malloc (data_length);
3098         if (unlikely (data == NULL)) {
3099             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3100             return FALSE;
3101         }
3102
3103         status = backend->load_truetype_table (scaled_font, TT_TAG_CFF,
3104                                            0, data, &data_length);
3105         if (unlikely (status))
3106             goto fail1;
3107     }
3108     /* Try to load a CFF font */
3109     if (status == CAIRO_INT_STATUS_UNSUPPORTED &&
3110         backend->load_type1_data &&
3111         (status = backend->load_type1_data (scaled_font,
3112                                             0, NULL, &data_length)) == CAIRO_INT_STATUS_SUCCESS)
3113     {
3114         data = _cairo_malloc (data_length);
3115         if (unlikely (data == NULL)) {
3116             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3117             return FALSE;
3118         }
3119
3120         status = backend->load_type1_data (scaled_font, 0, data, &data_length);
3121         if (unlikely (status))
3122             goto fail1;
3123     }
3124     if (status)
3125         goto fail1;
3126
3127     /* Check if it looks like a CFF font */
3128     if (!check_fontdata_is_cff (data, data_length))
3129         goto fail1;
3130
3131     data_end = data + data_length;
3132
3133     /* skip header */
3134     if (data_length < sizeof (cff_header_t))
3135         goto fail1;
3136
3137     header = (cff_header_t *) data;
3138     current_ptr = data + header->header_size;
3139
3140     /* skip name */
3141     cff_index_init (&index);
3142     status = cff_index_read (&index, &current_ptr, data_end);
3143     cff_index_fini (&index);
3144
3145     if (status)
3146         goto fail1;
3147
3148     /* read top dict */
3149     cff_index_init (&index);
3150     status = cff_index_read (&index, &current_ptr, data_end);
3151     if (unlikely (status))
3152         goto fail2;
3153
3154     status = cff_dict_init (&top_dict);
3155     if (unlikely (status))
3156         goto fail2;
3157
3158     element = _cairo_array_index (&index, 0);
3159     if (element == NULL) {
3160         status = _cairo_error (CAIRO_STATUS_NULL_POINTER);
3161         goto fail3;
3162     }
3163
3164     status = cff_dict_read (top_dict, element->data, element->length);
3165     if (unlikely (status))
3166         goto fail3;
3167
3168     /* check for ROS operator indicating a CID font */
3169     if (cff_dict_get_operands (top_dict, ROS_OP, &size) != NULL)
3170         is_cid = TRUE;
3171
3172 fail3:
3173     cff_dict_fini (top_dict);
3174
3175 fail2:
3176     cff_index_fini (&index);
3177
3178 fail1:
3179     free (data);
3180
3181     return is_cid;
3182 }
3183
3184 static cairo_int_status_t
3185 _cairo_cff_font_fallback_create (cairo_scaled_font_subset_t  *scaled_font_subset,
3186                                  cairo_cff_font_t           **font_return,
3187                                  const char                  *subset_name)
3188 {
3189     cairo_status_t status;
3190     cairo_cff_font_t *font;
3191
3192     font = _cairo_malloc (sizeof (cairo_cff_font_t));
3193     if (unlikely (font == NULL))
3194         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3195
3196     font->backend = NULL;
3197     font->scaled_font_subset = scaled_font_subset;
3198
3199     _cairo_array_init (&font->output, sizeof (char));
3200     status = _cairo_array_grow_by (&font->output, 4096);
3201     if (unlikely (status))
3202         goto fail1;
3203
3204     font->subset_font_name = strdup (subset_name);
3205     if (unlikely (font->subset_font_name == NULL)) {
3206         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3207         goto fail1;
3208     }
3209
3210     font->ps_name = strdup (subset_name);
3211     if (unlikely (font->ps_name == NULL)) {
3212         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3213         goto fail2;
3214     }
3215     font->font_name = NULL;
3216
3217     font->x_min = 0;
3218     font->y_min = 0;
3219     font->x_max = 0;
3220     font->y_max = 0;
3221     font->ascent = 0;
3222     font->descent = 0;
3223
3224     font->widths = calloc (font->scaled_font_subset->num_glyphs, sizeof (int));
3225     if (unlikely (font->widths == NULL)) {
3226         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3227         goto fail3;
3228     }
3229
3230     font->data_length = 0;
3231     font->data = NULL;
3232     font->data_end = NULL;
3233
3234     status = cff_dict_init (&font->top_dict);
3235     if (unlikely (status))
3236         goto fail4;
3237
3238     status = cff_dict_init (&font->private_dict);
3239     if (unlikely (status))
3240         goto fail5;
3241
3242     cff_index_init (&font->strings_index);
3243     cff_index_init (&font->charstrings_index);
3244     cff_index_init (&font->global_sub_index);
3245     cff_index_init (&font->local_sub_index);
3246     cff_index_init (&font->charstrings_subset_index);
3247     cff_index_init (&font->strings_subset_index);
3248     font->global_subs_used = NULL;
3249     font->local_subs_used = NULL;
3250     font->subset_subroutines = FALSE;
3251     font->fdselect = NULL;
3252     font->fd_dict = NULL;
3253     font->fd_private_dict = NULL;
3254     font->fd_local_sub_index = NULL;
3255     font->fdselect_subset = NULL;
3256     font->fd_subset_map = NULL;
3257     font->private_dict_offset = NULL;
3258
3259     *font_return = font;
3260
3261     return CAIRO_STATUS_SUCCESS;
3262
3263 fail5:
3264     _cairo_hash_table_destroy (font->top_dict);
3265 fail4:
3266     free (font->widths);
3267 fail3:
3268     free (font->font_name);
3269     free (font->ps_name);
3270 fail2:
3271     free (font->subset_font_name);
3272 fail1:
3273     _cairo_array_fini (&font->output);
3274     free (font);
3275     return status;
3276 }
3277
3278 static cairo_int_status_t
3279 cairo_cff_font_fallback_generate (cairo_cff_font_t           *font,
3280                                   cairo_type2_charstrings_t  *type2_subset,
3281                                   const char                **data,
3282                                   unsigned long              *length)
3283 {
3284     cairo_int_status_t status;
3285     cff_header_t header;
3286     cairo_array_t *charstring;
3287     unsigned char buf[40];
3288     unsigned char *end_buf, *end_buf2;
3289     unsigned int i;
3290     int sid;
3291
3292     /* Create header */
3293     header.major = 1;
3294     header.minor = 0;
3295     header.header_size = 4;
3296     header.offset_size = 4;
3297     font->header = &header;
3298
3299     /* Create Top Dict */
3300     font->is_cid = FALSE;
3301
3302     snprintf((char*)buf, sizeof(buf), "CairoFont-%u-%u",
3303              font->scaled_font_subset->font_id,
3304              font->scaled_font_subset->subset_id);
3305     sid = NUM_STD_STRINGS + _cairo_array_num_elements (&font->strings_subset_index);
3306     status = cff_index_append_copy (&font->strings_subset_index,
3307                                     (unsigned char *)buf,
3308                                     strlen((char*)buf));
3309     if (unlikely (status))
3310         return status;
3311
3312     end_buf = encode_integer (buf, sid);
3313     status = cff_dict_set_operands (font->top_dict, FULLNAME_OP,
3314                                     buf, end_buf - buf);
3315     if (unlikely (status))
3316         return status;
3317
3318     status = cff_dict_set_operands (font->top_dict, FAMILYNAME_OP,
3319                                     buf, end_buf - buf);
3320     if (unlikely (status))
3321         return status;
3322
3323     end_buf = encode_integer (buf, type2_subset->x_min);
3324     end_buf = encode_integer (end_buf, type2_subset->y_min);
3325     end_buf = encode_integer (end_buf, type2_subset->x_max);
3326     end_buf = encode_integer (end_buf, type2_subset->y_max);
3327     status = cff_dict_set_operands (font->top_dict,
3328                                     FONTBBOX_OP, buf, end_buf - buf);
3329     if (unlikely (status))
3330         return status;
3331
3332     end_buf = encode_integer_max (buf, 0);
3333     status = cff_dict_set_operands (font->top_dict,
3334                                     CHARSTRINGS_OP, buf, end_buf - buf);
3335     if (unlikely (status))
3336         return status;
3337
3338
3339     if (font->scaled_font_subset->is_latin) {
3340         status = cff_dict_set_operands (font->top_dict,
3341                                         ENCODING_OP, buf, end_buf - buf);
3342         if (unlikely (status))
3343             return status;
3344
3345         /* Private has two operands - size and offset */
3346         end_buf2 = encode_integer_max (end_buf, 0);
3347         cff_dict_set_operands (font->top_dict, PRIVATE_OP, buf, end_buf2 - buf);
3348
3349     } else {
3350         status = cff_dict_set_operands (font->top_dict,
3351                                         FDSELECT_OP, buf, end_buf - buf);
3352         if (unlikely (status))
3353             return status;
3354
3355         status = cff_dict_set_operands (font->top_dict,
3356                                         FDARRAY_OP, buf, end_buf - buf);
3357         if (unlikely (status))
3358             return status;
3359     }
3360
3361     status = cff_dict_set_operands (font->top_dict,
3362                                     CHARSET_OP, buf, end_buf - buf);
3363     if (unlikely (status))
3364         return status;
3365
3366     if (!font->scaled_font_subset->is_latin) {
3367         status = cairo_cff_font_set_ros_strings (font);
3368         if (unlikely (status))
3369             return status;
3370
3371         /* Create CID FD dictionary */
3372         status = cairo_cff_font_create_cid_fontdict (font);
3373         if (unlikely (status))
3374             return status;
3375     } else {
3376         font->private_dict_offset = _cairo_malloc (sizeof (int));
3377         if (unlikely (font->private_dict_offset == NULL))
3378             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3379     }
3380
3381     /* Create charstrings */
3382     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++) {
3383         charstring = _cairo_array_index(&type2_subset->charstrings, i);
3384         if (charstring == NULL)
3385             return _cairo_error (CAIRO_STATUS_NULL_POINTER);
3386
3387         status = cff_index_append (&font->charstrings_subset_index,
3388                                    _cairo_array_index (charstring, 0),
3389                                    _cairo_array_num_elements (charstring));
3390
3391         if (unlikely (status))
3392             return status;
3393     }
3394
3395     if (font->scaled_font_subset->is_latin)
3396         status = cairo_cff_font_add_euro_charset_string (font);
3397
3398     status = cairo_cff_font_write_subset (font);
3399     if (unlikely (status))
3400         return status;
3401
3402     *data = _cairo_array_index (&font->output, 0);
3403     *length = _cairo_array_num_elements (&font->output);
3404
3405     return CAIRO_STATUS_SUCCESS;
3406 }
3407
3408 cairo_status_t
3409 _cairo_cff_fallback_init (cairo_cff_subset_t          *cff_subset,
3410                           const char                  *subset_name,
3411                           cairo_scaled_font_subset_t  *font_subset)
3412 {
3413     cairo_cff_font_t *font = NULL; /* squelch bogus compiler warning */
3414     cairo_status_t status;
3415     const char *data = NULL; /* squelch bogus compiler warning */
3416     unsigned long length = 0; /* squelch bogus compiler warning */
3417     unsigned int i;
3418     cairo_type2_charstrings_t type2_subset;
3419
3420     status = _cairo_cff_font_fallback_create (font_subset, &font, subset_name);
3421     if (unlikely (status))
3422         return status;
3423
3424     status = _cairo_type2_charstrings_init (&type2_subset, font_subset);
3425     if (unlikely (status))
3426         goto fail1;
3427
3428     status = cairo_cff_font_fallback_generate (font, &type2_subset, &data, &length);
3429     if (unlikely (status))
3430         goto fail2;
3431
3432     cff_subset->family_name_utf8 = NULL;
3433     cff_subset->ps_name = strdup (font->ps_name);
3434     if (unlikely (cff_subset->ps_name == NULL)) {
3435         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3436         goto fail2;
3437     }
3438
3439     cff_subset->widths = calloc (sizeof (double), font->scaled_font_subset->num_glyphs);
3440     if (unlikely (cff_subset->widths == NULL)) {
3441         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3442         goto fail3;
3443     }
3444
3445     for (i = 0; i < font->scaled_font_subset->num_glyphs; i++)
3446         cff_subset->widths[i] = (double)type2_subset.widths[i]/1000;
3447
3448     cff_subset->x_min = (double)type2_subset.x_min/1000;
3449     cff_subset->y_min = (double)type2_subset.y_min/1000;
3450     cff_subset->x_max = (double)type2_subset.x_max/1000;
3451     cff_subset->y_max = (double)type2_subset.y_max/1000;
3452     cff_subset->ascent = (double)type2_subset.y_max/1000;
3453     cff_subset->descent = (double)type2_subset.y_min/1000;
3454
3455     cff_subset->data = _cairo_malloc (length);
3456     if (unlikely (cff_subset->data == NULL)) {
3457         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
3458         goto fail4;
3459     }
3460
3461     memcpy (cff_subset->data, data, length);
3462     cff_subset->data_length = length;
3463
3464     _cairo_type2_charstrings_fini (&type2_subset);
3465     cairo_cff_font_destroy (font);
3466
3467     return CAIRO_STATUS_SUCCESS;
3468
3469  fail4:
3470     free (cff_subset->widths);
3471  fail3:
3472     free (cff_subset->ps_name);
3473  fail2:
3474     _cairo_type2_charstrings_fini (&type2_subset);
3475  fail1:
3476     cairo_cff_font_destroy (font);
3477
3478     return status;
3479 }
3480
3481 void
3482 _cairo_cff_fallback_fini (cairo_cff_subset_t *subset)
3483 {
3484     free (subset->ps_name);
3485     free (subset->widths);
3486     free (subset->data);
3487 }
3488
3489 #endif /* CAIRO_HAS_FONT_SUBSET */