Imported Upstream version 2.4.0
[platform/upstream/harfbuzz.git] / src / hb-machinery.hh
1 /*
2  * Copyright © 2007,2008,2009,2010  Red Hat, Inc.
3  * Copyright © 2012,2018  Google, Inc.
4  *
5  *  This is part of HarfBuzz, a text shaping library.
6  *
7  * Permission is hereby granted, without written agreement and without
8  * license or royalty fees, to use, copy, modify, and distribute this
9  * software and its documentation for any purpose, provided that the
10  * above copyright notice and the following two paragraphs appear in
11  * all copies of this software.
12  *
13  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17  * DAMAGE.
18  *
19  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
22  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24  *
25  * Red Hat Author(s): Behdad Esfahbod
26  * Google Author(s): Behdad Esfahbod
27  */
28
29 #ifndef HB_MACHINERY_HH
30 #define HB_MACHINERY_HH
31
32 #include "hb.hh"
33 #include "hb-blob.hh"
34
35 #include "hb-array.hh"
36 #include "hb-vector.hh"
37
38
39 /*
40  * Casts
41  */
42
43 /* Cast to struct T, reference to reference */
44 template<typename Type, typename TObject>
45 static inline const Type& CastR(const TObject &X)
46 { return reinterpret_cast<const Type&> (X); }
47 template<typename Type, typename TObject>
48 static inline Type& CastR(TObject &X)
49 { return reinterpret_cast<Type&> (X); }
50
51 /* Cast to struct T, pointer to pointer */
52 template<typename Type, typename TObject>
53 static inline const Type* CastP(const TObject *X)
54 { return reinterpret_cast<const Type*> (X); }
55 template<typename Type, typename TObject>
56 static inline Type* CastP(TObject *X)
57 { return reinterpret_cast<Type*> (X); }
58
59 /* StructAtOffset<T>(P,Ofs) returns the struct T& that is placed at memory
60  * location pointed to by P plus Ofs bytes. */
61 template<typename Type>
62 static inline const Type& StructAtOffset(const void *P, unsigned int offset)
63 { return * reinterpret_cast<const Type*> ((const char *) P + offset); }
64 template<typename Type>
65 static inline Type& StructAtOffset(void *P, unsigned int offset)
66 { return * reinterpret_cast<Type*> ((char *) P + offset); }
67 template<typename Type>
68 static inline const Type& StructAtOffsetUnaligned(const void *P, unsigned int offset)
69 {
70 #pragma GCC diagnostic push
71 #pragma GCC diagnostic ignored "-Wcast-align"
72   return * reinterpret_cast<Type*> ((char *) P + offset);
73 #pragma GCC diagnostic pop
74 }
75 template<typename Type>
76 static inline Type& StructAtOffsetUnaligned(void *P, unsigned int offset)
77 {
78 #pragma GCC diagnostic push
79 #pragma GCC diagnostic ignored "-Wcast-align"
80   return * reinterpret_cast<Type*> ((char *) P + offset);
81 #pragma GCC diagnostic pop
82 }
83
84 /* StructAfter<T>(X) returns the struct T& that is placed after X.
85  * Works with X of variable size also.  X must implement get_size() */
86 template<typename Type, typename TObject>
87 static inline const Type& StructAfter(const TObject &X)
88 { return StructAtOffset<Type>(&X, X.get_size()); }
89 template<typename Type, typename TObject>
90 static inline Type& StructAfter(TObject &X)
91 { return StructAtOffset<Type>(&X, X.get_size()); }
92
93
94 /*
95  * Size checking
96  */
97
98 /* Check _assertion in a method environment */
99 #define _DEFINE_INSTANCE_ASSERTION1(_line, _assertion) \
100   void _instance_assertion_on_line_##_line () const \
101   { static_assert ((_assertion), ""); }
102 # define _DEFINE_INSTANCE_ASSERTION0(_line, _assertion) _DEFINE_INSTANCE_ASSERTION1 (_line, _assertion)
103 # define DEFINE_INSTANCE_ASSERTION(_assertion) _DEFINE_INSTANCE_ASSERTION0 (__LINE__, _assertion)
104
105 /* Check that _code compiles in a method environment */
106 #define _DEFINE_COMPILES_ASSERTION1(_line, _code) \
107   void _compiles_assertion_on_line_##_line () const \
108   { _code; }
109 # define _DEFINE_COMPILES_ASSERTION0(_line, _code) _DEFINE_COMPILES_ASSERTION1 (_line, _code)
110 # define DEFINE_COMPILES_ASSERTION(_code) _DEFINE_COMPILES_ASSERTION0 (__LINE__, _code)
111
112
113 #define DEFINE_SIZE_STATIC(size) \
114   DEFINE_INSTANCE_ASSERTION (sizeof (*this) == (size)) \
115   unsigned int get_size () const { return (size); } \
116   static constexpr unsigned null_size = (size); \
117   static constexpr unsigned min_size = (size); \
118   static constexpr unsigned static_size = (size)
119
120 #define DEFINE_SIZE_UNION(size, _member) \
121   DEFINE_COMPILES_ASSERTION ((void) this->u._member.static_size) \
122   DEFINE_INSTANCE_ASSERTION (sizeof(this->u._member) == (size)) \
123   static constexpr unsigned null_size = (size); \
124   static constexpr unsigned min_size = (size)
125
126 #define DEFINE_SIZE_MIN(size) \
127   DEFINE_INSTANCE_ASSERTION (sizeof (*this) >= (size)) \
128   static constexpr unsigned null_size = (size); \
129   static constexpr unsigned min_size = (size)
130
131 #define DEFINE_SIZE_UNBOUNDED(size) \
132   DEFINE_INSTANCE_ASSERTION (sizeof (*this) >= (size)) \
133   static constexpr unsigned min_size = (size)
134
135 #define DEFINE_SIZE_ARRAY(size, array) \
136   DEFINE_COMPILES_ASSERTION ((void) (array)[0].static_size) \
137   DEFINE_INSTANCE_ASSERTION (sizeof (*this) == (size) + VAR * sizeof ((array)[0])) \
138   static constexpr unsigned null_size = (size); \
139   static constexpr unsigned min_size = (size)
140
141 #define DEFINE_SIZE_ARRAY_SIZED(size, array) \
142   unsigned int get_size () const { return (size - (array).min_size + (array).get_size ()); } \
143   DEFINE_SIZE_ARRAY(size, array)
144
145
146 /*
147  * Dispatch
148  */
149
150 template <typename Context, typename Return, unsigned int MaxDebugDepth>
151 struct hb_dispatch_context_t
152 {
153   static constexpr unsigned max_debug_depth = MaxDebugDepth;
154   typedef Return return_t;
155   template <typename T, typename F>
156   bool may_dispatch (const T *obj HB_UNUSED, const F *format HB_UNUSED) { return true; }
157   static return_t no_dispatch_return_value () { return Context::default_return_value (); }
158   static bool stop_sublookup_iteration (const return_t r HB_UNUSED) { return false; }
159 };
160
161
162 /*
163  * Sanitize
164  *
165  *
166  * === Introduction ===
167  *
168  * The sanitize machinery is at the core of our zero-cost font loading.  We
169  * mmap() font file into memory and create a blob out of it.  Font subtables
170  * are returned as a readonly sub-blob of the main font blob.  These table
171  * blobs are then sanitized before use, to ensure invalid memory access does
172  * not happen.  The toplevel sanitize API use is like, eg. to load the 'head'
173  * table:
174  *
175  *   hb_blob_t *head_blob = hb_sanitize_context_t ().reference_table<OT::head> (face);
176  *
177  * The blob then can be converted to a head table struct with:
178  *
179  *   const head *head_table = head_blob->as<head> ();
180  *
181  * What the reference_table does is, to call hb_face_reference_table() to load
182  * the table blob, sanitize it and return either the sanitized blob, or empty
183  * blob if sanitization failed.  The blob->as() function returns the null
184  * object of its template type argument if the blob is empty.  Otherwise, it
185  * just casts the blob contents to the desired type.
186  *
187  * Sanitizing a blob of data with a type T works as follows (with minor
188  * simplification):
189  *
190  *   - Cast blob content to T*, call sanitize() method of it,
191  *   - If sanitize succeeded, return blob.
192  *   - Otherwise, if blob is not writable, try making it writable,
193  *     or copy if cannot be made writable in-place,
194  *   - Call sanitize() again.  Return blob if sanitize succeeded.
195  *   - Return empty blob otherwise.
196  *
197  *
198  * === The sanitize() contract ===
199  *
200  * The sanitize() method of each object type shall return true if it's safe to
201  * call other methods of the object, and false otherwise.
202  *
203  * Note that what sanitize() checks for might align with what the specification
204  * describes as valid table data, but does not have to be.  In particular, we
205  * do NOT want to be pedantic and concern ourselves with validity checks that
206  * are irrelevant to our use of the table.  On the contrary, we want to be
207  * lenient with error handling and accept invalid data to the extent that it
208  * does not impose extra burden on us.
209  *
210  * Based on the sanitize contract, one can see that what we check for depends
211  * on how we use the data in other table methods.  Ie. if other table methods
212  * assume that offsets do NOT point out of the table data block, then that's
213  * something sanitize() must check for (GSUB/GPOS/GDEF/etc work this way).  On
214  * the other hand, if other methods do such checks themselves, then sanitize()
215  * does not have to bother with them (glyf/local work this way).  The choice
216  * depends on the table structure and sanitize() performance.  For example, to
217  * check glyf/loca offsets in sanitize() would cost O(num-glyphs).  We try hard
218  * to avoid such costs during font loading.  By postponing such checks to the
219  * actual glyph loading, we reduce the sanitize cost to O(1) and total runtime
220  * cost to O(used-glyphs).  As such, this is preferred.
221  *
222  * The same argument can be made re GSUB/GPOS/GDEF, but there, the table
223  * structure is so complicated that by checking all offsets at sanitize() time,
224  * we make the code much simpler in other methods, as offsets and referenced
225  * objects do not need to be validated at each use site.
226  */
227
228 /* This limits sanitizing time on really broken fonts. */
229 #ifndef HB_SANITIZE_MAX_EDITS
230 #define HB_SANITIZE_MAX_EDITS 32
231 #endif
232 #ifndef HB_SANITIZE_MAX_OPS_FACTOR
233 #define HB_SANITIZE_MAX_OPS_FACTOR 8
234 #endif
235 #ifndef HB_SANITIZE_MAX_OPS_MIN
236 #define HB_SANITIZE_MAX_OPS_MIN 16384
237 #endif
238 #ifndef HB_SANITIZE_MAX_OPS_MAX
239 #define HB_SANITIZE_MAX_OPS_MAX 0x3FFFFFFF
240 #endif
241
242 struct hb_sanitize_context_t :
243        hb_dispatch_context_t<hb_sanitize_context_t, bool, HB_DEBUG_SANITIZE>
244 {
245   hb_sanitize_context_t () :
246         debug_depth (0),
247         start (nullptr), end (nullptr),
248         max_ops (0),
249         writable (false), edit_count (0),
250         blob (nullptr),
251         num_glyphs (65536),
252         num_glyphs_set (false) {}
253
254   const char *get_name () { return "SANITIZE"; }
255   template <typename T, typename F>
256   bool may_dispatch (const T *obj HB_UNUSED, const F *format)
257   { return format->sanitize (this); }
258   template <typename T>
259   return_t dispatch (const T &obj) { return obj.sanitize (this); }
260   static return_t default_return_value () { return true; }
261   static return_t no_dispatch_return_value () { return false; }
262   bool stop_sublookup_iteration (const return_t r) const { return !r; }
263
264   void init (hb_blob_t *b)
265   {
266     this->blob = hb_blob_reference (b);
267     this->writable = false;
268   }
269
270   void set_num_glyphs (unsigned int num_glyphs_)
271   {
272     num_glyphs = num_glyphs_;
273     num_glyphs_set = true;
274   }
275   unsigned int get_num_glyphs () { return num_glyphs; }
276
277   void set_max_ops (int max_ops_) { max_ops = max_ops_; }
278
279   template <typename T>
280   void set_object (const T *obj)
281   {
282     reset_object ();
283
284     if (!obj) return;
285
286     const char *obj_start = (const char *) obj;
287     if (unlikely (obj_start < this->start || this->end <= obj_start))
288       this->start = this->end = nullptr;
289     else
290     {
291       this->start = obj_start;
292       this->end   = obj_start + MIN<uintptr_t> (this->end - obj_start, obj->get_size ());
293     }
294   }
295
296   void reset_object ()
297   {
298     this->start = this->blob->data;
299     this->end = this->start + this->blob->length;
300     assert (this->start <= this->end); /* Must not overflow. */
301   }
302
303   void start_processing ()
304   {
305     reset_object ();
306     this->max_ops = MAX ((unsigned int) (this->end - this->start) * HB_SANITIZE_MAX_OPS_FACTOR,
307                          (unsigned) HB_SANITIZE_MAX_OPS_MIN);
308     this->edit_count = 0;
309     this->debug_depth = 0;
310
311     DEBUG_MSG_LEVEL (SANITIZE, start, 0, +1,
312                      "start [%p..%p] (%lu bytes)",
313                      this->start, this->end,
314                      (unsigned long) (this->end - this->start));
315   }
316
317   void end_processing ()
318   {
319     DEBUG_MSG_LEVEL (SANITIZE, this->start, 0, -1,
320                      "end [%p..%p] %u edit requests",
321                      this->start, this->end, this->edit_count);
322
323     hb_blob_destroy (this->blob);
324     this->blob = nullptr;
325     this->start = this->end = nullptr;
326   }
327
328   bool check_range (const void *base,
329                     unsigned int len) const
330   {
331     const char *p = (const char *) base;
332     bool ok = !len ||
333               (this->start <= p &&
334                p <= this->end &&
335                (unsigned int) (this->end - p) >= len &&
336                this->max_ops-- > 0);
337
338     DEBUG_MSG_LEVEL (SANITIZE, p, this->debug_depth+1, 0,
339                      "check_range [%p..%p]"
340                      " (%d bytes) in [%p..%p] -> %s",
341                      p, p + len, len,
342                      this->start, this->end,
343                      ok ? "OK" : "OUT-OF-RANGE");
344
345     return likely (ok);
346   }
347
348   template <typename T>
349   bool check_range (const T *base,
350                     unsigned int a,
351                     unsigned int b) const
352   {
353     return !hb_unsigned_mul_overflows (a, b) &&
354            this->check_range (base, a * b);
355   }
356
357   template <typename T>
358   bool check_range (const T *base,
359                     unsigned int a,
360                     unsigned int b,
361                     unsigned int c) const
362   {
363     return !hb_unsigned_mul_overflows (a, b) &&
364            this->check_range (base, a * b, c);
365   }
366
367   template <typename T>
368   bool check_array (const T *base, unsigned int len) const
369   {
370     return this->check_range (base, len, hb_static_size (T));
371   }
372
373   template <typename T>
374   bool check_array (const T *base,
375                     unsigned int a,
376                     unsigned int b) const
377   {
378     return this->check_range (base, a, b, hb_static_size (T));
379   }
380
381   template <typename Type>
382   bool check_struct (const Type *obj) const
383   { return likely (this->check_range (obj, obj->min_size)); }
384
385   bool may_edit (const void *base, unsigned int len)
386   {
387     if (this->edit_count >= HB_SANITIZE_MAX_EDITS)
388       return false;
389
390     const char *p = (const char *) base;
391     this->edit_count++;
392
393     DEBUG_MSG_LEVEL (SANITIZE, p, this->debug_depth+1, 0,
394        "may_edit(%u) [%p..%p] (%d bytes) in [%p..%p] -> %s",
395        this->edit_count,
396        p, p + len, len,
397        this->start, this->end,
398        this->writable ? "GRANTED" : "DENIED");
399
400     return this->writable;
401   }
402
403   template <typename Type, typename ValueType>
404   bool try_set (const Type *obj, const ValueType &v)
405   {
406     if (this->may_edit (obj, hb_static_size (Type)))
407     {
408       hb_assign (* const_cast<Type *> (obj), v);
409       return true;
410     }
411     return false;
412   }
413
414   template <typename Type>
415   hb_blob_t *sanitize_blob (hb_blob_t *blob)
416   {
417     bool sane;
418
419     init (blob);
420
421   retry:
422     DEBUG_MSG_FUNC (SANITIZE, start, "start");
423
424     start_processing ();
425
426     if (unlikely (!start))
427     {
428       end_processing ();
429       return blob;
430     }
431
432     Type *t = CastP<Type> (const_cast<char *> (start));
433
434     sane = t->sanitize (this);
435     if (sane)
436     {
437       if (edit_count)
438       {
439         DEBUG_MSG_FUNC (SANITIZE, start, "passed first round with %d edits; going for second round", edit_count);
440
441         /* sanitize again to ensure no toe-stepping */
442         edit_count = 0;
443         sane = t->sanitize (this);
444         if (edit_count) {
445           DEBUG_MSG_FUNC (SANITIZE, start, "requested %d edits in second round; FAILLING", edit_count);
446           sane = false;
447         }
448       }
449     }
450     else
451     {
452       if (edit_count && !writable) {
453         start = hb_blob_get_data_writable (blob, nullptr);
454         end = start + blob->length;
455
456         if (start)
457         {
458           writable = true;
459           /* ok, we made it writable by relocating.  try again */
460           DEBUG_MSG_FUNC (SANITIZE, start, "retry");
461           goto retry;
462         }
463       }
464     }
465
466     end_processing ();
467
468     DEBUG_MSG_FUNC (SANITIZE, start, sane ? "PASSED" : "FAILED");
469     if (sane)
470     {
471       hb_blob_make_immutable (blob);
472       return blob;
473     }
474     else
475     {
476       hb_blob_destroy (blob);
477       return hb_blob_get_empty ();
478     }
479   }
480
481   template <typename Type>
482   hb_blob_t *reference_table (const hb_face_t *face, hb_tag_t tableTag = Type::tableTag)
483   {
484     if (!num_glyphs_set)
485       set_num_glyphs (hb_face_get_glyph_count (face));
486     return sanitize_blob<Type> (hb_face_reference_table (face, tableTag));
487   }
488
489   mutable unsigned int debug_depth;
490   const char *start, *end;
491   mutable int max_ops;
492   private:
493   bool writable;
494   unsigned int edit_count;
495   hb_blob_t *blob;
496   unsigned int num_glyphs;
497   bool  num_glyphs_set;
498 };
499
500 struct hb_sanitize_with_object_t
501 {
502   template <typename T>
503   hb_sanitize_with_object_t (hb_sanitize_context_t *c,
504                                     const T& obj) : c (c)
505   { c->set_object (obj); }
506   ~hb_sanitize_with_object_t ()
507   { c->reset_object (); }
508
509   private:
510   hb_sanitize_context_t *c;
511 };
512
513
514 /*
515  * Serialize
516  */
517
518 struct hb_serialize_context_t
519 {
520   hb_serialize_context_t (void *start_, unsigned int size)
521   {
522     this->start = (char *) start_;
523     this->end = this->start + size;
524     reset ();
525   }
526
527   bool in_error () const { return !this->successful; }
528
529   void reset ()
530   {
531     this->successful = true;
532     this->head = this->start;
533     this->debug_depth = 0;
534   }
535
536   bool propagate_error (bool e)
537   { return this->successful = this->successful && e; }
538   template <typename T> bool propagate_error (const T &obj)
539   { return this->successful = this->successful && !obj.in_error (); }
540   template <typename T> bool propagate_error (const T *obj)
541   { return this->successful = this->successful && !obj->in_error (); }
542   template <typename T1, typename T2> bool propagate_error (T1 &o1, T2 &o2)
543   { return propagate_error (o1) && propagate_error (o2); }
544   template <typename T1, typename T2> bool propagate_error (T1 *o1, T2 *o2)
545   { return propagate_error (o1) && propagate_error (o2); }
546   template <typename T1, typename T2, typename T3>
547   bool propagate_error (T1 &o1, T2 &o2, T3 &o3)
548   { return propagate_error (o1) && propagate_error (o2, o3); }
549   template <typename T1, typename T2, typename T3>
550   bool propagate_error (T1 *o1, T2 *o2, T3 *o3)
551   { return propagate_error (o1) && propagate_error (o2, o3); }
552
553   /* To be called around main operation. */
554   template <typename Type>
555   Type *start_serialize ()
556   {
557     DEBUG_MSG_LEVEL (SERIALIZE, this->start, 0, +1,
558                      "start [%p..%p] (%lu bytes)",
559                      this->start, this->end,
560                      (unsigned long) (this->end - this->start));
561
562     return start_embed<Type> ();
563   }
564   void end_serialize ()
565   {
566     DEBUG_MSG_LEVEL (SERIALIZE, this->start, 0, -1,
567                      "end [%p..%p] serialized %d bytes; %s",
568                      this->start, this->end,
569                      (int) (this->head - this->start),
570                      this->successful ? "successful" : "UNSUCCESSFUL");
571   }
572
573   unsigned int length () const { return this->head - this->start; }
574
575   void align (unsigned int alignment)
576   {
577     unsigned int l = length () % alignment;
578     if (l)
579       allocate_size<void> (alignment - l);
580   }
581
582   template <typename Type>
583   Type *start_embed (const Type *_ HB_UNUSED = nullptr) const
584   {
585     Type *ret = reinterpret_cast<Type *> (this->head);
586     return ret;
587   }
588
589   template <typename Type>
590   Type *allocate_size (unsigned int size)
591   {
592     if (unlikely (!this->successful || this->end - this->head < ptrdiff_t (size))) {
593       this->successful = false;
594       return nullptr;
595     }
596     memset (this->head, 0, size);
597     char *ret = this->head;
598     this->head += size;
599     return reinterpret_cast<Type *> (ret);
600   }
601
602   template <typename Type>
603   Type *allocate_min ()
604   {
605     return this->allocate_size<Type> (Type::min_size);
606   }
607
608   template <typename Type>
609   Type *embed (const Type &obj)
610   {
611     unsigned int size = obj.get_size ();
612     Type *ret = this->allocate_size<Type> (size);
613     if (unlikely (!ret)) return nullptr;
614     memcpy (ret, &obj, size);
615     return ret;
616   }
617   template <typename Type>
618   hb_serialize_context_t &operator << (const Type &obj) { embed (obj); return *this; }
619
620   template <typename Type>
621   Type *extend_size (Type &obj, unsigned int size)
622   {
623     assert (this->start <= (char *) &obj);
624     assert ((char *) &obj <= this->head);
625     assert ((char *) &obj + size >= this->head);
626     if (unlikely (!this->allocate_size<Type> (((char *) &obj) + size - this->head))) return nullptr;
627     return reinterpret_cast<Type *> (&obj);
628   }
629
630   template <typename Type>
631   Type *extend_min (Type &obj) { return extend_size (obj, obj.min_size); }
632
633   template <typename Type>
634   Type *extend (Type &obj) { return extend_size (obj, obj.get_size ()); }
635
636   /* Output routines. */
637   template <typename Type>
638   Type *copy () const
639   {
640     assert (this->successful);
641     unsigned int len = this->head - this->start;
642     void *p = malloc (len);
643     if (p)
644       memcpy (p, this->start, len);
645     return reinterpret_cast<Type *> (p);
646   }
647   hb_bytes_t copy_bytes () const
648   {
649     assert (this->successful);
650     unsigned int len = this->head - this->start;
651     void *p = malloc (len);
652     if (p)
653       memcpy (p, this->start, len);
654     else
655       return hb_bytes_t ();
656     return hb_bytes_t ((char *) p, len);
657   }
658   hb_blob_t *copy_blob () const
659   {
660     assert (this->successful);
661     return hb_blob_create (this->start,
662                            this->head - this->start,
663                            HB_MEMORY_MODE_DUPLICATE,
664                            nullptr, nullptr);
665   }
666
667   public:
668   unsigned int debug_depth;
669   char *start, *end, *head;
670   bool successful;
671 };
672
673
674
675 /*
676  * Big-endian integers.
677  */
678
679 template <typename Type, int Bytes> struct BEInt;
680
681 template <typename Type>
682 struct BEInt<Type, 1>
683 {
684   public:
685   void set (Type V)      { v = V; }
686   operator Type () const { return v; }
687   private: uint8_t v;
688 };
689 template <typename Type>
690 struct BEInt<Type, 2>
691 {
692   public:
693   void set (Type V)
694   {
695     v[0] = (V >>  8) & 0xFF;
696     v[1] = (V      ) & 0xFF;
697   }
698   operator Type () const
699   {
700 #if ((defined(__GNUC__) && __GNUC__ >= 5) || defined(__clang__)) && \
701     defined(__BYTE_ORDER) && \
702     (__BYTE_ORDER == __LITTLE_ENDIAN || __BYTE_ORDER == __BIG_ENDIAN)
703     /* Spoon-feed the compiler a big-endian integer with alignment 1.
704      * https://github.com/harfbuzz/harfbuzz/pull/1398 */
705     struct __attribute__((packed)) packed_uint16_t { uint16_t v; };
706 #if __BYTE_ORDER == __LITTLE_ENDIAN
707     return __builtin_bswap16 (((packed_uint16_t *) this)->v);
708 #else /* __BYTE_ORDER == __BIG_ENDIAN */
709     return ((packed_uint16_t *) this)->v;
710 #endif
711 #endif
712     return (v[0] <<  8)
713          + (v[1]      );
714   }
715   private: uint8_t v[2];
716 };
717 template <typename Type>
718 struct BEInt<Type, 3>
719 {
720   public:
721   void set (Type V)
722   {
723     v[0] = (V >> 16) & 0xFF;
724     v[1] = (V >>  8) & 0xFF;
725     v[2] = (V      ) & 0xFF;
726   }
727   operator Type () const
728   {
729     return (v[0] << 16)
730          + (v[1] <<  8)
731          + (v[2]      );
732   }
733   private: uint8_t v[3];
734 };
735 template <typename Type>
736 struct BEInt<Type, 4>
737 {
738   public:
739   typedef Type type;
740   void set (Type V)
741   {
742     v[0] = (V >> 24) & 0xFF;
743     v[1] = (V >> 16) & 0xFF;
744     v[2] = (V >>  8) & 0xFF;
745     v[3] = (V      ) & 0xFF;
746   }
747   operator Type () const
748   {
749     return (v[0] << 24)
750          + (v[1] << 16)
751          + (v[2] <<  8)
752          + (v[3]      );
753   }
754   private: uint8_t v[4];
755 };
756
757
758 /*
759  * Lazy loaders.
760  */
761
762 template <typename Data, unsigned int WheresData>
763 struct hb_data_wrapper_t
764 {
765   static_assert (WheresData > 0, "");
766
767   Data * get_data () const
768   { return *(((Data **) (void *) this) - WheresData); }
769
770   bool is_inert () const { return !get_data (); }
771
772   template <typename Stored, typename Subclass>
773   Stored * call_create () const { return Subclass::create (get_data ()); }
774 };
775 template <>
776 struct hb_data_wrapper_t<void, 0>
777 {
778   bool is_inert () const { return false; }
779
780   template <typename Stored, typename Funcs>
781   Stored * call_create () const { return Funcs::create (); }
782 };
783
784 template <typename T1, typename T2> struct hb_non_void_t { typedef T1 value; };
785 template <typename T2> struct hb_non_void_t<void, T2> { typedef T2 value; };
786
787 template <typename Returned,
788           typename Subclass = void,
789           typename Data = void,
790           unsigned int WheresData = 0,
791           typename Stored = Returned>
792 struct hb_lazy_loader_t : hb_data_wrapper_t<Data, WheresData>
793 {
794   typedef typename hb_non_void_t<Subclass,
795                                  hb_lazy_loader_t<Returned,Subclass,Data,WheresData,Stored>
796                                 >::value Funcs;
797
798   void init0 () {} /* Init, when memory is already set to 0. No-op for us. */
799   void init ()  { instance.set_relaxed (nullptr); }
800   void fini ()  { do_destroy (instance.get ()); }
801
802   void free_instance ()
803   {
804   retry:
805     Stored *p = instance.get ();
806     if (unlikely (p && !cmpexch (p, nullptr)))
807       goto retry;
808     do_destroy (p);
809   }
810
811   static void do_destroy (Stored *p)
812   {
813     if (p && p != const_cast<Stored *> (Funcs::get_null ()))
814       Funcs::destroy (p);
815   }
816
817   const Returned * operator -> () const { return get (); }
818   const Returned & operator * () const  { return *get (); }
819   explicit_operator bool () const
820   { return get_stored () != Funcs::get_null (); }
821   template <typename C> operator const C * () const { return get (); }
822
823   Stored * get_stored () const
824   {
825   retry:
826     Stored *p = this->instance.get ();
827     if (unlikely (!p))
828     {
829       if (unlikely (this->is_inert ()))
830         return const_cast<Stored *> (Funcs::get_null ());
831
832       p = this->template call_create<Stored, Funcs> ();
833       if (unlikely (!p))
834         p = const_cast<Stored *> (Funcs::get_null ());
835
836       if (unlikely (!cmpexch (nullptr, p)))
837       {
838         do_destroy (p);
839         goto retry;
840       }
841     }
842     return p;
843   }
844   Stored * get_stored_relaxed () const
845   {
846     return this->instance.get_relaxed ();
847   }
848
849   bool cmpexch (Stored *current, Stored *value) const
850   {
851     /* This *must* be called when there are no other threads accessing. */
852     return this->instance.cmpexch (current, value);
853   }
854
855   const Returned * get () const { return Funcs::convert (get_stored ()); }
856   const Returned * get_relaxed () const { return Funcs::convert (get_stored_relaxed ()); }
857   Returned * get_unconst () const { return const_cast<Returned *> (Funcs::convert (get_stored ())); }
858
859   /* To be possibly overloaded by subclasses. */
860   static Returned* convert (Stored *p) { return p; }
861
862   /* By default null/init/fini the object. */
863   static const Stored* get_null () { return &Null(Stored); }
864   static Stored *create (Data *data)
865   {
866     Stored *p = (Stored *) calloc (1, sizeof (Stored));
867     if (likely (p))
868       p->init (data);
869     return p;
870   }
871   static Stored *create ()
872   {
873     Stored *p = (Stored *) calloc (1, sizeof (Stored));
874     if (likely (p))
875       p->init ();
876     return p;
877   }
878   static void destroy (Stored *p)
879   {
880     p->fini ();
881     free (p);
882   }
883
884 //  private:
885   /* Must only have one pointer. */
886   hb_atomic_ptr_t<Stored *> instance;
887 };
888
889 /* Specializations. */
890
891 template <typename T, unsigned int WheresFace>
892 struct hb_face_lazy_loader_t : hb_lazy_loader_t<T,
893                                                 hb_face_lazy_loader_t<T, WheresFace>,
894                                                 hb_face_t, WheresFace> {};
895
896 template <typename T, unsigned int WheresFace>
897 struct hb_table_lazy_loader_t : hb_lazy_loader_t<T,
898                                                  hb_table_lazy_loader_t<T, WheresFace>,
899                                                  hb_face_t, WheresFace,
900                                                  hb_blob_t>
901 {
902   static hb_blob_t *create (hb_face_t *face)
903   { return hb_sanitize_context_t ().reference_table<T> (face); }
904   static void destroy (hb_blob_t *p) { hb_blob_destroy (p); }
905
906   static const hb_blob_t *get_null ()
907   { return hb_blob_get_empty (); }
908
909   static const T* convert (const hb_blob_t *blob)
910   { return blob->as<T> (); }
911
912   hb_blob_t* get_blob () const { return this->get_stored (); }
913 };
914
915 template <typename Subclass>
916 struct hb_font_funcs_lazy_loader_t : hb_lazy_loader_t<hb_font_funcs_t, Subclass>
917 {
918   static void destroy (hb_font_funcs_t *p)
919   { hb_font_funcs_destroy (p); }
920   static const hb_font_funcs_t *get_null ()
921   { return hb_font_funcs_get_empty (); }
922 };
923 template <typename Subclass>
924 struct hb_unicode_funcs_lazy_loader_t : hb_lazy_loader_t<hb_unicode_funcs_t, Subclass>
925 {
926   static void destroy (hb_unicode_funcs_t *p)
927   { hb_unicode_funcs_destroy (p); }
928   static const hb_unicode_funcs_t *get_null ()
929   { return hb_unicode_funcs_get_empty (); }
930 };
931
932
933 #endif /* HB_MACHINERY_HH */