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