Imported Upstream version 3.4.0
[platform/upstream/harfbuzz.git] / src / hb-ot-cff-common.hh
1 /*
2  * Copyright © 2018 Adobe Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Adobe Author(s): Michiharu Ariza
25  */
26 #ifndef HB_OT_CFF_COMMON_HH
27 #define HB_OT_CFF_COMMON_HH
28
29 #include "hb-open-type.hh"
30 #include "hb-bimap.hh"
31 #include "hb-ot-layout-common.hh"
32 #include "hb-cff-interp-dict-common.hh"
33 #include "hb-subset-plan.hh"
34
35 namespace CFF {
36
37 using namespace OT;
38
39 #define CFF_UNDEF_CODE  0xFFFFFFFF
40
41 using objidx_t = hb_serialize_context_t::objidx_t;
42 using whence_t = hb_serialize_context_t::whence_t;
43
44 /* utility macro */
45 template<typename Type>
46 static inline const Type& StructAtOffsetOrNull (const void *P, unsigned int offset)
47 { return offset ? StructAtOffset<Type> (P, offset) : Null (Type); }
48
49 inline unsigned int calcOffSize (unsigned int dataSize)
50 {
51   unsigned int size = 1;
52   unsigned int offset = dataSize + 1;
53   while (offset & ~0xFF)
54   {
55     size++;
56     offset >>= 8;
57   }
58   /* format does not support size > 4; caller should handle it as an error */
59   return size;
60 }
61
62 struct code_pair_t
63 {
64   hb_codepoint_t code;
65   hb_codepoint_t glyph;
66 };
67
68 typedef hb_vector_t<unsigned char> str_buff_t;
69 struct str_buff_vec_t : hb_vector_t<str_buff_t>
70 {
71   unsigned int total_size () const
72   {
73     unsigned int size = 0;
74     for (unsigned int i = 0; i < length; i++)
75       size += (*this)[i].length;
76     return size;
77   }
78
79   private:
80   typedef hb_vector_t<str_buff_t> SUPER;
81 };
82
83 /* CFF INDEX */
84 template <typename COUNT>
85 struct CFFIndex
86 {
87   static unsigned int calculate_offset_array_size (unsigned int offSize, unsigned int count)
88   { return offSize * (count + 1); }
89
90   unsigned int offset_array_size () const
91   { return calculate_offset_array_size (offSize, count); }
92
93   CFFIndex *copy (hb_serialize_context_t *c) const
94   {
95     TRACE_SERIALIZE (this);
96     unsigned int size = get_size ();
97     CFFIndex *out = c->allocate_size<CFFIndex> (size);
98     if (likely (out))
99       memcpy (out, this, size);
100     return_trace (out);
101   }
102
103   bool serialize (hb_serialize_context_t *c, const CFFIndex &src)
104   {
105     TRACE_SERIALIZE (this);
106     unsigned int size = src.get_size ();
107     CFFIndex *dest = c->allocate_size<CFFIndex> (size);
108     if (unlikely (!dest)) return_trace (false);
109     memcpy (dest, &src, size);
110     return_trace (true);
111   }
112
113   bool serialize (hb_serialize_context_t *c,
114                   unsigned int offSize_,
115                   const byte_str_array_t &byteArray)
116   {
117     TRACE_SERIALIZE (this);
118     if (byteArray.length == 0)
119     {
120       COUNT *dest = c->allocate_min<COUNT> ();
121       if (unlikely (!dest)) return_trace (false);
122       *dest = 0;
123     }
124     else
125     {
126       /* serialize CFFIndex header */
127       if (unlikely (!c->extend_min (this))) return_trace (false);
128       this->count = byteArray.length;
129       this->offSize = offSize_;
130       if (unlikely (!c->allocate_size<HBUINT8> (offSize_ * (byteArray.length + 1))))
131         return_trace (false);
132
133       /* serialize indices */
134       unsigned int  offset = 1;
135       unsigned int  i = 0;
136       for (; i < byteArray.length; i++)
137       {
138         set_offset_at (i, offset);
139         offset += byteArray[i].get_size ();
140       }
141       set_offset_at (i, offset);
142
143       /* serialize data */
144       for (unsigned int i = 0; i < byteArray.length; i++)
145       {
146         const byte_str_t &bs = byteArray[i];
147         unsigned char *dest = c->allocate_size<unsigned char> (bs.length);
148         if (unlikely (!dest)) return_trace (false);
149         memcpy (dest, &bs[0], bs.length);
150       }
151     }
152     return_trace (true);
153   }
154
155   bool serialize (hb_serialize_context_t *c,
156                   unsigned int offSize_,
157                   const str_buff_vec_t &buffArray)
158   {
159     byte_str_array_t  byteArray;
160     byteArray.init ();
161     byteArray.resize (buffArray.length);
162     for (unsigned int i = 0; i < byteArray.length; i++)
163       byteArray[i] = byte_str_t (buffArray[i].arrayZ, buffArray[i].length);
164     bool result = this->serialize (c, offSize_, byteArray);
165     byteArray.fini ();
166     return result;
167   }
168
169   template <typename Iterator,
170             hb_requires (hb_is_iterator (Iterator))>
171   bool serialize (hb_serialize_context_t *c,
172                   Iterator it)
173   {
174     TRACE_SERIALIZE (this);
175     if (it.len () == 0)
176     {
177       COUNT *dest = c->allocate_min<COUNT> ();
178       if (unlikely (!dest)) return_trace (false);
179       *dest = 0;
180     }
181     else
182     {
183       serialize_header(c, + it | hb_map ([] (const byte_str_t &_) { return _.length; }));
184       for (const auto &_ : +it)
185         _.copy (c);
186     }
187     return_trace (true);
188   }
189
190   bool serialize (hb_serialize_context_t *c,
191                   const byte_str_array_t &byteArray)
192   { return serialize (c, + hb_iter (byteArray)); }
193
194   bool serialize (hb_serialize_context_t *c,
195                   const str_buff_vec_t &buffArray)
196   {
197     auto it =
198     + hb_iter (buffArray)
199     | hb_map ([] (const str_buff_t &_) { return byte_str_t (_.arrayZ, _.length); })
200     ;
201     return serialize (c, it);
202   }
203
204   template <typename Iterator,
205             hb_requires (hb_is_iterator (Iterator))>
206   bool serialize_header (hb_serialize_context_t *c,
207                         Iterator it)
208   {
209     TRACE_SERIALIZE (this);
210
211     unsigned total = + it | hb_reduce (hb_add, 0);
212     unsigned off_size = calcOffSize (total);
213
214     /* serialize CFFIndex header */
215     if (unlikely (!c->extend_min (this))) return_trace (false);
216     this->count = it.len ();
217     this->offSize = off_size;
218     if (unlikely (!c->allocate_size<HBUINT8> (off_size * (it.len () + 1))))
219       return_trace (false);
220
221     /* serialize indices */
222     unsigned int offset = 1;
223     unsigned int i = 0;
224     for (unsigned _ : +it)
225     {
226       CFFIndex<COUNT>::set_offset_at (i++, offset);
227       offset += _;
228     }
229     CFFIndex<COUNT>::set_offset_at (i, offset);
230
231     return_trace (true);
232   }
233
234   void set_offset_at (unsigned int index, unsigned int offset)
235   {
236     HBUINT8 *p = offsets + offSize * index + offSize;
237     unsigned int size = offSize;
238     for (; size; size--)
239     {
240       --p;
241       *p = offset & 0xFF;
242       offset >>= 8;
243     }
244   }
245
246   unsigned int offset_at (unsigned int index) const
247   {
248     assert (index <= count);
249     const HBUINT8 *p = offsets + offSize * index;
250     unsigned int size = offSize;
251     unsigned int offset = 0;
252     for (; size; size--)
253       offset = (offset << 8) + *p++;
254     return offset;
255   }
256
257   unsigned int length_at (unsigned int index) const
258   {
259     if (unlikely ((offset_at (index + 1) < offset_at (index)) ||
260                   (offset_at (index + 1) > offset_at (count))))
261       return 0;
262     return offset_at (index + 1) - offset_at (index);
263   }
264
265   const unsigned char *data_base () const
266   { return (const unsigned char *) this + min_size + offset_array_size (); }
267
268   unsigned int data_size () const { return HBINT8::static_size; }
269
270   byte_str_t operator [] (unsigned int index) const
271   {
272     if (unlikely (index >= count)) return Null (byte_str_t);
273     return byte_str_t (data_base () + offset_at (index) - 1, length_at (index));
274   }
275
276   unsigned int get_size () const
277   {
278     if (this == &Null (CFFIndex)) return 0;
279     if (count > 0)
280       return min_size + offset_array_size () + (offset_at (count) - 1);
281     return count.static_size;  /* empty CFFIndex contains count only */
282   }
283
284   bool sanitize (hb_sanitize_context_t *c) const
285   {
286     TRACE_SANITIZE (this);
287     return_trace (likely ((c->check_struct (this) && count == 0) || /* empty INDEX */
288                           (c->check_struct (this) && offSize >= 1 && offSize <= 4 &&
289                            c->check_array (offsets, offSize, count + 1) &&
290                            c->check_array ((const HBUINT8*) data_base (), 1, max_offset () - 1))));
291   }
292
293   protected:
294   unsigned int max_offset () const
295   {
296     unsigned int max = 0;
297     for (unsigned int i = 0; i < count + 1u; i++)
298     {
299       unsigned int off = offset_at (i);
300       if (off > max) max = off;
301     }
302     return max;
303   }
304
305   public:
306   COUNT         count;          /* Number of object data. Note there are (count+1) offsets */
307   HBUINT8       offSize;        /* The byte size of each offset in the offsets array. */
308   HBUINT8       offsets[HB_VAR_ARRAY];
309                                 /* The array of (count + 1) offsets into objects array (1-base). */
310   /* HBUINT8 data[HB_VAR_ARRAY];        Object data */
311   public:
312   DEFINE_SIZE_ARRAY (COUNT::static_size + HBUINT8::static_size, offsets);
313 };
314
315 template <typename COUNT, typename TYPE>
316 struct CFFIndexOf : CFFIndex<COUNT>
317 {
318   const byte_str_t operator [] (unsigned int index) const
319   {
320     if (likely (index < CFFIndex<COUNT>::count))
321       return byte_str_t (CFFIndex<COUNT>::data_base () + CFFIndex<COUNT>::offset_at (index) - 1, CFFIndex<COUNT>::length_at (index));
322     return Null (byte_str_t);
323   }
324
325   template <typename DATA, typename PARAM1, typename PARAM2>
326   bool serialize (hb_serialize_context_t *c,
327                   unsigned int offSize_,
328                   const DATA *dataArray,
329                   unsigned int dataArrayLen,
330                   const hb_vector_t<unsigned int> &dataSizeArray,
331                   const PARAM1 &param1,
332                   const PARAM2 &param2)
333   {
334     TRACE_SERIALIZE (this);
335     /* serialize CFFIndex header */
336     if (unlikely (!c->extend_min (this))) return_trace (false);
337     this->count = dataArrayLen;
338     this->offSize = offSize_;
339     if (unlikely (!c->allocate_size<HBUINT8> (offSize_ * (dataArrayLen + 1))))
340       return_trace (false);
341
342     /* serialize indices */
343     unsigned int  offset = 1;
344     unsigned int  i = 0;
345     for (; i < dataArrayLen; i++)
346     {
347       CFFIndex<COUNT>::set_offset_at (i, offset);
348       offset += dataSizeArray[i];
349     }
350     CFFIndex<COUNT>::set_offset_at (i, offset);
351
352     /* serialize data */
353     for (unsigned int i = 0; i < dataArrayLen; i++)
354     {
355       TYPE *dest = c->start_embed<TYPE> ();
356       if (unlikely (!dest || !dest->serialize (c, dataArray[i], param1, param2)))
357         return_trace (false);
358     }
359     return_trace (true);
360   }
361 };
362
363 /* Top Dict, Font Dict, Private Dict */
364 struct Dict : UnsizedByteStr
365 {
366   template <typename DICTVAL, typename OP_SERIALIZER, typename ...Ts>
367   bool serialize (hb_serialize_context_t *c,
368                   const DICTVAL &dictval,
369                   OP_SERIALIZER& opszr,
370                   Ts&&... ds)
371   {
372     TRACE_SERIALIZE (this);
373     for (unsigned int i = 0; i < dictval.get_count (); i++)
374       if (unlikely (!opszr.serialize (c, dictval[i], std::forward<Ts> (ds)...)))
375         return_trace (false);
376
377     return_trace (true);
378   }
379
380   template <typename T, typename V>
381   static bool serialize_int_op (hb_serialize_context_t *c, op_code_t op, V value, op_code_t intOp)
382   {
383     // XXX: not sure why but LLVM fails to compile the following 'unlikely' macro invocation
384     if (/*unlikely*/ (!serialize_int<T, V> (c, intOp, value)))
385       return false;
386
387     TRACE_SERIALIZE (this);
388     /* serialize the opcode */
389     HBUINT8 *p = c->allocate_size<HBUINT8> (OpCode_Size (op));
390     if (unlikely (!p)) return_trace (false);
391     if (Is_OpCode_ESC (op))
392     {
393       *p = OpCode_escape;
394       op = Unmake_OpCode_ESC (op);
395       p++;
396     }
397     *p = op;
398     return_trace (true);
399   }
400
401   template <typename V>
402   static bool serialize_int4_op (hb_serialize_context_t *c, op_code_t op, V value)
403   { return serialize_int_op<HBINT32> (c, op, value, OpCode_longintdict); }
404
405   template <typename V>
406   static bool serialize_int2_op (hb_serialize_context_t *c, op_code_t op, V value)
407   { return serialize_int_op<HBINT16> (c, op, value, OpCode_shortint); }
408
409   template <typename T, int int_op>
410   static bool serialize_link_op (hb_serialize_context_t *c, op_code_t op, objidx_t link, whence_t whence)
411   {
412     T &ofs = *(T *) (c->head + OpCode_Size (int_op));
413     if (unlikely (!serialize_int_op<T> (c, op, 0, int_op))) return false;
414     c->add_link (ofs, link, whence);
415     return true;
416   }
417
418   static bool serialize_link4_op (hb_serialize_context_t *c, op_code_t op, objidx_t link, whence_t whence = whence_t::Head)
419   { return serialize_link_op<HBINT32, OpCode_longintdict> (c, op, link, whence); }
420
421   static bool serialize_link2_op (hb_serialize_context_t *c, op_code_t op, objidx_t link, whence_t whence = whence_t::Head)
422   { return serialize_link_op<HBINT16, OpCode_shortint> (c, op, link, whence); }
423 };
424
425 struct TopDict : Dict {};
426 struct FontDict : Dict {};
427 struct PrivateDict : Dict {};
428
429 struct table_info_t
430 {
431   void init () { offset = size = 0; link = 0; }
432
433   unsigned int    offset;
434   unsigned int    size;
435   objidx_t        link;
436 };
437
438 template <typename COUNT>
439 struct FDArray : CFFIndexOf<COUNT, FontDict>
440 {
441   template <typename DICTVAL, typename INFO, typename Iterator, typename OP_SERIALIZER>
442   bool serialize (hb_serialize_context_t *c,
443                   Iterator it,
444                   OP_SERIALIZER& opszr)
445   {
446     TRACE_SERIALIZE (this);
447
448     /* serialize INDEX data */
449     hb_vector_t<unsigned> sizes;
450     c->push ();
451     + it
452     | hb_map ([&] (const hb_pair_t<const DICTVAL&, const INFO&> &_)
453     {
454       FontDict *dict = c->start_embed<FontDict> ();
455                 dict->serialize (c, _.first, opszr, _.second);
456                 return c->head - (const char*)dict;
457               })
458     | hb_sink (sizes)
459     ;
460     c->pop_pack (false);
461
462     /* serialize INDEX header */
463     return_trace (CFFIndex<COUNT>::serialize_header (c, hb_iter (sizes)));
464   }
465 };
466
467 /* FDSelect */
468 struct FDSelect0 {
469   bool sanitize (hb_sanitize_context_t *c, unsigned int fdcount) const
470   {
471     TRACE_SANITIZE (this);
472     if (unlikely (!(c->check_struct (this))))
473       return_trace (false);
474     for (unsigned int i = 0; i < c->get_num_glyphs (); i++)
475       if (unlikely (!fds[i].sanitize (c)))
476         return_trace (false);
477
478     return_trace (true);
479   }
480
481   hb_codepoint_t get_fd (hb_codepoint_t glyph) const
482   { return (hb_codepoint_t) fds[glyph]; }
483
484   unsigned int get_size (unsigned int num_glyphs) const
485   { return HBUINT8::static_size * num_glyphs; }
486
487   HBUINT8     fds[HB_VAR_ARRAY];
488
489   DEFINE_SIZE_MIN (0);
490 };
491
492 template <typename GID_TYPE, typename FD_TYPE>
493 struct FDSelect3_4_Range
494 {
495   bool sanitize (hb_sanitize_context_t *c, const void * /*nullptr*/, unsigned int fdcount) const
496   {
497     TRACE_SANITIZE (this);
498     return_trace (first < c->get_num_glyphs () && (fd < fdcount));
499   }
500
501   GID_TYPE    first;
502   FD_TYPE     fd;
503   public:
504   DEFINE_SIZE_STATIC (GID_TYPE::static_size + FD_TYPE::static_size);
505 };
506
507 template <typename GID_TYPE, typename FD_TYPE>
508 struct FDSelect3_4
509 {
510   unsigned int get_size () const
511   { return GID_TYPE::static_size * 2 + ranges.get_size (); }
512
513   bool sanitize (hb_sanitize_context_t *c, unsigned int fdcount) const
514   {
515     TRACE_SANITIZE (this);
516     if (unlikely (!c->check_struct (this) || !ranges.sanitize (c, nullptr, fdcount) ||
517                   (nRanges () == 0) || ranges[0].first != 0))
518       return_trace (false);
519
520     for (unsigned int i = 1; i < nRanges (); i++)
521       if (unlikely (ranges[i - 1].first >= ranges[i].first))
522         return_trace (false);
523
524     if (unlikely (!sentinel().sanitize (c) || (sentinel() != c->get_num_glyphs ())))
525       return_trace (false);
526
527     return_trace (true);
528   }
529
530   hb_codepoint_t get_fd (hb_codepoint_t glyph) const
531   {
532     unsigned int i;
533     for (i = 1; i < nRanges (); i++)
534       if (glyph < ranges[i].first)
535         break;
536
537     return (hb_codepoint_t) ranges[i - 1].fd;
538   }
539
540   GID_TYPE        &nRanges ()       { return ranges.len; }
541   GID_TYPE         nRanges () const { return ranges.len; }
542   GID_TYPE       &sentinel ()       { return StructAfter<GID_TYPE> (ranges[nRanges () - 1]); }
543   const GID_TYPE &sentinel () const { return StructAfter<GID_TYPE> (ranges[nRanges () - 1]); }
544
545   ArrayOf<FDSelect3_4_Range<GID_TYPE, FD_TYPE>, GID_TYPE> ranges;
546   /* GID_TYPE sentinel */
547
548   DEFINE_SIZE_ARRAY (GID_TYPE::static_size, ranges);
549 };
550
551 typedef FDSelect3_4<HBUINT16, HBUINT8> FDSelect3;
552 typedef FDSelect3_4_Range<HBUINT16, HBUINT8> FDSelect3_Range;
553
554 struct FDSelect
555 {
556   bool serialize (hb_serialize_context_t *c, const FDSelect &src, unsigned int num_glyphs)
557   {
558     TRACE_SERIALIZE (this);
559     unsigned int size = src.get_size (num_glyphs);
560     FDSelect *dest = c->allocate_size<FDSelect> (size);
561     if (unlikely (!dest)) return_trace (false);
562     memcpy (dest, &src, size);
563     return_trace (true);
564   }
565
566   unsigned int get_size (unsigned int num_glyphs) const
567   {
568     switch (format)
569     {
570     case 0: return format.static_size + u.format0.get_size (num_glyphs);
571     case 3: return format.static_size + u.format3.get_size ();
572     default:return 0;
573     }
574   }
575
576   hb_codepoint_t get_fd (hb_codepoint_t glyph) const
577   {
578     if (this == &Null (FDSelect)) return 0;
579
580     switch (format)
581     {
582     case 0: return u.format0.get_fd (glyph);
583     case 3: return u.format3.get_fd (glyph);
584     default:return 0;
585     }
586   }
587
588   bool sanitize (hb_sanitize_context_t *c, unsigned int fdcount) const
589   {
590     TRACE_SANITIZE (this);
591     if (unlikely (!c->check_struct (this)))
592       return_trace (false);
593
594     switch (format)
595     {
596     case 0: return_trace (u.format0.sanitize (c, fdcount));
597     case 3: return_trace (u.format3.sanitize (c, fdcount));
598     default:return_trace (false);
599     }
600   }
601
602   HBUINT8       format;
603   union {
604   FDSelect0     format0;
605   FDSelect3     format3;
606   } u;
607   public:
608   DEFINE_SIZE_MIN (1);
609 };
610
611 template <typename COUNT>
612 struct Subrs : CFFIndex<COUNT>
613 {
614   typedef COUNT count_type;
615   typedef CFFIndex<COUNT> SUPER;
616 };
617
618 } /* namespace CFF */
619
620 #endif /* HB_OT_CFF_COMMON_HH */