c4f2709af61d566ea9663ad159b859c6cf6af036
[framework/uifw/harfbuzz.git] / src / hb-open-type-private.hh
1 /*
2  * Copyright (C) 2007,2008,2009,2010  Red Hat, 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  * Red Hat Author(s): Behdad Esfahbod
25  */
26
27 #ifndef HB_OPEN_TYPES_PRIVATE_HH
28 #define HB_OPEN_TYPES_PRIVATE_HH
29
30 #include "hb-private.h"
31
32 #include "hb-blob.h"
33
34
35 /* Table/script/language-system/feature/... not found */
36 #define NO_INDEX                ((unsigned int) 0xFFFF)
37
38
39
40 /*
41  * Casts
42  */
43
44 /* Cast to "const char *" and "char *" */
45 template <typename Type>
46 inline const char * CharP (const Type* X)
47 { return reinterpret_cast<const char *>(X); }
48 template <typename Type>
49 inline char * CharP (Type* X)
50 { return reinterpret_cast<char *>(X); }
51
52 /* Cast to struct T, reference to reference */
53 template<typename Type, typename TObject>
54 inline const Type& CastR(const TObject &X)
55 { return reinterpret_cast<const Type&> (X); }
56 template<typename Type, typename TObject>
57 inline Type& CastR(TObject &X)
58 { return reinterpret_cast<Type&> (X); }
59
60 /* Cast to struct T, pointer to pointer */
61 template<typename Type, typename TObject>
62 inline const Type* CastP(const TObject *X)
63 { return reinterpret_cast<const Type*> (X); }
64 template<typename Type, typename TObject>
65 inline Type* CastP(TObject *X)
66 { return reinterpret_cast<Type*> (X); }
67
68 /* StructAtOffset<T>(X,Ofs) returns the struct T& that is placed at memory
69  * location of X plus Ofs bytes. */
70 template<typename Type, typename TObject>
71 inline const Type& StructAtOffset(const TObject &X, unsigned int offset)
72 { return * reinterpret_cast<const Type*> (CharP(&X) + offset); }
73 template<typename Type, typename TObject>
74 inline Type& StructAtOffset(TObject &X, unsigned int offset)
75 { return * reinterpret_cast<Type*> (CharP(&X) + offset); }
76
77 /* StructAfter<T>(X) returns the struct T& that is placed after X.
78  * Works with X of variable size also.  X must implement get_size() */
79 template<typename Type, typename TObject>
80 inline const Type& StructAfter(const TObject &X)
81 { return StructAtOffset<Type>(X, X.get_size()); }
82 template<typename Type, typename TObject>
83 inline Type& StructAfter(TObject &X)
84 { return StructAtOffset<Type>(X, X.get_size()); }
85
86
87
88 /*
89  * Size checking
90  */
91
92 #define DEFINE_SIZE_STATIC(size) \
93   inline void _size_assertion (void) const \
94   { ASSERT_STATIC (sizeof (*this) == (size)); } \
95   static inline unsigned int get_size (void) { return (size); } \
96   static const unsigned int static_size = (size); \
97   static const unsigned int min_size = (size)
98
99 #define DEFINE_SIZE_VAR(size, _var_type) \
100   inline void _size_assertion (void) const \
101   { ASSERT_STATIC (sizeof (*this) == (size) + VAR0 * sizeof (_var_type)); } \
102   static const unsigned int min_size = (size)
103
104 #define DEFINE_SIZE_VAR2(_type, size, _var_type1, _var_type2) \
105   inline void _size_assertion (void) const \
106   { ASSERT_STATIC (sizeof (*this) == (size) + VAR0 * sizeof (_var_type1) + VAR0 * sizeof (_var_type2)); } \
107   static const unsigned int min_size = (size)
108
109
110
111 /*
112  * Null objects
113  */
114
115 /* Global nul-content Null pool.  Enlarge as necessary. */
116 static const void *_NullPool[32 / sizeof (void *)];
117
118 /* Generic template for nul-content sizeof-sized Null objects. */
119 template <typename Type>
120 static inline const Type& Null () {
121   ASSERT_STATIC (sizeof (Type) <= sizeof (_NullPool));
122   return *CastP<Type> (_NullPool);
123 }
124
125 /* Specializaiton for arbitrary-content arbitrary-sized Null objects. */
126 #define DEFINE_NULL_DATA(Type, data) \
127 static const char _Null##Type[Type::min_size + 1] = data; /* +1 is for nul-termination in data */ \
128 template <> \
129 inline const Type& Null<Type> () { \
130   return *CastP<Type> (_Null##Type); \
131 } /* The following line really exists such that we end in a place needing semicolon */ \
132 ASSERT_STATIC (sizeof (Type) + 1 <= sizeof (_Null##Type))
133
134 /* Accessor macro. */
135 #define Null(Type) Null<Type>()
136
137
138 /*
139  * Trace
140  */
141
142
143 template <int max_depth>
144 struct hb_trace_t {
145   explicit hb_trace_t (unsigned int *pdepth) : pdepth(pdepth) { if (max_depth) ++*pdepth; }
146   ~hb_trace_t (void) { if (max_depth) --*pdepth; }
147
148   inline void log (const char *what, const char *function, const void *obj)
149   {
150     if (*pdepth < max_depth)
151       fprintf (stderr, "%s(%p) %-*d-> %s\n", what, obj, *pdepth, *pdepth, function);
152   }
153
154   private:
155   unsigned int *pdepth;
156 };
157 template <> /* Optimize when tracing is disabled */
158 struct hb_trace_t<0> {
159   explicit hb_trace_t (unsigned int *p) {}
160   inline void log (const char *what, const char *function, const void *obj) {};
161 };
162
163
164
165 /*
166  * Sanitize
167  */
168
169 #ifndef HB_DEBUG_SANITIZE
170 #define HB_DEBUG_SANITIZE HB_DEBUG+0
171 #endif
172
173
174 #define TRACE_SANITIZE() \
175         hb_trace_t<HB_DEBUG_SANITIZE> trace (&context->debug_depth); \
176         trace.log ("SANITIZE", HB_FUNC, this);
177
178
179 struct hb_sanitize_context_t
180 {
181   inline void init (hb_blob_t *blob)
182   {
183     this->blob = hb_blob_reference (blob);
184     this->start = hb_blob_lock (blob);
185     this->end = this->start + hb_blob_get_length (blob);
186     this->writable = hb_blob_is_writable (blob);
187     this->edit_count = 0;
188     this->debug_depth = 0;
189
190     if (HB_DEBUG_SANITIZE)
191       fprintf (stderr, "sanitize %p init [%p..%p] (%u bytes)\n",
192                this->blob, this->start, this->end, this->end - this->start);
193   }
194
195   inline void finish (void)
196   {
197     if (HB_DEBUG_SANITIZE)
198       fprintf (stderr, "sanitize %p fini [%p..%p] %u edit requests\n",
199                this->blob, this->start, this->end, this->edit_count);
200
201     hb_blob_unlock (this->blob);
202     hb_blob_destroy (this->blob);
203     this->blob = NULL;
204     this->start = this->end = NULL;
205   }
206
207   inline bool check_range (const void *base, unsigned int len) const
208   {
209     bool ret = this->start <= base &&
210                base <= this->end &&
211                (unsigned int) (this->end - CharP(base)) >= len;
212
213     if (HB_DEBUG_SANITIZE && (int) this->debug_depth < (int) HB_DEBUG_SANITIZE) \
214       fprintf (stderr, "SANITIZE(%p) %-*d-> range [%p..%p] (%d bytes) in [%p..%p] -> %s\n", \
215                base,
216                this->debug_depth, this->debug_depth,
217                base, CharP(base)+len, len,
218                this->start, this->end,
219                ret ? "pass" : "FAIL");
220
221     return likely (ret);
222   }
223
224   inline bool check_array (const void *base, unsigned int record_size, unsigned int len) const
225   {
226     bool overflows = len >= ((unsigned int) -1) / record_size;
227
228     if (HB_DEBUG_SANITIZE && (int) this->debug_depth < (int) HB_DEBUG_SANITIZE)
229       fprintf (stderr, "SANITIZE(%p) %-*d-> array [%p..%p] (%d*%d=%ld bytes) in [%p..%p] -> %s\n", \
230                base,
231                this->debug_depth, this->debug_depth,
232                base, CharP(base) + (record_size * len), record_size, len, (unsigned long) record_size * len,
233                this->start, this->end,
234                !overflows ? "does not overflow" : "OVERFLOWS FAIL");
235
236     return likely (!overflows && this->check_range (base, record_size * len));
237   }
238
239   template <typename Type>
240   inline bool check_struct (const Type *obj) const
241   {
242     return likely (this->check_range (obj, sizeof (*obj)));
243   }
244
245   inline bool can_edit (const char *base HB_UNUSED, unsigned int len HB_UNUSED)
246   {
247     this->edit_count++;
248
249     if (HB_DEBUG_SANITIZE && (int) this->debug_depth < (int) HB_DEBUG_SANITIZE)
250       fprintf (stderr, "SANITIZE(%p) %-*d-> edit(%u) [%p..%p] (%d bytes) in [%p..%p] -> %s\n", \
251                base,
252                this->debug_depth, this->debug_depth,
253                this->edit_count,
254                base, base+len, len,
255                this->start, this->end,
256                this->writable ? "granted" : "REJECTED");
257
258     return this->writable;
259   }
260
261   unsigned int debug_depth;
262   const char *start, *end;
263   bool writable;
264   unsigned int edit_count;
265   hb_blob_t *blob;
266 };
267
268
269
270 /* Template to sanitize an object. */
271 template <typename Type>
272 struct Sanitizer
273 {
274   static hb_blob_t *sanitize (hb_blob_t *blob) {
275     hb_sanitize_context_t context[1] = {{0}};
276     bool sane;
277
278     /* TODO is_sane() stuff */
279
280   retry:
281     if (HB_DEBUG_SANITIZE)
282       fprintf (stderr, "Sanitizer %p start %s\n", blob, HB_FUNC);
283
284     context->init (blob);
285
286     Type *t = CastP<Type> (const_cast<char *> (context->start));
287
288     sane = t->sanitize (context);
289     if (sane) {
290       if (context->edit_count) {
291         if (HB_DEBUG_SANITIZE)
292           fprintf (stderr, "Sanitizer %p passed first round with %d edits; doing a second round %s\n",
293                    blob, context->edit_count, HB_FUNC);
294
295         /* sanitize again to ensure no toe-stepping */
296         context->edit_count = 0;
297         sane = t->sanitize (context);
298         if (context->edit_count) {
299           if (HB_DEBUG_SANITIZE)
300             fprintf (stderr, "Sanitizer %p requested %d edits in second round; FAILLING %s\n",
301                      blob, context->edit_count, HB_FUNC);
302           sane = false;
303         }
304       }
305       context->finish ();
306     } else {
307       unsigned int edit_count = context->edit_count;
308       context->finish ();
309       if (edit_count && !hb_blob_is_writable (blob) && hb_blob_try_writable (blob)) {
310         /* ok, we made it writable by relocating.  try again */
311         if (HB_DEBUG_SANITIZE)
312           fprintf (stderr, "Sanitizer %p retry %s\n", blob, HB_FUNC);
313         goto retry;
314       }
315     }
316
317     if (HB_DEBUG_SANITIZE)
318       fprintf (stderr, "Sanitizer %p %s %s\n", blob, sane ? "passed" : "FAILED", HB_FUNC);
319     if (sane)
320       return blob;
321     else {
322       hb_blob_destroy (blob);
323       return hb_blob_create_empty ();
324     }
325   }
326 };
327
328
329
330
331 /*
332  *
333  * The OpenType Font File: Data Types
334  */
335
336
337 /* "The following data types are used in the OpenType font file.
338  *  All OpenType fonts use Motorola-style byte ordering (Big Endian):" */
339
340 /*
341  * Int types
342  */
343
344
345 template <typename Type, int Bytes> class BEInt;
346
347 /* LONGTERMTODO: On machines allowing unaligned access, we can make the
348  * following tighter by using byteswap instructions on ints directly. */
349 template <typename Type>
350 class BEInt<Type, 2>
351 {
352   public:
353   inline class BEInt<Type,2>& operator = (Type i) { hb_be_uint16_put (v,i); return *this; }
354   inline operator Type () const { return hb_be_uint16_get (v); }
355   inline bool operator == (const BEInt<Type, 2>& o) const { return hb_be_uint16_cmp (v, o.v); }
356   inline bool operator != (const BEInt<Type, 2>& o) const { return !(*this == o); }
357   private: uint8_t v[2];
358 };
359 template <typename Type>
360 class BEInt<Type, 4>
361 {
362   public:
363   inline class BEInt<Type,4>& operator = (Type i) { hb_be_uint32_put (v,i); return *this; }
364   inline operator Type () const { return hb_be_uint32_get (v); }
365   inline bool operator == (const BEInt<Type, 4>& o) const { return hb_be_uint32_cmp (v, o.v); }
366   inline bool operator != (const BEInt<Type, 4>& o) const { return !(*this == o); }
367   private: uint8_t v[4];
368 };
369
370 /* Integer types in big-endian order and no alignment requirement */
371 template <typename Type>
372 struct IntType
373 {
374   inline void set (Type i) { v = i; }
375   inline operator Type(void) const { return v; }
376   inline bool operator == (const IntType<Type> &o) const { return v == o.v; }
377   inline bool operator != (const IntType<Type> &o) const { return v != o.v; }
378   inline bool sanitize (hb_sanitize_context_t *context) {
379     TRACE_SANITIZE ();
380     return context->check_struct (this);
381   }
382   DEFINE_SIZE_STATIC (sizeof (Type));
383   private: BEInt<Type, sizeof (Type)> v;
384 };
385
386 typedef IntType<uint16_t> USHORT;       /* 16-bit unsigned integer. */
387 typedef IntType<int16_t>  SHORT;        /* 16-bit signed integer. */
388 typedef IntType<uint32_t> ULONG;        /* 32-bit unsigned integer. */
389 typedef IntType<int32_t>  LONG;         /* 32-bit signed integer. */
390
391 /* Array of four uint8s (length = 32 bits) used to identify a script, language
392  * system, feature, or baseline */
393 struct Tag : ULONG
394 {
395   /* What the char* converters return is NOT nul-terminated.  Print using "%.4s" */
396   inline operator const char* (void) const { return CharP(this); }
397   inline operator char* (void) { return CharP(this); }
398 };
399 ASSERT_SIZE (Tag, 4);
400 DEFINE_NULL_DATA (Tag, "    ");
401
402 /* Glyph index number, same as uint16 (length = 16 bits) */
403 typedef USHORT GlyphID;
404
405 /* Offset to a table, same as uint16 (length = 16 bits), Null offset = 0x0000 */
406 typedef USHORT Offset;
407
408 /* LongOffset to a table, same as uint32 (length = 32 bits), Null offset = 0x00000000 */
409 typedef ULONG LongOffset;
410
411
412 /* CheckSum */
413 struct CheckSum : ULONG
414 {
415   static uint32_t CalcTableChecksum (ULONG *Table, uint32_t Length)
416   {
417     uint32_t Sum = 0L;
418     ULONG *EndPtr = Table+((Length+3) & ~3) / ULONG::static_size;
419
420     while (Table < EndPtr)
421       Sum += *Table++;
422     return Sum;
423   }
424 };
425 ASSERT_SIZE (CheckSum, 4);
426
427
428 /*
429  * Version Numbers
430  */
431
432 struct FixedVersion
433 {
434   inline operator uint32_t (void) const { return (major << 16) + minor; }
435
436   inline bool sanitize (hb_sanitize_context_t *context) {
437     TRACE_SANITIZE ();
438     return context->check_struct (this);
439   }
440
441   USHORT major;
442   USHORT minor;
443 };
444 ASSERT_SIZE (FixedVersion, 4);
445
446
447
448 /*
449  * Template subclasses of Offset and LongOffset that do the dereferencing.
450  * Use: (base+offset)
451  */
452
453 template <typename OffsetType, typename Type>
454 struct GenericOffsetTo : OffsetType
455 {
456   inline const Type& operator () (const void *base) const
457   {
458     unsigned int offset = *this;
459     if (unlikely (!offset)) return Null(Type);
460     return StructAtOffset<Type> (*CharP(base), offset);
461   }
462
463   inline bool sanitize (hb_sanitize_context_t *context, void *base) {
464     TRACE_SANITIZE ();
465     if (!context->check_struct (this)) return false;
466     unsigned int offset = *this;
467     if (unlikely (!offset)) return true;
468     Type &obj = StructAtOffset<Type> (*CharP(base), offset);
469     return likely (obj.sanitize (context)) || neuter (context);
470   }
471   template <typename T>
472   inline bool sanitize (hb_sanitize_context_t *context, void *base, T user_data) {
473     TRACE_SANITIZE ();
474     if (!context->check_struct (this)) return false;
475     unsigned int offset = *this;
476     if (unlikely (!offset)) return true;
477     Type &obj = StructAtOffset<Type> (*CharP(base), offset);
478     return likely (obj.sanitize (context, user_data)) || neuter (context);
479   }
480
481   private:
482   /* Set the offset to Null */
483   inline bool neuter (hb_sanitize_context_t *context) {
484     if (context->can_edit (CharP(this), this->static_size)) {
485       this->set (0); /* 0 is Null offset */
486       return true;
487     }
488     return false;
489   }
490 };
491 template <typename Base, typename OffsetType, typename Type>
492 inline const Type& operator + (const Base &base, GenericOffsetTo<OffsetType, Type> offset) { return offset (base); }
493
494 template <typename Type>
495 struct OffsetTo : GenericOffsetTo<Offset, Type> {};
496
497 template <typename Type>
498 struct LongOffsetTo : GenericOffsetTo<LongOffset, Type> {};
499
500
501 /*
502  * Array Types
503  */
504
505 template <typename LenType, typename Type>
506 struct GenericArrayOf
507 {
508   const Type *array(void) const { return &StructAfter<Type> (len); }
509   Type *array(void) { return &StructAfter<Type> (len); }
510
511   const Type *sub_array (unsigned int start_offset, unsigned int *pcount /* IN/OUT */) const
512   {
513     unsigned int count = len;
514     if (unlikely (start_offset > count))
515       count = 0;
516     else
517       count -= start_offset;
518     count = MIN (count, *pcount);
519     *pcount = count;
520     return array() + start_offset;
521   }
522
523   inline const Type& operator [] (unsigned int i) const
524   {
525     if (unlikely (i >= len)) return Null(Type);
526     return array()[i];
527   }
528   inline unsigned int get_size () const
529   { return len.static_size + len * Type::static_size; }
530
531   inline bool sanitize (hb_sanitize_context_t *context) {
532     TRACE_SANITIZE ();
533     if (!likely (sanitize_shallow (context))) return false;
534     /* Note: for structs that do not reference other structs,
535      * we do not need to call their sanitize() as we already did
536      * a bound check on the aggregate array size, hence the return.
537      */
538     return true;
539     /* We do keep this code though to make sure the structs pointed
540      * to do have a simple sanitize(), ie. they do not reference
541      * other structs. */
542     unsigned int count = len;
543     for (unsigned int i = 0; i < count; i++)
544       if (array()[i].sanitize (context))
545         return false;
546     return true;
547   }
548   inline bool sanitize (hb_sanitize_context_t *context, void *base) {
549     TRACE_SANITIZE ();
550     if (!likely (sanitize_shallow (context))) return false;
551     unsigned int count = len;
552     for (unsigned int i = 0; i < count; i++)
553       if (!array()[i].sanitize (context, base))
554         return false;
555     return true;
556   }
557   template <typename T>
558   inline bool sanitize (hb_sanitize_context_t *context, void *base, T user_data) {
559     TRACE_SANITIZE ();
560     if (!likely (sanitize_shallow (context))) return false;
561     unsigned int count = len;
562     for (unsigned int i = 0; i < count; i++)
563       if (!array()[i].sanitize (context, base, user_data))
564         return false;
565     return true;
566   }
567
568   private:
569   inline bool sanitize_shallow (hb_sanitize_context_t *context) {
570     TRACE_SANITIZE ();
571     return context->check_struct (this)
572         && context->check_array (this, Type::static_size, len);
573   }
574
575   public:
576   LenType len;
577 /*Type array[VAR];*/
578 };
579
580 /* An array with a USHORT number of elements. */
581 template <typename Type>
582 struct ArrayOf : GenericArrayOf<USHORT, Type> {};
583
584 /* An array with a ULONG number of elements. */
585 template <typename Type>
586 struct LongArrayOf : GenericArrayOf<ULONG, Type> {};
587
588 /* Array of Offset's */
589 template <typename Type>
590 struct OffsetArrayOf : ArrayOf<OffsetTo<Type> > {};
591
592 /* Array of LongOffset's */
593 template <typename Type>
594 struct LongOffsetArrayOf : ArrayOf<LongOffsetTo<Type> > {};
595
596 /* LongArray of LongOffset's */
597 template <typename Type>
598 struct LongOffsetLongArrayOf : LongArrayOf<LongOffsetTo<Type> > {};
599
600 /* Array of offsets relative to the beginning of the array itself. */
601 template <typename Type>
602 struct OffsetListOf : OffsetArrayOf<Type>
603 {
604   inline const Type& operator [] (unsigned int i) const
605   {
606     if (unlikely (i >= this->len)) return Null(Type);
607     return this+this->array()[i];
608   }
609
610   inline bool sanitize (hb_sanitize_context_t *context) {
611     TRACE_SANITIZE ();
612     return OffsetArrayOf<Type>::sanitize (context, CharP(this));
613   }
614   template <typename T>
615   inline bool sanitize (hb_sanitize_context_t *context, T user_data) {
616     TRACE_SANITIZE ();
617     return OffsetArrayOf<Type>::sanitize (context, CharP(this), user_data);
618   }
619 };
620
621
622 /* An array with a USHORT number of elements,
623  * starting at second element. */
624 template <typename Type>
625 struct HeadlessArrayOf
626 {
627   const Type *array(void) const { return &StructAfter<Type> (len); }
628   Type *array(void) { return &StructAfter<Type> (len); }
629
630   inline const Type& operator [] (unsigned int i) const
631   {
632     if (unlikely (i >= len || !i)) return Null(Type);
633     return array()[i-1];
634   }
635   inline unsigned int get_size () const
636   { return len.static_size + (len ? len - 1 : 0) * Type::static_size; }
637
638   inline bool sanitize_shallow (hb_sanitize_context_t *context) {
639     return context->check_struct (this)
640         && context->check_array (this, Type::static_size, len);
641   }
642
643   inline bool sanitize (hb_sanitize_context_t *context) {
644     TRACE_SANITIZE ();
645     if (!likely (sanitize_shallow (context))) return false;
646     /* Note: for structs that do not reference other structs,
647      * we do not need to call their sanitize() as we already did
648      * a bound check on the aggregate array size, hence the return.
649      */
650     return true;
651     /* We do keep this code though to make sure the structs pointed
652      * to do have a simple sanitize(), ie. they do not reference
653      * other structs. */
654     unsigned int count = len ? len - 1 : 0;
655     Type *a = array();
656     for (unsigned int i = 0; i < count; i++)
657       if (!a[i].sanitize (context))
658         return false;
659     return true;
660   }
661
662   USHORT len;
663 /*Type array[VAR];*/
664 };
665
666
667 #endif /* HB_OPEN_TYPE_PRIVATE_HH */