1 /****************************************************************************
2  *
3  * cffparse.c
4  *
5  *   CFF token stream parser (body)
6  *
7  * Copyright 1996-2018 by
8  * David Turner, Robert Wilhelm, and Werner Lemberg.
9  *
10  * This file is part of the FreeType project, and may only be used,
11  * modified, and distributed under the terms of the FreeType project
12  * license, LICENSE.TXT.  By continuing to use, modify, or distribute
13  * this file you indicate that you have read the license and
14  * understand and accept it fully.
15  *
16  */
17 
18 
19 #include <ft2build.h>
20 #include "cffparse.h"
21 #include FT_INTERNAL_STREAM_H
22 #include FT_INTERNAL_DEBUG_H
23 #include FT_INTERNAL_CALC_H
24 #include FT_INTERNAL_POSTSCRIPT_AUX_H
25 
26 #include "cfferrs.h"
27 #include "cffload.h"
28 
29 
30   /**************************************************************************
31    *
32    * The macro FT_COMPONENT is used in trace mode.  It is an implicit
33    * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
34    * messages during execution.
35    */
36 #undef  FT_COMPONENT
37 #define FT_COMPONENT  trace_cffparse
38 
39 
40   FT_LOCAL_DEF( FT_Error )
cff_parser_init(CFF_Parser parser,FT_UInt code,void * object,FT_Library library,FT_UInt stackSize,FT_UShort num_designs,FT_UShort num_axes)41   cff_parser_init( CFF_Parser  parser,
42                    FT_UInt     code,
43                    void*       object,
44                    FT_Library  library,
45                    FT_UInt     stackSize,
46                    FT_UShort   num_designs,
47                    FT_UShort   num_axes )
48   {
49     FT_Memory  memory = library->memory;    /* for FT_NEW_ARRAY */
50     FT_Error   error;                       /* for FT_NEW_ARRAY */
51 
52 
53     FT_ZERO( parser );
54 
55 #if 0
56     parser->top         = parser->stack;
57 #endif
58     parser->object_code = code;
59     parser->object      = object;
60     parser->library     = library;
61     parser->num_designs = num_designs;
62     parser->num_axes    = num_axes;
63 
64     /* allocate the stack buffer */
65     if ( FT_NEW_ARRAY( parser->stack, stackSize ) )
66     {
67       FT_FREE( parser->stack );
68       goto Exit;
69     }
70 
71     parser->stackSize = stackSize;
72     parser->top       = parser->stack;    /* empty stack */
73 
74   Exit:
75     return error;
76   }
77 
78 
79   FT_LOCAL_DEF( void )
cff_parser_done(CFF_Parser parser)80   cff_parser_done( CFF_Parser  parser )
81   {
82     FT_Memory  memory = parser->library->memory;    /* for FT_FREE */
83 
84 
85     FT_FREE( parser->stack );
86   }
87 
88 
89   /* read an integer */
90   static FT_Long
cff_parse_integer(FT_Byte * start,FT_Byte * limit)91   cff_parse_integer( FT_Byte*  start,
92                      FT_Byte*  limit )
93   {
94     FT_Byte*  p   = start;
95     FT_Int    v   = *p++;
96     FT_Long   val = 0;
97 
98 
99     if ( v == 28 )
100     {
101       if ( p + 2 > limit )
102         goto Bad;
103 
104       val = (FT_Short)( ( (FT_UShort)p[0] << 8 ) | p[1] );
105     }
106     else if ( v == 29 )
107     {
108       if ( p + 4 > limit )
109         goto Bad;
110 
111       val = (FT_Long)( ( (FT_ULong)p[0] << 24 ) |
112                        ( (FT_ULong)p[1] << 16 ) |
113                        ( (FT_ULong)p[2] <<  8 ) |
114                          (FT_ULong)p[3]         );
115     }
116     else if ( v < 247 )
117     {
118       val = v - 139;
119     }
120     else if ( v < 251 )
121     {
122       if ( p + 1 > limit )
123         goto Bad;
124 
125       val = ( v - 247 ) * 256 + p[0] + 108;
126     }
127     else
128     {
129       if ( p + 1 > limit )
130         goto Bad;
131 
132       val = -( v - 251 ) * 256 - p[0] - 108;
133     }
134 
135   Exit:
136     return val;
137 
138   Bad:
139     val = 0;
140     FT_TRACE4(( "!!!END OF DATA:!!!" ));
141     goto Exit;
142   }
143 
144 
145   static const FT_Long power_tens[] =
146   {
147     1L,
148     10L,
149     100L,
150     1000L,
151     10000L,
152     100000L,
153     1000000L,
154     10000000L,
155     100000000L,
156     1000000000L
157   };
158 
159   /* maximum values allowed for multiplying      */
160   /* with the corresponding `power_tens' element */
161   static const FT_Long power_ten_limits[] =
162   {
163     FT_LONG_MAX / 1L,
164     FT_LONG_MAX / 10L,
165     FT_LONG_MAX / 100L,
166     FT_LONG_MAX / 1000L,
167     FT_LONG_MAX / 10000L,
168     FT_LONG_MAX / 100000L,
169     FT_LONG_MAX / 1000000L,
170     FT_LONG_MAX / 10000000L,
171     FT_LONG_MAX / 100000000L,
172     FT_LONG_MAX / 1000000000L,
173   };
174 
175 
176   /* read a real */
177   static FT_Fixed
cff_parse_real(FT_Byte * start,FT_Byte * limit,FT_Long power_ten,FT_Long * scaling)178   cff_parse_real( FT_Byte*  start,
179                   FT_Byte*  limit,
180                   FT_Long   power_ten,
181                   FT_Long*  scaling )
182   {
183     FT_Byte*  p = start;
184     FT_Int    nib;
185     FT_UInt   phase;
186 
187     FT_Long   result, number, exponent;
188     FT_Int    sign = 0, exponent_sign = 0, have_overflow = 0;
189     FT_Long   exponent_add, integer_length, fraction_length;
190 
191 
192     if ( scaling )
193       *scaling = 0;
194 
195     result = 0;
196 
197     number   = 0;
198     exponent = 0;
199 
200     exponent_add    = 0;
201     integer_length  = 0;
202     fraction_length = 0;
203 
204     /* First of all, read the integer part. */
205     phase = 4;
206 
207     for (;;)
208     {
209       /* If we entered this iteration with phase == 4, we need to */
210       /* read a new byte.  This also skips past the initial 0x1E. */
211       if ( phase )
212       {
213         p++;
214 
215         /* Make sure we don't read past the end. */
216         if ( p >= limit )
217           goto Bad;
218       }
219 
220       /* Get the nibble. */
221       nib   = (FT_Int)( p[0] >> phase ) & 0xF;
222       phase = 4 - phase;
223 
224       if ( nib == 0xE )
225         sign = 1;
226       else if ( nib > 9 )
227         break;
228       else
229       {
230         /* Increase exponent if we can't add the digit. */
231         if ( number >= 0xCCCCCCCL )
232           exponent_add++;
233         /* Skip leading zeros. */
234         else if ( nib || number )
235         {
236           integer_length++;
237           number = number * 10 + nib;
238         }
239       }
240     }
241 
242     /* Read fraction part, if any. */
243     if ( nib == 0xA )
244       for (;;)
245       {
246         /* If we entered this iteration with phase == 4, we need */
247         /* to read a new byte.                                   */
248         if ( phase )
249         {
250           p++;
251 
252           /* Make sure we don't read past the end. */
253           if ( p >= limit )
254             goto Bad;
255         }
256 
257         /* Get the nibble. */
258         nib   = ( p[0] >> phase ) & 0xF;
259         phase = 4 - phase;
260         if ( nib >= 10 )
261           break;
262 
263         /* Skip leading zeros if possible. */
264         if ( !nib && !number )
265           exponent_add--;
266         /* Only add digit if we don't overflow. */
267         else if ( number < 0xCCCCCCCL && fraction_length < 9 )
268         {
269           fraction_length++;
270           number = number * 10 + nib;
271         }
272       }
273 
274     /* Read exponent, if any. */
275     if ( nib == 12 )
276     {
277       exponent_sign = 1;
278       nib           = 11;
279     }
280 
281     if ( nib == 11 )
282     {
283       for (;;)
284       {
285         /* If we entered this iteration with phase == 4, */
286         /* we need to read a new byte.                   */
287         if ( phase )
288         {
289           p++;
290 
291           /* Make sure we don't read past the end. */
292           if ( p >= limit )
293             goto Bad;
294         }
295 
296         /* Get the nibble. */
297         nib   = ( p[0] >> phase ) & 0xF;
298         phase = 4 - phase;
299         if ( nib >= 10 )
300           break;
301 
302         /* Arbitrarily limit exponent. */
303         if ( exponent > 1000 )
304           have_overflow = 1;
305         else
306           exponent = exponent * 10 + nib;
307       }
308 
309       if ( exponent_sign )
310         exponent = -exponent;
311     }
312 
313     if ( !number )
314       goto Exit;
315 
316     if ( have_overflow )
317     {
318       if ( exponent_sign )
319         goto Underflow;
320       else
321         goto Overflow;
322     }
323 
324     /* We don't check `power_ten' and `exponent_add'. */
325     exponent += power_ten + exponent_add;
326 
327     if ( scaling )
328     {
329       /* Only use `fraction_length'. */
330       fraction_length += integer_length;
331       exponent        += integer_length;
332 
333       if ( fraction_length <= 5 )
334       {
335         if ( number > 0x7FFFL )
336         {
337           result   = FT_DivFix( number, 10 );
338           *scaling = exponent - fraction_length + 1;
339         }
340         else
341         {
342           if ( exponent > 0 )
343           {
344             FT_Long  new_fraction_length, shift;
345 
346 
347             /* Make `scaling' as small as possible. */
348             new_fraction_length = FT_MIN( exponent, 5 );
349             shift               = new_fraction_length - fraction_length;
350 
351             if ( shift > 0 )
352             {
353               exponent -= new_fraction_length;
354               number   *= power_tens[shift];
355               if ( number > 0x7FFFL )
356               {
357                 number   /= 10;
358                 exponent += 1;
359               }
360             }
361             else
362               exponent -= fraction_length;
363           }
364           else
365             exponent -= fraction_length;
366 
367           result   = (FT_Long)( (FT_ULong)number << 16 );
368           *scaling = exponent;
369         }
370       }
371       else
372       {
373         if ( ( number / power_tens[fraction_length - 5] ) > 0x7FFFL )
374         {
375           result   = FT_DivFix( number, power_tens[fraction_length - 4] );
376           *scaling = exponent - 4;
377         }
378         else
379         {
380           result   = FT_DivFix( number, power_tens[fraction_length - 5] );
381           *scaling = exponent - 5;
382         }
383       }
384     }
385     else
386     {
387       integer_length  += exponent;
388       fraction_length -= exponent;
389 
390       if ( integer_length > 5 )
391         goto Overflow;
392       if ( integer_length < -5 )
393         goto Underflow;
394 
395       /* Remove non-significant digits. */
396       if ( integer_length < 0 )
397       {
398         number          /= power_tens[-integer_length];
399         fraction_length += integer_length;
400       }
401 
402       /* this can only happen if exponent was non-zero */
403       if ( fraction_length == 10 )
404       {
405         number          /= 10;
406         fraction_length -= 1;
407       }
408 
409       /* Convert into 16.16 format. */
410       if ( fraction_length > 0 )
411       {
412         if ( ( number / power_tens[fraction_length] ) > 0x7FFFL )
413           goto Exit;
414 
415         result = FT_DivFix( number, power_tens[fraction_length] );
416       }
417       else
418       {
419         number *= power_tens[-fraction_length];
420 
421         if ( number > 0x7FFFL )
422           goto Overflow;
423 
424         result = (FT_Long)( (FT_ULong)number << 16 );
425       }
426     }
427 
428   Exit:
429     if ( sign )
430       result = -result;
431 
432     return result;
433 
434   Overflow:
435     result = 0x7FFFFFFFL;
436     FT_TRACE4(( "!!!OVERFLOW:!!!" ));
437     goto Exit;
438 
439   Underflow:
440     result = 0;
441     FT_TRACE4(( "!!!UNDERFLOW:!!!" ));
442     goto Exit;
443 
444   Bad:
445     result = 0;
446     FT_TRACE4(( "!!!END OF DATA:!!!" ));
447     goto Exit;
448   }
449 
450 
451   /* read a number, either integer or real */
452   FT_LOCAL_DEF( FT_Long )
cff_parse_num(CFF_Parser parser,FT_Byte ** d)453   cff_parse_num( CFF_Parser  parser,
454                  FT_Byte**   d )
455   {
456     if ( **d == 30 )
457     {
458       /* binary-coded decimal is truncated to integer */
459       return cff_parse_real( *d, parser->limit, 0, NULL ) >> 16;
460     }
461 
462     else if ( **d == 255 )
463     {
464       /* 16.16 fixed point is used internally for CFF2 blend results. */
465       /* Since these are trusted values, a limit check is not needed. */
466 
467       /* After the 255, 4 bytes give the number.                 */
468       /* The blend value is converted to integer, with rounding; */
469       /* due to the right-shift we don't need the lowest byte.   */
470 #if 0
471       return (FT_Short)(
472                ( ( ( (FT_UInt32)*( d[0] + 1 ) << 24 ) |
473                    ( (FT_UInt32)*( d[0] + 2 ) << 16 ) |
474                    ( (FT_UInt32)*( d[0] + 3 ) <<  8 ) |
475                      (FT_UInt32)*( d[0] + 4 )         ) + 0x8000U ) >> 16 );
476 #else
477       return (FT_Short)(
478                ( ( ( (FT_UInt32)*( d[0] + 1 ) << 16 ) |
479                    ( (FT_UInt32)*( d[0] + 2 ) <<  8 ) |
480                      (FT_UInt32)*( d[0] + 3 )         ) + 0x80U ) >> 8 );
481 #endif
482     }
483 
484     else
485       return cff_parse_integer( *d, parser->limit );
486   }
487 
488 
489   /* read a floating point number, either integer or real */
490   static FT_Fixed
do_fixed(CFF_Parser parser,FT_Byte ** d,FT_Long scaling)491   do_fixed( CFF_Parser  parser,
492             FT_Byte**   d,
493             FT_Long     scaling )
494   {
495     if ( **d == 30 )
496       return cff_parse_real( *d, parser->limit, scaling, NULL );
497     else
498     {
499       FT_Long  val = cff_parse_integer( *d, parser->limit );
500 
501 
502       if ( scaling )
503       {
504         if ( FT_ABS( val ) > power_ten_limits[scaling] )
505         {
506           val = val > 0 ? 0x7FFFFFFFL : -0x7FFFFFFFL;
507           goto Overflow;
508         }
509 
510         val *= power_tens[scaling];
511       }
512 
513       if ( val > 0x7FFF )
514       {
515         val = 0x7FFFFFFFL;
516         goto Overflow;
517       }
518       else if ( val < -0x7FFF )
519       {
520         val = -0x7FFFFFFFL;
521         goto Overflow;
522       }
523 
524       return (FT_Long)( (FT_ULong)val << 16 );
525 
526     Overflow:
527       FT_TRACE4(( "!!!OVERFLOW:!!!" ));
528       return val;
529     }
530   }
531 
532 
533   /* read a floating point number, either integer or real */
534   static FT_Fixed
cff_parse_fixed(CFF_Parser parser,FT_Byte ** d)535   cff_parse_fixed( CFF_Parser  parser,
536                    FT_Byte**   d )
537   {
538     return do_fixed( parser, d, 0 );
539   }
540 
541 
542   /* read a floating point number, either integer or real, */
543   /* but return `10^scaling' times the number read in      */
544   static FT_Fixed
cff_parse_fixed_scaled(CFF_Parser parser,FT_Byte ** d,FT_Long scaling)545   cff_parse_fixed_scaled( CFF_Parser  parser,
546                           FT_Byte**   d,
547                           FT_Long     scaling )
548   {
549     return do_fixed( parser, d, scaling );
550   }
551 
552 
553   /* read a floating point number, either integer or real,     */
554   /* and return it as precise as possible -- `scaling' returns */
555   /* the scaling factor (as a power of 10)                     */
556   static FT_Fixed
cff_parse_fixed_dynamic(CFF_Parser parser,FT_Byte ** d,FT_Long * scaling)557   cff_parse_fixed_dynamic( CFF_Parser  parser,
558                            FT_Byte**   d,
559                            FT_Long*    scaling )
560   {
561     FT_ASSERT( scaling );
562 
563     if ( **d == 30 )
564       return cff_parse_real( *d, parser->limit, 0, scaling );
565     else
566     {
567       FT_Long  number;
568       FT_Int   integer_length;
569 
570 
571       number = cff_parse_integer( d[0], d[1] );
572 
573       if ( number > 0x7FFFL )
574       {
575         for ( integer_length = 5; integer_length < 10; integer_length++ )
576           if ( number < power_tens[integer_length] )
577             break;
578 
579         if ( ( number / power_tens[integer_length - 5] ) > 0x7FFFL )
580         {
581           *scaling = integer_length - 4;
582           return FT_DivFix( number, power_tens[integer_length - 4] );
583         }
584         else
585         {
586           *scaling = integer_length - 5;
587           return FT_DivFix( number, power_tens[integer_length - 5] );
588         }
589       }
590       else
591       {
592         *scaling = 0;
593         return (FT_Long)( (FT_ULong)number << 16 );
594       }
595     }
596   }
597 
598 
599   static FT_Error
cff_parse_font_matrix(CFF_Parser parser)600   cff_parse_font_matrix( CFF_Parser  parser )
601   {
602     CFF_FontRecDict  dict   = (CFF_FontRecDict)parser->object;
603     FT_Matrix*       matrix = &dict->font_matrix;
604     FT_Vector*       offset = &dict->font_offset;
605     FT_ULong*        upm    = &dict->units_per_em;
606     FT_Byte**        data   = parser->stack;
607 
608 
609     if ( parser->top >= parser->stack + 6 )
610     {
611       FT_Fixed  values[6];
612       FT_Long   scalings[6];
613 
614       FT_Long  min_scaling, max_scaling;
615       int      i;
616 
617 
618       dict->has_font_matrix = TRUE;
619 
620       /* We expect a well-formed font matrix, this is, the matrix elements */
621       /* `xx' and `yy' are of approximately the same magnitude.  To avoid  */
622       /* loss of precision, we use the magnitude of the largest matrix     */
623       /* element to scale all other elements.  The scaling factor is then  */
624       /* contained in the `units_per_em' value.                            */
625 
626       max_scaling = FT_LONG_MIN;
627       min_scaling = FT_LONG_MAX;
628 
629       for ( i = 0; i < 6; i++ )
630       {
631         values[i] = cff_parse_fixed_dynamic( parser, data++, &scalings[i] );
632         if ( values[i] )
633         {
634           if ( scalings[i] > max_scaling )
635             max_scaling = scalings[i];
636           if ( scalings[i] < min_scaling )
637             min_scaling = scalings[i];
638         }
639       }
640 
641       if ( max_scaling < -9                  ||
642            max_scaling > 0                   ||
643            ( max_scaling - min_scaling ) < 0 ||
644            ( max_scaling - min_scaling ) > 9 )
645       {
646         FT_TRACE1(( "cff_parse_font_matrix:"
647                     " strange scaling values (minimum %d, maximum %d),\n"
648                     "                      "
649                     " using default matrix\n", min_scaling, max_scaling ));
650         goto Unlikely;
651       }
652 
653       for ( i = 0; i < 6; i++ )
654       {
655         FT_Fixed  value = values[i];
656         FT_Long   divisor, half_divisor;
657 
658 
659         if ( !value )
660           continue;
661 
662         divisor      = power_tens[max_scaling - scalings[i]];
663         half_divisor = divisor >> 1;
664 
665         if ( value < 0 )
666         {
667           if ( FT_LONG_MIN + half_divisor < value )
668             values[i] = ( value - half_divisor ) / divisor;
669           else
670             values[i] = FT_LONG_MIN / divisor;
671         }
672         else
673         {
674           if ( FT_LONG_MAX - half_divisor > value )
675             values[i] = ( value + half_divisor ) / divisor;
676           else
677             values[i] = FT_LONG_MAX / divisor;
678         }
679       }
680 
681       matrix->xx = values[0];
682       matrix->yx = values[1];
683       matrix->xy = values[2];
684       matrix->yy = values[3];
685       offset->x  = values[4];
686       offset->y  = values[5];
687 
688       *upm = (FT_ULong)power_tens[-max_scaling];
689 
690       FT_TRACE4(( " [%f %f %f %f %f %f]\n",
691                   (double)matrix->xx / *upm / 65536,
692                   (double)matrix->xy / *upm / 65536,
693                   (double)matrix->yx / *upm / 65536,
694                   (double)matrix->yy / *upm / 65536,
695                   (double)offset->x  / *upm / 65536,
696                   (double)offset->y  / *upm / 65536 ));
697 
698       if ( !FT_Matrix_Check( matrix ) )
699       {
700         FT_TRACE1(( "cff_parse_font_matrix:"
701                     " degenerate values, using default matrix\n" ));
702         goto Unlikely;
703       }
704 
705       return FT_Err_Ok;
706     }
707     else
708       return FT_THROW( Stack_Underflow );
709 
710   Unlikely:
711     /* Return default matrix in case of unlikely values. */
712 
713     matrix->xx = 0x10000L;
714     matrix->yx = 0;
715     matrix->xy = 0;
716     matrix->yy = 0x10000L;
717     offset->x  = 0;
718     offset->y  = 0;
719     *upm       = 1;
720 
721     return FT_Err_Ok;
722   }
723 
724 
725   static FT_Error
cff_parse_font_bbox(CFF_Parser parser)726   cff_parse_font_bbox( CFF_Parser  parser )
727   {
728     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
729     FT_BBox*         bbox = &dict->font_bbox;
730     FT_Byte**        data = parser->stack;
731     FT_Error         error;
732 
733 
734     error = FT_ERR( Stack_Underflow );
735 
736     if ( parser->top >= parser->stack + 4 )
737     {
738       bbox->xMin = FT_RoundFix( cff_parse_fixed( parser, data++ ) );
739       bbox->yMin = FT_RoundFix( cff_parse_fixed( parser, data++ ) );
740       bbox->xMax = FT_RoundFix( cff_parse_fixed( parser, data++ ) );
741       bbox->yMax = FT_RoundFix( cff_parse_fixed( parser, data   ) );
742       error = FT_Err_Ok;
743 
744       FT_TRACE4(( " [%d %d %d %d]\n",
745                   bbox->xMin / 65536,
746                   bbox->yMin / 65536,
747                   bbox->xMax / 65536,
748                   bbox->yMax / 65536 ));
749     }
750 
751     return error;
752   }
753 
754 
755   static FT_Error
cff_parse_private_dict(CFF_Parser parser)756   cff_parse_private_dict( CFF_Parser  parser )
757   {
758     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
759     FT_Byte**        data = parser->stack;
760     FT_Error         error;
761 
762 
763     error = FT_ERR( Stack_Underflow );
764 
765     if ( parser->top >= parser->stack + 2 )
766     {
767       FT_Long  tmp;
768 
769 
770       tmp = cff_parse_num( parser, data++ );
771       if ( tmp < 0 )
772       {
773         FT_ERROR(( "cff_parse_private_dict: Invalid dictionary size\n" ));
774         error = FT_THROW( Invalid_File_Format );
775         goto Fail;
776       }
777       dict->private_size = (FT_ULong)tmp;
778 
779       tmp = cff_parse_num( parser, data );
780       if ( tmp < 0 )
781       {
782         FT_ERROR(( "cff_parse_private_dict: Invalid dictionary offset\n" ));
783         error = FT_THROW( Invalid_File_Format );
784         goto Fail;
785       }
786       dict->private_offset = (FT_ULong)tmp;
787 
788       FT_TRACE4(( " %lu %lu\n",
789                   dict->private_size, dict->private_offset ));
790 
791       error = FT_Err_Ok;
792     }
793 
794   Fail:
795     return error;
796   }
797 
798 
799   /* The `MultipleMaster' operator comes before any  */
800   /* top DICT operators that contain T2 charstrings. */
801 
802   static FT_Error
cff_parse_multiple_master(CFF_Parser parser)803   cff_parse_multiple_master( CFF_Parser  parser )
804   {
805     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
806     FT_Error         error;
807 
808 
809 #ifdef FT_DEBUG_LEVEL_TRACE
810     /* beautify tracing message */
811     if ( ft_trace_levels[FT_COMPONENT] < 4 )
812       FT_TRACE1(( "Multiple Master CFFs not supported yet,"
813                   " handling first master design only\n" ));
814     else
815       FT_TRACE1(( " (not supported yet,"
816                   " handling first master design only)\n" ));
817 #endif
818 
819     error = FT_ERR( Stack_Underflow );
820 
821     /* currently, we handle only the first argument */
822     if ( parser->top >= parser->stack + 5 )
823     {
824       FT_Long  num_designs = cff_parse_num( parser, parser->stack );
825 
826 
827       if ( num_designs > 16 || num_designs < 2 )
828       {
829         FT_ERROR(( "cff_parse_multiple_master:"
830                    " Invalid number of designs\n" ));
831         error = FT_THROW( Invalid_File_Format );
832       }
833       else
834       {
835         dict->num_designs   = (FT_UShort)num_designs;
836         dict->num_axes      = (FT_UShort)( parser->top - parser->stack - 4 );
837 
838         parser->num_designs = dict->num_designs;
839         parser->num_axes    = dict->num_axes;
840 
841         error = FT_Err_Ok;
842       }
843     }
844 
845     return error;
846   }
847 
848 
849   static FT_Error
cff_parse_cid_ros(CFF_Parser parser)850   cff_parse_cid_ros( CFF_Parser  parser )
851   {
852     CFF_FontRecDict  dict = (CFF_FontRecDict)parser->object;
853     FT_Byte**        data = parser->stack;
854     FT_Error         error;
855 
856 
857     error = FT_ERR( Stack_Underflow );
858 
859     if ( parser->top >= parser->stack + 3 )
860     {
861       dict->cid_registry = (FT_UInt)cff_parse_num( parser, data++ );
862       dict->cid_ordering = (FT_UInt)cff_parse_num( parser, data++ );
863       if ( **data == 30 )
864         FT_TRACE1(( "cff_parse_cid_ros: real supplement is rounded\n" ));
865       dict->cid_supplement = cff_parse_num( parser, data );
866       if ( dict->cid_supplement < 0 )
867         FT_TRACE1(( "cff_parse_cid_ros: negative supplement %d is found\n",
868                    dict->cid_supplement ));
869       error = FT_Err_Ok;
870 
871       FT_TRACE4(( " %d %d %d\n",
872                   dict->cid_registry,
873                   dict->cid_ordering,
874                   dict->cid_supplement ));
875     }
876 
877     return error;
878   }
879 
880 
881   static FT_Error
cff_parse_vsindex(CFF_Parser parser)882   cff_parse_vsindex( CFF_Parser  parser )
883   {
884     /* vsindex operator can only be used in a Private DICT */
885     CFF_Private  priv = (CFF_Private)parser->object;
886     FT_Byte**    data = parser->stack;
887     CFF_Blend    blend;
888     FT_Error     error;
889 
890 
891     if ( !priv || !priv->subfont )
892     {
893       error = FT_THROW( Invalid_File_Format );
894       goto Exit;
895     }
896 
897     blend = &priv->subfont->blend;
898 
899     if ( blend->usedBV )
900     {
901       FT_ERROR(( " cff_parse_vsindex: vsindex not allowed after blend\n" ));
902       error = FT_THROW( Syntax_Error );
903       goto Exit;
904     }
905 
906     priv->vsindex = (FT_UInt)cff_parse_num( parser, data++ );
907 
908     FT_TRACE4(( " %d\n", priv->vsindex ));
909 
910     error = FT_Err_Ok;
911 
912   Exit:
913     return error;
914   }
915 
916 
917   static FT_Error
cff_parse_blend(CFF_Parser parser)918   cff_parse_blend( CFF_Parser  parser )
919   {
920     /* blend operator can only be used in a Private DICT */
921     CFF_Private  priv = (CFF_Private)parser->object;
922     CFF_SubFont  subFont;
923     CFF_Blend    blend;
924     FT_UInt      numBlends;
925     FT_Error     error;
926 
927 
928     if ( !priv || !priv->subfont )
929     {
930       error = FT_THROW( Invalid_File_Format );
931       goto Exit;
932     }
933 
934     subFont = priv->subfont;
935     blend   = &subFont->blend;
936 
937     if ( cff_blend_check_vector( blend,
938                                  priv->vsindex,
939                                  subFont->lenNDV,
940                                  subFont->NDV ) )
941     {
942       error = cff_blend_build_vector( blend,
943                                       priv->vsindex,
944                                       subFont->lenNDV,
945                                       subFont->NDV );
946       if ( error )
947         goto Exit;
948     }
949 
950     numBlends = (FT_UInt)cff_parse_num( parser, parser->top - 1 );
951     if ( numBlends > parser->stackSize )
952     {
953       FT_ERROR(( "cff_parse_blend: Invalid number of blends\n" ));
954       error = FT_THROW( Invalid_File_Format );
955       goto Exit;
956     }
957 
958     FT_TRACE4(( "   %d value%s blended\n",
959                 numBlends,
960                 numBlends == 1 ? "" : "s" ));
961 
962     error = cff_blend_doBlend( subFont, parser, numBlends );
963 
964     blend->usedBV = TRUE;
965 
966   Exit:
967     return error;
968   }
969 
970 
971   /* maxstack operator increases parser and operand stacks for CFF2 */
972   static FT_Error
cff_parse_maxstack(CFF_Parser parser)973   cff_parse_maxstack( CFF_Parser  parser )
974   {
975     /* maxstack operator can only be used in a Top DICT */
976     CFF_FontRecDict  dict  = (CFF_FontRecDict)parser->object;
977     FT_Byte**        data  = parser->stack;
978     FT_Error         error = FT_Err_Ok;
979 
980 
981     if ( !dict )
982     {
983       error = FT_THROW( Invalid_File_Format );
984       goto Exit;
985     }
986 
987     dict->maxstack = (FT_UInt)cff_parse_num( parser, data++ );
988     if ( dict->maxstack > CFF2_MAX_STACK )
989       dict->maxstack = CFF2_MAX_STACK;
990     if ( dict->maxstack < CFF2_DEFAULT_STACK )
991       dict->maxstack = CFF2_DEFAULT_STACK;
992 
993     FT_TRACE4(( " %d\n", dict->maxstack ));
994 
995   Exit:
996     return error;
997   }
998 
999 
1000 #define CFF_FIELD_NUM( code, name, id )             \
1001           CFF_FIELD( code, name, id, cff_kind_num )
1002 #define CFF_FIELD_FIXED( code, name, id )             \
1003           CFF_FIELD( code, name, id, cff_kind_fixed )
1004 #define CFF_FIELD_FIXED_1000( code, name, id )                 \
1005           CFF_FIELD( code, name, id, cff_kind_fixed_thousand )
1006 #define CFF_FIELD_STRING( code, name, id )             \
1007           CFF_FIELD( code, name, id, cff_kind_string )
1008 #define CFF_FIELD_BOOL( code, name, id )             \
1009           CFF_FIELD( code, name, id, cff_kind_bool )
1010 
1011 
1012 #undef  CFF_FIELD
1013 #undef  CFF_FIELD_DELTA
1014 
1015 
1016 #ifndef FT_DEBUG_LEVEL_TRACE
1017 
1018 
1019 #define CFF_FIELD_CALLBACK( code, name, id ) \
1020           {                                  \
1021             cff_kind_callback,               \
1022             code | CFFCODE,                  \
1023             0, 0,                            \
1024             cff_parse_ ## name,              \
1025             0, 0                             \
1026           },
1027 
1028 #define CFF_FIELD_BLEND( code, id ) \
1029           {                         \
1030             cff_kind_blend,         \
1031             code | CFFCODE,         \
1032             0, 0,                   \
1033             cff_parse_blend,        \
1034             0, 0                    \
1035           },
1036 
1037 #define CFF_FIELD( code, name, id, kind ) \
1038           {                               \
1039             kind,                         \
1040             code | CFFCODE,               \
1041             FT_FIELD_OFFSET( name ),      \
1042             FT_FIELD_SIZE( name ),        \
1043             0, 0, 0                       \
1044           },
1045 
1046 #define CFF_FIELD_DELTA( code, name, max, id ) \
1047           {                                    \
1048             cff_kind_delta,                    \
1049             code | CFFCODE,                    \
1050             FT_FIELD_OFFSET( name ),           \
1051             FT_FIELD_SIZE_DELTA( name ),       \
1052             0,                                 \
1053             max,                               \
1054             FT_FIELD_OFFSET( num_ ## name )    \
1055           },
1056 
1057   static const CFF_Field_Handler  cff_field_handlers[] =
1058   {
1059 
1060 #include "cfftoken.h"
1061 
1062     { 0, 0, 0, 0, 0, 0, 0 }
1063   };
1064 
1065 
1066 #else /* FT_DEBUG_LEVEL_TRACE */
1067 
1068 
1069 
1070 #define CFF_FIELD_CALLBACK( code, name, id ) \
1071           {                                  \
1072             cff_kind_callback,               \
1073             code | CFFCODE,                  \
1074             0, 0,                            \
1075             cff_parse_ ## name,              \
1076             0, 0,                            \
1077             id                               \
1078           },
1079 
1080 #define CFF_FIELD_BLEND( code, id ) \
1081           {                         \
1082             cff_kind_blend,         \
1083             code | CFFCODE,         \
1084             0, 0,                   \
1085             cff_parse_blend,        \
1086             0, 0,                   \
1087             id                      \
1088           },
1089 
1090 #define CFF_FIELD( code, name, id, kind ) \
1091           {                               \
1092             kind,                         \
1093             code | CFFCODE,               \
1094             FT_FIELD_OFFSET( name ),      \
1095             FT_FIELD_SIZE( name ),        \
1096             0, 0, 0,                      \
1097             id                            \
1098           },
1099 
1100 #define CFF_FIELD_DELTA( code, name, max, id ) \
1101           {                                    \
1102             cff_kind_delta,                    \
1103             code | CFFCODE,                    \
1104             FT_FIELD_OFFSET( name ),           \
1105             FT_FIELD_SIZE_DELTA( name ),       \
1106             0,                                 \
1107             max,                               \
1108             FT_FIELD_OFFSET( num_ ## name ),   \
1109             id                                 \
1110           },
1111 
1112   static const CFF_Field_Handler  cff_field_handlers[] =
1113   {
1114 
1115 #include "cfftoken.h"
1116 
1117     { 0, 0, 0, 0, 0, 0, 0, 0 }
1118   };
1119 
1120 
1121 #endif /* FT_DEBUG_LEVEL_TRACE */
1122 
1123 
1124   FT_LOCAL_DEF( FT_Error )
cff_parser_run(CFF_Parser parser,FT_Byte * start,FT_Byte * limit)1125   cff_parser_run( CFF_Parser  parser,
1126                   FT_Byte*    start,
1127                   FT_Byte*    limit )
1128   {
1129 #ifdef CFF_CONFIG_OPTION_OLD_ENGINE
1130     PSAux_Service  psaux;
1131 #endif
1132 
1133     FT_Byte*    p       = start;
1134     FT_Error    error   = FT_Err_Ok;
1135     FT_Library  library = parser->library;
1136 
1137     FT_UNUSED( library );
1138 
1139 
1140     parser->top    = parser->stack;
1141     parser->start  = start;
1142     parser->limit  = limit;
1143     parser->cursor = start;
1144 
1145     while ( p < limit )
1146     {
1147       FT_UInt  v = *p;
1148 
1149 
1150       /* Opcode 31 is legacy MM T2 operator, not a number.      */
1151       /* Opcode 255 is reserved and should not appear in fonts; */
1152       /* it is used internally for CFF2 blends.                 */
1153       if ( v >= 27 && v != 31 && v != 255 )
1154       {
1155         /* it's a number; we will push its position on the stack */
1156         if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize )
1157           goto Stack_Overflow;
1158 
1159         *parser->top++ = p;
1160 
1161         /* now, skip it */
1162         if ( v == 30 )
1163         {
1164           /* skip real number */
1165           p++;
1166           for (;;)
1167           {
1168             /* An unterminated floating point number at the */
1169             /* end of a dictionary is invalid but harmless. */
1170             if ( p >= limit )
1171               goto Exit;
1172             v = p[0] >> 4;
1173             if ( v == 15 )
1174               break;
1175             v = p[0] & 0xF;
1176             if ( v == 15 )
1177               break;
1178             p++;
1179           }
1180         }
1181         else if ( v == 28 )
1182           p += 2;
1183         else if ( v == 29 )
1184           p += 4;
1185         else if ( v > 246 )
1186           p += 1;
1187       }
1188 #ifdef CFF_CONFIG_OPTION_OLD_ENGINE
1189       else if ( v == 31 )
1190       {
1191         /* a Type 2 charstring */
1192 
1193         CFF_Decoder  decoder;
1194         CFF_FontRec  cff_rec;
1195         FT_Byte*     charstring_base;
1196         FT_ULong     charstring_len;
1197 
1198         FT_Fixed*  stack;
1199         FT_Byte*   q;
1200 
1201 
1202         charstring_base = ++p;
1203 
1204         /* search `endchar' operator */
1205         for (;;)
1206         {
1207           if ( p >= limit )
1208             goto Exit;
1209           if ( *p == 14 )
1210             break;
1211           p++;
1212         }
1213 
1214         charstring_len = (FT_ULong)( p - charstring_base ) + 1;
1215 
1216         /* construct CFF_Decoder object */
1217         FT_ZERO( &decoder );
1218         FT_ZERO( &cff_rec );
1219 
1220         cff_rec.top_font.font_dict.num_designs = parser->num_designs;
1221         cff_rec.top_font.font_dict.num_axes    = parser->num_axes;
1222         decoder.cff                            = &cff_rec;
1223 
1224         psaux = (PSAux_Service)FT_Get_Module_Interface( library, "psaux" );
1225         if ( !psaux )
1226         {
1227           FT_ERROR(( "cff_parser_run: cannot access `psaux' module\n" ));
1228           error = FT_THROW( Missing_Module );
1229           goto Exit;
1230         }
1231 
1232         error = psaux->cff_decoder_funcs->parse_charstrings_old(
1233                   &decoder, charstring_base, charstring_len, 1 );
1234 
1235         /* Now copy the stack data in the temporary decoder object,    */
1236         /* converting it back to charstring number representations     */
1237         /* (this is ugly, I know).                                     */
1238         /*                                                             */
1239         /* We overwrite the original top DICT charstring under the     */
1240         /* assumption that the charstring representation of the result */
1241         /* of `cff_decoder_parse_charstrings' is shorter, which should */
1242         /* be always true.                                             */
1243 
1244         q     = charstring_base - 1;
1245         stack = decoder.stack;
1246 
1247         while ( stack < decoder.top )
1248         {
1249           FT_ULong  num;
1250           FT_Bool   neg;
1251 
1252 
1253           if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize )
1254             goto Stack_Overflow;
1255 
1256           *parser->top++ = q;
1257 
1258           if ( *stack < 0 )
1259           {
1260             num = (FT_ULong)-*stack;
1261             neg = 1;
1262           }
1263           else
1264           {
1265             num = (FT_ULong)*stack;
1266             neg = 0;
1267           }
1268 
1269           if ( num & 0xFFFFU )
1270           {
1271             if ( neg )
1272               num = (FT_ULong)-num;
1273 
1274             *q++ = 255;
1275             *q++ = ( num & 0xFF000000U ) >> 24;
1276             *q++ = ( num & 0x00FF0000U ) >> 16;
1277             *q++ = ( num & 0x0000FF00U ) >>  8;
1278             *q++ =   num & 0x000000FFU;
1279           }
1280           else
1281           {
1282             num >>= 16;
1283 
1284             if ( neg )
1285             {
1286               if ( num <= 107 )
1287                 *q++ = (FT_Byte)( 139 - num );
1288               else if ( num <= 1131 )
1289               {
1290                 *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 251 );
1291                 *q++ = (FT_Byte)( ( num - 108 ) & 0xFF );
1292               }
1293               else
1294               {
1295                 num = (FT_ULong)-num;
1296 
1297                 *q++ = 28;
1298                 *q++ = (FT_Byte)( num >> 8 );
1299                 *q++ = (FT_Byte)( num & 0xFF );
1300               }
1301             }
1302             else
1303             {
1304               if ( num <= 107 )
1305                 *q++ = (FT_Byte)( num + 139 );
1306               else if ( num <= 1131 )
1307               {
1308                 *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 247 );
1309                 *q++ = (FT_Byte)( ( num - 108 ) & 0xFF );
1310               }
1311               else
1312               {
1313                 *q++ = 28;
1314                 *q++ = (FT_Byte)( num >> 8 );
1315                 *q++ = (FT_Byte)( num & 0xFF );
1316               }
1317             }
1318           }
1319 
1320           stack++;
1321         }
1322       }
1323 #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */
1324       else
1325       {
1326         /* This is not a number, hence it's an operator.  Compute its code */
1327         /* and look for it in our current list.                            */
1328 
1329         FT_UInt                   code;
1330         FT_UInt                   num_args;
1331         const CFF_Field_Handler*  field;
1332 
1333 
1334         if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize )
1335           goto Stack_Overflow;
1336 
1337         num_args     = (FT_UInt)( parser->top - parser->stack );
1338         *parser->top = p;
1339         code         = v;
1340 
1341         if ( v == 12 )
1342         {
1343           /* two byte operator */
1344           p++;
1345           if ( p >= limit )
1346             goto Syntax_Error;
1347 
1348           code = 0x100 | p[0];
1349         }
1350         code = code | parser->object_code;
1351 
1352         for ( field = cff_field_handlers; field->kind; field++ )
1353         {
1354           if ( field->code == (FT_Int)code )
1355           {
1356             /* we found our field's handler; read it */
1357             FT_Long   val;
1358             FT_Byte*  q = (FT_Byte*)parser->object + field->offset;
1359 
1360 
1361 #ifdef FT_DEBUG_LEVEL_TRACE
1362             FT_TRACE4(( "  %s", field->id ));
1363 #endif
1364 
1365             /* check that we have enough arguments -- except for */
1366             /* delta encoded arrays, which can be empty          */
1367             if ( field->kind != cff_kind_delta && num_args < 1 )
1368               goto Stack_Underflow;
1369 
1370             switch ( field->kind )
1371             {
1372             case cff_kind_bool:
1373             case cff_kind_string:
1374             case cff_kind_num:
1375               val = cff_parse_num( parser, parser->stack );
1376               goto Store_Number;
1377 
1378             case cff_kind_fixed:
1379               val = cff_parse_fixed( parser, parser->stack );
1380               goto Store_Number;
1381 
1382             case cff_kind_fixed_thousand:
1383               val = cff_parse_fixed_scaled( parser, parser->stack, 3 );
1384 
1385             Store_Number:
1386               switch ( field->size )
1387               {
1388               case (8 / FT_CHAR_BIT):
1389                 *(FT_Byte*)q = (FT_Byte)val;
1390                 break;
1391 
1392               case (16 / FT_CHAR_BIT):
1393                 *(FT_Short*)q = (FT_Short)val;
1394                 break;
1395 
1396               case (32 / FT_CHAR_BIT):
1397                 *(FT_Int32*)q = (FT_Int)val;
1398                 break;
1399 
1400               default:  /* for 64-bit systems */
1401                 *(FT_Long*)q = val;
1402               }
1403 
1404 #ifdef FT_DEBUG_LEVEL_TRACE
1405               switch ( field->kind )
1406               {
1407               case cff_kind_bool:
1408                 FT_TRACE4(( " %s\n", val ? "true" : "false" ));
1409                 break;
1410 
1411               case cff_kind_string:
1412                 FT_TRACE4(( " %ld (SID)\n", val ));
1413                 break;
1414 
1415               case cff_kind_num:
1416                 FT_TRACE4(( " %ld\n", val ));
1417                 break;
1418 
1419               case cff_kind_fixed:
1420                 FT_TRACE4(( " %f\n", (double)val / 65536 ));
1421                 break;
1422 
1423               case cff_kind_fixed_thousand:
1424                 FT_TRACE4(( " %f\n", (double)val / 65536 / 1000 ));
1425 
1426               default:
1427                 ; /* never reached */
1428               }
1429 #endif
1430 
1431               break;
1432 
1433             case cff_kind_delta:
1434               {
1435                 FT_Byte*   qcount = (FT_Byte*)parser->object +
1436                                       field->count_offset;
1437 
1438                 FT_Byte**  data = parser->stack;
1439 
1440 
1441                 if ( num_args > field->array_max )
1442                   num_args = field->array_max;
1443 
1444                 FT_TRACE4(( " [" ));
1445 
1446                 /* store count */
1447                 *qcount = (FT_Byte)num_args;
1448 
1449                 val = 0;
1450                 while ( num_args > 0 )
1451                 {
1452                   val = ADD_LONG( val, cff_parse_num( parser, data++ ) );
1453                   switch ( field->size )
1454                   {
1455                   case (8 / FT_CHAR_BIT):
1456                     *(FT_Byte*)q = (FT_Byte)val;
1457                     break;
1458 
1459                   case (16 / FT_CHAR_BIT):
1460                     *(FT_Short*)q = (FT_Short)val;
1461                     break;
1462 
1463                   case (32 / FT_CHAR_BIT):
1464                     *(FT_Int32*)q = (FT_Int)val;
1465                     break;
1466 
1467                   default:  /* for 64-bit systems */
1468                     *(FT_Long*)q = val;
1469                   }
1470 
1471                   FT_TRACE4(( " %ld", val ));
1472 
1473                   q += field->size;
1474                   num_args--;
1475                 }
1476 
1477                 FT_TRACE4(( "]\n" ));
1478               }
1479               break;
1480 
1481             default:  /* callback or blend */
1482               error = field->reader( parser );
1483               if ( error )
1484                 goto Exit;
1485             }
1486             goto Found;
1487           }
1488         }
1489 
1490         /* this is an unknown operator, or it is unsupported; */
1491         /* we will ignore it for now.                         */
1492 
1493       Found:
1494         /* clear stack */
1495         /* TODO: could clear blend stack here,       */
1496         /*       but we don't have access to subFont */
1497         if ( field->kind != cff_kind_blend )
1498           parser->top = parser->stack;
1499       }
1500       p++;
1501     }
1502 
1503   Exit:
1504     return error;
1505 
1506   Stack_Overflow:
1507     error = FT_THROW( Invalid_Argument );
1508     goto Exit;
1509 
1510   Stack_Underflow:
1511     error = FT_THROW( Invalid_Argument );
1512     goto Exit;
1513 
1514   Syntax_Error:
1515     error = FT_THROW( Invalid_Argument );
1516     goto Exit;
1517   }
1518 
1519 
1520 /* END */
1521