1 /***************************************************************************/
2 /*                                                                         */
3 /*  cidload.c                                                              */
4 /*                                                                         */
5 /*    CID-keyed Type1 font loader (body).                                  */
6 /*                                                                         */
7 /*  Copyright 1996-2006, 2009, 2011-2014 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 FT_INTERNAL_DEBUG_H
21 #include FT_CONFIG_CONFIG_H
22 #include FT_MULTIPLE_MASTERS_H
23 #include FT_INTERNAL_TYPE1_TYPES_H
24 
25 #include "cidload.h"
26 
27 #include "ciderrs.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_cidload
38 
39 
40   /* read a single offset */
41   FT_LOCAL_DEF( FT_Long )
cid_get_offset(FT_Byte ** start,FT_Byte offsize)42   cid_get_offset( FT_Byte*  *start,
43                   FT_Byte    offsize )
44   {
45     FT_ULong  result;
46     FT_Byte*  p = *start;
47 
48 
49     for ( result = 0; offsize > 0; offsize-- )
50     {
51       result <<= 8;
52       result  |= *p++;
53     }
54 
55     *start = p;
56     return (FT_Long)result;
57   }
58 
59 
60   /*************************************************************************/
61   /*************************************************************************/
62   /*****                                                               *****/
63   /*****                    TYPE 1 SYMBOL PARSING                      *****/
64   /*****                                                               *****/
65   /*************************************************************************/
66   /*************************************************************************/
67 
68 
69   static FT_Error
cid_load_keyword(CID_Face face,CID_Loader * loader,const T1_Field keyword)70   cid_load_keyword( CID_Face        face,
71                     CID_Loader*     loader,
72                     const T1_Field  keyword )
73   {
74     FT_Error      error;
75     CID_Parser*   parser = &loader->parser;
76     FT_Byte*      object;
77     void*         dummy_object;
78     CID_FaceInfo  cid = &face->cid;
79 
80 
81     /* if the keyword has a dedicated callback, call it */
82     if ( keyword->type == T1_FIELD_TYPE_CALLBACK )
83     {
84       keyword->reader( (FT_Face)face, parser );
85       error = parser->root.error;
86       goto Exit;
87     }
88 
89     /* we must now compute the address of our target object */
90     switch ( keyword->location )
91     {
92     case T1_FIELD_LOCATION_CID_INFO:
93       object = (FT_Byte*)cid;
94       break;
95 
96     case T1_FIELD_LOCATION_FONT_INFO:
97       object = (FT_Byte*)&cid->font_info;
98       break;
99 
100     case T1_FIELD_LOCATION_FONT_EXTRA:
101       object = (FT_Byte*)&face->font_extra;
102       break;
103 
104     case T1_FIELD_LOCATION_BBOX:
105       object = (FT_Byte*)&cid->font_bbox;
106       break;
107 
108     default:
109       {
110         CID_FaceDict  dict;
111 
112 
113         if ( parser->num_dict < 0 || parser->num_dict >= cid->num_dicts )
114         {
115           FT_ERROR(( "cid_load_keyword: invalid use of `%s'\n",
116                      keyword->ident ));
117           error = FT_THROW( Syntax_Error );
118           goto Exit;
119         }
120 
121         dict = cid->font_dicts + parser->num_dict;
122         switch ( keyword->location )
123         {
124         case T1_FIELD_LOCATION_PRIVATE:
125           object = (FT_Byte*)&dict->private_dict;
126           break;
127 
128         default:
129           object = (FT_Byte*)dict;
130         }
131       }
132     }
133 
134     dummy_object = object;
135 
136     /* now, load the keyword data in the object's field(s) */
137     if ( keyword->type == T1_FIELD_TYPE_INTEGER_ARRAY ||
138          keyword->type == T1_FIELD_TYPE_FIXED_ARRAY   )
139       error = cid_parser_load_field_table( &loader->parser, keyword,
140                                            &dummy_object );
141     else
142       error = cid_parser_load_field( &loader->parser,
143                                      keyword, &dummy_object );
144   Exit:
145     return error;
146   }
147 
148 
149   FT_CALLBACK_DEF( FT_Error )
cid_parse_font_matrix(CID_Face face,CID_Parser * parser)150   cid_parse_font_matrix( CID_Face     face,
151                          CID_Parser*  parser )
152   {
153     CID_FaceDict  dict;
154     FT_Face       root = (FT_Face)&face->root;
155     FT_Fixed      temp[6];
156     FT_Fixed      temp_scale;
157 
158 
159     if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
160     {
161       FT_Matrix*  matrix;
162       FT_Vector*  offset;
163       FT_Int      result;
164 
165 
166       dict   = face->cid.font_dicts + parser->num_dict;
167       matrix = &dict->font_matrix;
168       offset = &dict->font_offset;
169 
170       result = cid_parser_to_fixed_array( parser, 6, temp, 3 );
171 
172       if ( result < 6 )
173         return FT_THROW( Invalid_File_Format );
174 
175       temp_scale = FT_ABS( temp[3] );
176 
177       if ( temp_scale == 0 )
178       {
179         FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" ));
180         return FT_THROW( Invalid_File_Format );
181       }
182 
183       /* Set Units per EM based on FontMatrix values.  We set the value to */
184       /* 1000 / temp_scale, because temp_scale was already multiplied by   */
185       /* 1000 (in t1_tofixed, from psobjs.c).                              */
186 
187       root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
188 
189       /* we need to scale the values by 1.0/temp[3] */
190       if ( temp_scale != 0x10000L )
191       {
192         temp[0] = FT_DivFix( temp[0], temp_scale );
193         temp[1] = FT_DivFix( temp[1], temp_scale );
194         temp[2] = FT_DivFix( temp[2], temp_scale );
195         temp[4] = FT_DivFix( temp[4], temp_scale );
196         temp[5] = FT_DivFix( temp[5], temp_scale );
197         temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
198       }
199 
200       matrix->xx = temp[0];
201       matrix->yx = temp[1];
202       matrix->xy = temp[2];
203       matrix->yy = temp[3];
204 
205       /* note that the font offsets are expressed in integer font units */
206       offset->x  = temp[4] >> 16;
207       offset->y  = temp[5] >> 16;
208     }
209 
210     return FT_Err_Ok;
211   }
212 
213 
214   FT_CALLBACK_DEF( FT_Error )
parse_fd_array(CID_Face face,CID_Parser * parser)215   parse_fd_array( CID_Face     face,
216                   CID_Parser*  parser )
217   {
218     CID_FaceInfo  cid    = &face->cid;
219     FT_Memory     memory = face->root.memory;
220     FT_Error      error  = FT_Err_Ok;
221     FT_Long       num_dicts;
222 
223 
224     num_dicts = cid_parser_to_int( parser );
225 
226     if ( !cid->font_dicts )
227     {
228       FT_Int  n;
229 
230 
231       if ( FT_NEW_ARRAY( cid->font_dicts, num_dicts ) )
232         goto Exit;
233 
234       cid->num_dicts = (FT_UInt)num_dicts;
235 
236       /* don't forget to set a few defaults */
237       for ( n = 0; n < cid->num_dicts; n++ )
238       {
239         CID_FaceDict  dict = cid->font_dicts + n;
240 
241 
242         /* default value for lenIV */
243         dict->private_dict.lenIV = 4;
244       }
245     }
246 
247   Exit:
248     return error;
249   }
250 
251 
252   /* by mistake, `expansion_factor' appears both in PS_PrivateRec */
253   /* and CID_FaceDictRec (both are public header files and can't  */
254   /* changed); we simply copy the value                           */
255 
256   FT_CALLBACK_DEF( FT_Error )
parse_expansion_factor(CID_Face face,CID_Parser * parser)257   parse_expansion_factor( CID_Face     face,
258                           CID_Parser*  parser )
259   {
260     CID_FaceDict  dict;
261 
262 
263     if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
264     {
265       dict = face->cid.font_dicts + parser->num_dict;
266 
267       dict->expansion_factor              = cid_parser_to_fixed( parser, 0 );
268       dict->private_dict.expansion_factor = dict->expansion_factor;
269     }
270 
271     return FT_Err_Ok;
272   }
273 
274 
275   static
276   const T1_FieldRec  cid_field_records[] =
277   {
278 
279 #include "cidtoken.h"
280 
281     T1_FIELD_CALLBACK( "FDArray",         parse_fd_array, 0 )
282     T1_FIELD_CALLBACK( "FontMatrix",      cid_parse_font_matrix, 0 )
283     T1_FIELD_CALLBACK( "ExpansionFactor", parse_expansion_factor, 0 )
284 
285     { 0, T1_FIELD_LOCATION_CID_INFO, T1_FIELD_TYPE_NONE, 0, 0, 0, 0, 0, 0 }
286   };
287 
288 
289   static FT_Error
cid_parse_dict(CID_Face face,CID_Loader * loader,FT_Byte * base,FT_Long size)290   cid_parse_dict( CID_Face     face,
291                   CID_Loader*  loader,
292                   FT_Byte*     base,
293                   FT_Long      size )
294   {
295     CID_Parser*  parser = &loader->parser;
296 
297 
298     parser->root.cursor = base;
299     parser->root.limit  = base + size;
300     parser->root.error  = FT_Err_Ok;
301 
302     {
303       FT_Byte*  cur   = base;
304       FT_Byte*  limit = cur + size;
305 
306 
307       for (;;)
308       {
309         FT_Byte*  newlimit;
310 
311 
312         parser->root.cursor = cur;
313         cid_parser_skip_spaces( parser );
314 
315         if ( parser->root.cursor >= limit )
316           newlimit = limit - 1 - 17;
317         else
318           newlimit = parser->root.cursor - 17;
319 
320         /* look for `%ADOBeginFontDict' */
321         for ( ; cur < newlimit; cur++ )
322         {
323           if ( *cur == '%'                                            &&
324                ft_strncmp( (char*)cur, "%ADOBeginFontDict", 17 ) == 0 )
325           {
326             /* if /FDArray was found, then cid->num_dicts is > 0, and */
327             /* we can start increasing parser->num_dict               */
328             if ( face->cid.num_dicts > 0 )
329               parser->num_dict++;
330           }
331         }
332 
333         cur = parser->root.cursor;
334         /* no error can occur in cid_parser_skip_spaces */
335         if ( cur >= limit )
336           break;
337 
338         cid_parser_skip_PS_token( parser );
339         if ( parser->root.cursor >= limit || parser->root.error )
340           break;
341 
342         /* look for immediates */
343         if ( *cur == '/' && cur + 2 < limit )
344         {
345           FT_PtrDist  len;
346 
347 
348           cur++;
349           len = parser->root.cursor - cur;
350 
351           if ( len > 0 && len < 22 )
352           {
353             /* now compare the immediate name to the keyword table */
354             T1_Field  keyword = (T1_Field)cid_field_records;
355 
356 
357             for (;;)
358             {
359               FT_Byte*  name;
360 
361 
362               name = (FT_Byte*)keyword->ident;
363               if ( !name )
364                 break;
365 
366               if ( cur[0] == name[0]                                 &&
367                    len == (FT_PtrDist)ft_strlen( (const char*)name ) )
368               {
369                 FT_PtrDist  n;
370 
371 
372                 for ( n = 1; n < len; n++ )
373                   if ( cur[n] != name[n] )
374                     break;
375 
376                 if ( n >= len )
377                 {
378                   /* we found it - run the parsing callback */
379                   parser->root.error = cid_load_keyword( face,
380                                                          loader,
381                                                          keyword );
382                   if ( parser->root.error )
383                     return parser->root.error;
384                   break;
385                 }
386               }
387               keyword++;
388             }
389           }
390         }
391 
392         cur = parser->root.cursor;
393       }
394     }
395     return parser->root.error;
396   }
397 
398 
399   /* read the subrmap and the subrs of each font dict */
400   static FT_Error
cid_read_subrs(CID_Face face)401   cid_read_subrs( CID_Face  face )
402   {
403     CID_FaceInfo   cid    = &face->cid;
404     FT_Memory      memory = face->root.memory;
405     FT_Stream      stream = face->cid_stream;
406     FT_Error       error;
407     FT_Int         n;
408     CID_Subrs      subr;
409     FT_UInt        max_offsets = 0;
410     FT_ULong*      offsets = 0;
411     PSAux_Service  psaux = (PSAux_Service)face->psaux;
412 
413 
414     if ( FT_NEW_ARRAY( face->subrs, cid->num_dicts ) )
415       goto Exit;
416 
417     subr = face->subrs;
418     for ( n = 0; n < cid->num_dicts; n++, subr++ )
419     {
420       CID_FaceDict  dict  = cid->font_dicts + n;
421       FT_Int        lenIV = dict->private_dict.lenIV;
422       FT_UInt       count, num_subrs = dict->num_subrs;
423       FT_ULong      data_len;
424       FT_Byte*      p;
425 
426 
427       /* Check for possible overflow. */
428       if ( num_subrs == FT_UINT_MAX )
429       {
430         error = FT_THROW( Syntax_Error );
431         goto Fail;
432       }
433 
434       /* reallocate offsets array if needed */
435       if ( num_subrs + 1 > max_offsets )
436       {
437         FT_UInt  new_max = FT_PAD_CEIL( num_subrs + 1, 4 );
438 
439 
440         if ( new_max <= max_offsets )
441         {
442           error = FT_THROW( Syntax_Error );
443           goto Fail;
444         }
445 
446         if ( FT_RENEW_ARRAY( offsets, max_offsets, new_max ) )
447           goto Fail;
448 
449         max_offsets = new_max;
450       }
451 
452       /* read the subrmap's offsets */
453       if ( FT_STREAM_SEEK( cid->data_offset + dict->subrmap_offset ) ||
454            FT_FRAME_ENTER( ( num_subrs + 1 ) * dict->sd_bytes )      )
455         goto Fail;
456 
457       p = (FT_Byte*)stream->cursor;
458       for ( count = 0; count <= num_subrs; count++ )
459         offsets[count] = cid_get_offset( &p, (FT_Byte)dict->sd_bytes );
460 
461       FT_FRAME_EXIT();
462 
463       /* offsets must be ordered */
464       for ( count = 1; count <= num_subrs; count++ )
465         if ( offsets[count - 1] > offsets[count] )
466           goto Fail;
467 
468       /* now, compute the size of subrs charstrings, */
469       /* allocate, and read them                     */
470       data_len = offsets[num_subrs] - offsets[0];
471 
472       if ( FT_NEW_ARRAY( subr->code, num_subrs + 1 ) ||
473                FT_ALLOC( subr->code[0], data_len )   )
474         goto Fail;
475 
476       if ( FT_STREAM_SEEK( cid->data_offset + offsets[0] ) ||
477            FT_STREAM_READ( subr->code[0], data_len )  )
478         goto Fail;
479 
480       /* set up pointers */
481       for ( count = 1; count <= num_subrs; count++ )
482       {
483         FT_ULong  len;
484 
485 
486         len               = offsets[count] - offsets[count - 1];
487         subr->code[count] = subr->code[count - 1] + len;
488       }
489 
490       /* decrypt subroutines, but only if lenIV >= 0 */
491       if ( lenIV >= 0 )
492       {
493         for ( count = 0; count < num_subrs; count++ )
494         {
495           FT_ULong  len;
496 
497 
498           len = offsets[count + 1] - offsets[count];
499           psaux->t1_decrypt( subr->code[count], len, 4330 );
500         }
501       }
502 
503       subr->num_subrs = num_subrs;
504     }
505 
506   Exit:
507     FT_FREE( offsets );
508     return error;
509 
510   Fail:
511     if ( face->subrs )
512     {
513       for ( n = 0; n < cid->num_dicts; n++ )
514       {
515         if ( face->subrs[n].code )
516           FT_FREE( face->subrs[n].code[0] );
517 
518         FT_FREE( face->subrs[n].code );
519       }
520       FT_FREE( face->subrs );
521     }
522     goto Exit;
523   }
524 
525 
526   static void
cid_init_loader(CID_Loader * loader,CID_Face face)527   cid_init_loader( CID_Loader*  loader,
528                    CID_Face     face )
529   {
530     FT_UNUSED( face );
531 
532     FT_MEM_ZERO( loader, sizeof ( *loader ) );
533   }
534 
535 
536   static  void
cid_done_loader(CID_Loader * loader)537   cid_done_loader( CID_Loader*  loader )
538   {
539     CID_Parser*  parser = &loader->parser;
540 
541 
542     /* finalize parser */
543     cid_parser_done( parser );
544   }
545 
546 
547   static FT_Error
cid_hex_to_binary(FT_Byte * data,FT_Long data_len,FT_ULong offset,CID_Face face)548   cid_hex_to_binary( FT_Byte*  data,
549                      FT_Long   data_len,
550                      FT_ULong  offset,
551                      CID_Face  face )
552   {
553     FT_Stream  stream = face->root.stream;
554     FT_Error   error;
555 
556     FT_Byte    buffer[256];
557     FT_Byte   *p, *plimit;
558     FT_Byte   *d, *dlimit;
559     FT_Byte    val;
560 
561     FT_Bool    upper_nibble, done;
562 
563 
564     if ( FT_STREAM_SEEK( offset ) )
565       goto Exit;
566 
567     d      = data;
568     dlimit = d + data_len;
569     p      = buffer;
570     plimit = p;
571 
572     upper_nibble = 1;
573     done         = 0;
574 
575     while ( d < dlimit )
576     {
577       if ( p >= plimit )
578       {
579         FT_ULong  oldpos = FT_STREAM_POS();
580         FT_ULong  size   = stream->size - oldpos;
581 
582 
583         if ( size == 0 )
584         {
585           error = FT_THROW( Syntax_Error );
586           goto Exit;
587         }
588 
589         if ( FT_STREAM_READ( buffer, 256 > size ? size : 256 ) )
590           goto Exit;
591         p      = buffer;
592         plimit = p + FT_STREAM_POS() - oldpos;
593       }
594 
595       if ( ft_isdigit( *p ) )
596         val = (FT_Byte)( *p - '0' );
597       else if ( *p >= 'a' && *p <= 'f' )
598         val = (FT_Byte)( *p - 'a' );
599       else if ( *p >= 'A' && *p <= 'F' )
600         val = (FT_Byte)( *p - 'A' + 10 );
601       else if ( *p == ' '  ||
602                 *p == '\t' ||
603                 *p == '\r' ||
604                 *p == '\n' ||
605                 *p == '\f' ||
606                 *p == '\0' )
607       {
608         p++;
609         continue;
610       }
611       else if ( *p == '>' )
612       {
613         val  = 0;
614         done = 1;
615       }
616       else
617       {
618         error = FT_THROW( Syntax_Error );
619         goto Exit;
620       }
621 
622       if ( upper_nibble )
623         *d = (FT_Byte)( val << 4 );
624       else
625       {
626         *d = (FT_Byte)( *d + val );
627         d++;
628       }
629 
630       upper_nibble = (FT_Byte)( 1 - upper_nibble );
631 
632       if ( done )
633         break;
634 
635       p++;
636     }
637 
638     error = FT_Err_Ok;
639 
640   Exit:
641     return error;
642   }
643 
644 
645   FT_LOCAL_DEF( FT_Error )
cid_face_open(CID_Face face,FT_Int face_index)646   cid_face_open( CID_Face  face,
647                  FT_Int    face_index )
648   {
649     CID_Loader   loader;
650     CID_Parser*  parser;
651     FT_Memory    memory = face->root.memory;
652     FT_Error     error;
653 
654 
655     cid_init_loader( &loader, face );
656 
657     parser = &loader.parser;
658     error = cid_parser_new( parser, face->root.stream, face->root.memory,
659                             (PSAux_Service)face->psaux );
660     if ( error )
661       goto Exit;
662 
663     error = cid_parse_dict( face, &loader,
664                             parser->postscript,
665                             parser->postscript_len );
666     if ( error )
667       goto Exit;
668 
669     if ( face_index < 0 )
670       goto Exit;
671 
672     if ( FT_NEW( face->cid_stream ) )
673       goto Exit;
674 
675     if ( parser->binary_length )
676     {
677       /* we must convert the data section from hexadecimal to binary */
678       if ( FT_ALLOC( face->binary_data, parser->binary_length )         ||
679            cid_hex_to_binary( face->binary_data, parser->binary_length,
680                               parser->data_offset, face )               )
681         goto Exit;
682 
683       FT_Stream_OpenMemory( face->cid_stream,
684                             face->binary_data, parser->binary_length );
685       face->cid.data_offset = 0;
686     }
687     else
688     {
689       *face->cid_stream     = *face->root.stream;
690       face->cid.data_offset = loader.parser.data_offset;
691     }
692 
693     error = cid_read_subrs( face );
694 
695   Exit:
696     cid_done_loader( &loader );
697     return error;
698   }
699 
700 
701 /* END */
702