1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 // This file is available under and governed by the GNU General Public
  26 // License version 2 only, as published by the Free Software Foundation.
  27 // However, the following notice accompanied the original version of this
  28 // file:
  29 //
  30 /*
  31  * Copyright © 2007,2008,2009  Red Hat, Inc.
  32  * Copyright © 2011,2012  Google, Inc.
  33  *
  34  *  This is part of HarfBuzz, a text shaping library.
  35  *
  36  * Permission is hereby granted, without written agreement and without
  37  * license or royalty fees, to use, copy, modify, and distribute this
  38  * software and its documentation for any purpose, provided that the
  39  * above copyright notice and the following two paragraphs appear in
  40  * all copies of this software.
  41  *
  42  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
  43  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
  44  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
  45  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  46  * DAMAGE.
  47  *
  48  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
  49  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  50  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  51  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
  52  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  53  *
  54  * Red Hat Author(s): Behdad Esfahbod
  55  * Google Author(s): Behdad Esfahbod
  56  */
  57 
  58 #ifndef HB_PRIVATE_HH
  59 #define HB_PRIVATE_HH
  60 
  61 #ifdef HAVE_CONFIG_H
  62 #include "config.h"
  63 #endif
  64 
  65 #include "hb.h"
  66 #define HB_H_IN
  67 #ifdef HAVE_OT
  68 #include "hb-ot.h"
  69 #define HB_OT_H_IN
  70 #endif
  71 
  72 #include <stdlib.h>
  73 #include <stddef.h>
  74 #include <string.h>
  75 #include <assert.h>
  76 
  77 /* We only use these two for debug output.  However, the debug code is
  78  * always seen by the compiler (and optimized out in non-debug builds.
  79  * If including these becomes a problem, we can start thinking about
  80  * someway around that. */
  81 #include <stdio.h>
  82 #include <errno.h>
  83 #include <stdarg.h>
  84 
  85 
  86 /* Compile-time custom allocator support. */
  87 
  88 #if defined(hb_malloc_impl) \
  89  && defined(hb_calloc_impl) \
  90  && defined(hb_realloc_impl) \
  91  && defined(hb_free_impl)
  92 extern "C" void* hb_malloc_impl(size_t size);
  93 extern "C" void* hb_calloc_impl(size_t nmemb, size_t size);
  94 extern "C" void* hb_realloc_impl(void *ptr, size_t size);
  95 extern "C" void  hb_free_impl(void *ptr);
  96 #define malloc hb_malloc_impl
  97 #define calloc hb_calloc_impl
  98 #define realloc hb_realloc_impl
  99 #define free hb_free_impl
 100 #endif
 101 
 102 
 103 /* Compiler attributes */
 104 
 105 
 106 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
 107 #define _HB_BOOLEAN_EXPR(expr) ((expr) ? 1 : 0)
 108 #define likely(expr) (__builtin_expect (_HB_BOOLEAN_EXPR(expr), 1))
 109 #define unlikely(expr) (__builtin_expect (_HB_BOOLEAN_EXPR(expr), 0))
 110 #else
 111 #define likely(expr) (expr)
 112 #define unlikely(expr) (expr)
 113 #endif
 114 
 115 #ifndef __GNUC__
 116 #undef __attribute__
 117 #define __attribute__(x)
 118 #endif
 119 
 120 #if __GNUC__ >= 3
 121 #define HB_PURE_FUNC    __attribute__((pure))
 122 #define HB_CONST_FUNC   __attribute__((const))
 123 #define HB_PRINTF_FUNC(format_idx, arg_idx) __attribute__((__format__ (__printf__, format_idx, arg_idx)))
 124 #else
 125 #define HB_PURE_FUNC
 126 #define HB_CONST_FUNC
 127 #define HB_PRINTF_FUNC(format_idx, arg_idx)
 128 #endif
 129 #if __GNUC__ >= 4
 130 #define HB_UNUSED       __attribute__((unused))
 131 #else
 132 #define HB_UNUSED
 133 #endif
 134 
 135 #ifndef HB_INTERNAL
 136 # if !defined(__MINGW32__) && !defined(__CYGWIN__)
 137 #  define HB_INTERNAL __attribute__((__visibility__("hidden")))
 138 # else
 139 #  define HB_INTERNAL
 140 # endif
 141 #endif
 142 
 143 #if __GNUC__ >= 3
 144 #define HB_FUNC __PRETTY_FUNCTION__
 145 #elif defined(_MSC_VER)
 146 #define HB_FUNC __FUNCSIG__
 147 #else
 148 #define HB_FUNC __func__
 149 #endif
 150 
 151 #if defined(_WIN32) || defined(__CYGWIN__)
 152    /* We need Windows Vista for both Uniscribe backend and for
 153     * MemoryBarrier.  We don't support compiling on Windows XP,
 154     * though we run on it fine. */
 155 #  if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600
 156 #    undef _WIN32_WINNT
 157 #  endif
 158 #  ifndef _WIN32_WINNT
 159 #    define _WIN32_WINNT 0x0600
 160 #  endif
 161 #  ifndef WIN32_LEAN_AND_MEAN
 162 #    define WIN32_LEAN_AND_MEAN 1
 163 #  endif
 164 #  ifndef STRICT
 165 #    define STRICT 1
 166 #  endif
 167 
 168 #  if defined(_WIN32_WCE)
 169      /* Some things not defined on Windows CE. */
 170 #    define strdup _strdup
 171 #    define getenv(Name) NULL
 172 #    if _WIN32_WCE < 0x800
 173 #      define setlocale(Category, Locale) "C"
 174 static int errno = 0; /* Use something better? */
 175 #    endif
 176 #  elif defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
 177 #    define getenv(Name) NULL
 178 #  endif
 179 #  if defined(_MSC_VER) && _MSC_VER < 1900
 180 #    define snprintf _snprintf
 181 #  endif
 182 #endif
 183 
 184 #if HAVE_ATEXIT
 185 /* atexit() is only safe to be called from shared libraries on certain
 186  * platforms.  Whitelist.
 187  * https://bugs.freedesktop.org/show_bug.cgi?id=82246 */
 188 #  if defined(__linux) && defined(__GLIBC_PREREQ)
 189 #    if __GLIBC_PREREQ(2,3)
 190 /* From atexit() manpage, it's safe with glibc 2.2.3 on Linux. */
 191 #      define HB_USE_ATEXIT 1
 192 #    endif
 193 #  elif defined(_MSC_VER) || defined(__MINGW32__)
 194 /* For MSVC:
 195  * http://msdn.microsoft.com/en-ca/library/tze57ck3.aspx
 196  * http://msdn.microsoft.com/en-ca/library/zk17ww08.aspx
 197  * mingw32 headers say atexit is safe to use in shared libraries.
 198  */
 199 #    define HB_USE_ATEXIT 1
 200 #  elif defined(__ANDROID__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
 201 /* This was fixed in Android NKD r8 or r8b:
 202  * https://code.google.com/p/android/issues/detail?id=6455
 203  * which introduced GCC 4.6:
 204  * https://developer.android.com/tools/sdk/ndk/index.html
 205  */
 206 #    define HB_USE_ATEXIT 1
 207 #  endif
 208 #endif
 209 
 210 /* Basics */
 211 
 212 
 213 #ifndef NULL
 214 # define NULL ((void *) 0)
 215 #endif
 216 
 217 #undef MIN
 218 template <typename Type>
 219 static inline Type MIN (const Type &a, const Type &b) { return a < b ? a : b; }
 220 
 221 #undef MAX
 222 template <typename Type>
 223 static inline Type MAX (const Type &a, const Type &b) { return a > b ? a : b; }
 224 
 225 static inline unsigned int DIV_CEIL (const unsigned int a, unsigned int b)
 226 { return (a + (b - 1)) / b; }
 227 
 228 
 229 #undef  ARRAY_LENGTH
 230 template <typename Type, unsigned int n>
 231 static inline unsigned int ARRAY_LENGTH (const Type (&)[n]) { return n; }
 232 /* A const version, but does not detect erratically being called on pointers. */
 233 #define ARRAY_LENGTH_CONST(__array) ((signed int) (sizeof (__array) / sizeof (__array[0])))
 234 
 235 #define HB_STMT_START do
 236 #define HB_STMT_END   while (0)
 237 
 238 #define _ASSERT_STATIC1(_line, _cond)   HB_UNUSED typedef int _static_assert_on_line_##_line##_failed[(_cond)?1:-1]
 239 #define _ASSERT_STATIC0(_line, _cond)   _ASSERT_STATIC1 (_line, (_cond))
 240 #define ASSERT_STATIC(_cond)            _ASSERT_STATIC0 (__LINE__, (_cond))
 241 
 242 /* Note: C++ allows sizeof() of variable-lengh arrays.  So, if _cond is not
 243  * constant, it still compiles (ouch!), but at least we'll get a -Wvla warning. */
 244 #define ASSERT_STATIC_EXPR_ZERO(_cond) (0 * sizeof (char[(_cond) ? 1 : -1]))
 245 
 246 #define _PASTE1(a,b) a##b
 247 #define PASTE(a,b) _PASTE1(a,b)
 248 
 249 /* Lets assert int types.  Saves trouble down the road. */
 250 
 251 ASSERT_STATIC (sizeof (int8_t) == 1);
 252 ASSERT_STATIC (sizeof (uint8_t) == 1);
 253 ASSERT_STATIC (sizeof (int16_t) == 2);
 254 ASSERT_STATIC (sizeof (uint16_t) == 2);
 255 ASSERT_STATIC (sizeof (int32_t) == 4);
 256 ASSERT_STATIC (sizeof (uint32_t) == 4);
 257 ASSERT_STATIC (sizeof (int64_t) == 8);
 258 ASSERT_STATIC (sizeof (uint64_t) == 8);
 259 
 260 ASSERT_STATIC (sizeof (hb_codepoint_t) == 4);
 261 ASSERT_STATIC (sizeof (hb_position_t) == 4);
 262 ASSERT_STATIC (sizeof (hb_mask_t) == 4);
 263 ASSERT_STATIC (sizeof (hb_var_int_t) == 4);
 264 
 265 
 266 /* We like our types POD */
 267 
 268 #define _ASSERT_TYPE_POD1(_line, _type) union _type_##_type##_on_line_##_line##_is_not_POD { _type instance; }
 269 #define _ASSERT_TYPE_POD0(_line, _type) _ASSERT_TYPE_POD1 (_line, _type)
 270 #define ASSERT_TYPE_POD(_type)          _ASSERT_TYPE_POD0 (__LINE__, _type)
 271 
 272 #ifdef __GNUC__
 273 # define _ASSERT_INSTANCE_POD1(_line, _instance) \
 274         HB_STMT_START { \
 275                 typedef __typeof__(_instance) _type_##_line; \
 276                 _ASSERT_TYPE_POD1 (_line, _type_##_line); \
 277         } HB_STMT_END
 278 #else
 279 # define _ASSERT_INSTANCE_POD1(_line, _instance)        typedef int _assertion_on_line_##_line##_not_tested
 280 #endif
 281 # define _ASSERT_INSTANCE_POD0(_line, _instance)        _ASSERT_INSTANCE_POD1 (_line, _instance)
 282 # define ASSERT_INSTANCE_POD(_instance)                 _ASSERT_INSTANCE_POD0 (__LINE__, _instance)
 283 
 284 /* Check _assertion in a method environment */
 285 #define _ASSERT_POD1(_line) \
 286         HB_UNUSED inline void _static_assertion_on_line_##_line (void) const \
 287         { _ASSERT_INSTANCE_POD1 (_line, *this); /* Make sure it's POD. */ }
 288 # define _ASSERT_POD0(_line)    _ASSERT_POD1 (_line)
 289 # define ASSERT_POD()           _ASSERT_POD0 (__LINE__)
 290 
 291 
 292 
 293 /* Misc */
 294 
 295 /* Void! */
 296 struct _hb_void_t {};
 297 typedef const _hb_void_t *hb_void_t;
 298 #define HB_VOID ((const _hb_void_t *) NULL)
 299 
 300 /* Return the number of 1 bits in mask. */
 301 static inline HB_CONST_FUNC unsigned int
 302 _hb_popcount32 (uint32_t mask)
 303 {
 304 #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
 305   return __builtin_popcount (mask);
 306 #else
 307   /* "HACKMEM 169" */
 308   uint32_t y;
 309   y = (mask >> 1) &033333333333;
 310   y = mask - y - ((y >>1) & 033333333333);
 311   return (((y + (y >> 3)) & 030707070707) % 077);
 312 #endif
 313 }
 314 
 315 /* Returns the number of bits needed to store number */
 316 static inline HB_CONST_FUNC unsigned int
 317 _hb_bit_storage (unsigned int number)
 318 {
 319 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
 320   return likely (number) ? (sizeof (unsigned int) * 8 - __builtin_clz (number)) : 0;
 321 #else
 322   unsigned int n_bits = 0;
 323   while (number) {
 324     n_bits++;
 325     number >>= 1;
 326   }
 327   return n_bits;
 328 #endif
 329 }
 330 
 331 /* Returns the number of zero bits in the least significant side of number */
 332 static inline HB_CONST_FUNC unsigned int
 333 _hb_ctz (unsigned int number)
 334 {
 335 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
 336   return likely (number) ? __builtin_ctz (number) : 0;
 337 #else
 338   unsigned int n_bits = 0;
 339   if (unlikely (!number)) return 0;
 340   while (!(number & 1)) {
 341     n_bits++;
 342     number >>= 1;
 343   }
 344   return n_bits;
 345 #endif
 346 }
 347 
 348 static inline bool
 349 _hb_unsigned_int_mul_overflows (unsigned int count, unsigned int size)
 350 {
 351   return (size > 0) && (count >= ((unsigned int) -1) / size);
 352 }
 353 
 354 
 355 /* Type of bsearch() / qsort() compare function */
 356 typedef int (*hb_compare_func_t) (const void *, const void *);
 357 
 358 
 359 
 360 
 361 /* arrays and maps */
 362 
 363 
 364 #define HB_PREALLOCED_ARRAY_INIT {0, 0, NULL}
 365 template <typename Type, unsigned int StaticSize=16>
 366 struct hb_prealloced_array_t
 367 {
 368   unsigned int len;
 369   unsigned int allocated;
 370   Type *array;
 371   Type static_array[StaticSize];
 372 
 373   void init (void) { memset (this, 0, sizeof (*this)); }
 374 
 375   inline Type& operator [] (unsigned int i) { return array[i]; }
 376   inline const Type& operator [] (unsigned int i) const { return array[i]; }
 377 
 378   inline Type *push (void)
 379   {
 380     if (!array) {
 381       array = static_array;
 382       allocated = ARRAY_LENGTH (static_array);
 383     }
 384     if (likely (len < allocated))
 385       return &array[len++];
 386 
 387     /* Need to reallocate */
 388     unsigned int new_allocated = allocated + (allocated >> 1) + 8;
 389     Type *new_array = NULL;
 390 
 391     if (array == static_array) {
 392       new_array = (Type *) calloc (new_allocated, sizeof (Type));
 393       if (new_array)
 394         memcpy (new_array, array, len * sizeof (Type));
 395     } else {
 396       bool overflows = (new_allocated < allocated) || _hb_unsigned_int_mul_overflows (new_allocated, sizeof (Type));
 397       if (likely (!overflows)) {
 398         new_array = (Type *) realloc (array, new_allocated * sizeof (Type));
 399       }
 400     }
 401 
 402     if (unlikely (!new_array))
 403       return NULL;
 404 
 405     array = new_array;
 406     allocated = new_allocated;
 407     return &array[len++];
 408   }
 409 
 410   inline void pop (void)
 411   {
 412     len--;
 413   }
 414 
 415   inline void remove (unsigned int i)
 416   {
 417      if (unlikely (i >= len))
 418        return;
 419      memmove (static_cast<void *> (&array[i]),
 420               static_cast<void *> (&array[i + 1]),
 421               (len - i - 1) * sizeof (Type));
 422      len--;
 423   }
 424 
 425   inline void shrink (unsigned int l)
 426   {
 427      if (l < len)
 428        len = l;
 429   }
 430 
 431   template <typename T>
 432   inline Type *find (T v) {
 433     for (unsigned int i = 0; i < len; i++)
 434       if (array[i] == v)
 435         return &array[i];
 436     return NULL;
 437   }
 438   template <typename T>
 439   inline const Type *find (T v) const {
 440     for (unsigned int i = 0; i < len; i++)
 441       if (array[i] == v)
 442         return &array[i];
 443     return NULL;
 444   }
 445 
 446   inline void qsort (void)
 447   {
 448     ::qsort (array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
 449   }
 450 
 451   inline void qsort (unsigned int start, unsigned int end)
 452   {
 453     ::qsort (array + start, end - start, sizeof (Type), (hb_compare_func_t) Type::cmp);
 454   }
 455 
 456   template <typename T>
 457   inline Type *bsearch (T *key)
 458   {
 459     return (Type *) ::bsearch (key, array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
 460   }
 461   template <typename T>
 462   inline const Type *bsearch (T *key) const
 463   {
 464     return (const Type *) ::bsearch (key, array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
 465   }
 466 
 467   inline void finish (void)
 468   {
 469     if (array != static_array)
 470       free (array);
 471     array = NULL;
 472     allocated = len = 0;
 473   }
 474 };
 475 
 476 template <typename Type>
 477 struct hb_auto_array_t : hb_prealloced_array_t <Type>
 478 {
 479   hb_auto_array_t (void) { hb_prealloced_array_t<Type>::init (); }
 480   ~hb_auto_array_t (void) { hb_prealloced_array_t<Type>::finish (); }
 481 };
 482 
 483 
 484 #define HB_LOCKABLE_SET_INIT {HB_PREALLOCED_ARRAY_INIT}
 485 template <typename item_t, typename lock_t>
 486 struct hb_lockable_set_t
 487 {
 488   hb_prealloced_array_t <item_t, 2> items;
 489 
 490   inline void init (void) { items.init (); }
 491 
 492   template <typename T>
 493   inline item_t *replace_or_insert (T v, lock_t &l, bool replace)
 494   {
 495     l.lock ();
 496     item_t *item = items.find (v);
 497     if (item) {
 498       if (replace) {
 499         item_t old = *item;
 500         *item = v;
 501         l.unlock ();
 502         old.finish ();
 503       }
 504       else {
 505         item = NULL;
 506         l.unlock ();
 507       }
 508     } else {
 509       item = items.push ();
 510       if (likely (item))
 511         *item = v;
 512       l.unlock ();
 513     }
 514     return item;
 515   }
 516 
 517   template <typename T>
 518   inline void remove (T v, lock_t &l)
 519   {
 520     l.lock ();
 521     item_t *item = items.find (v);
 522     if (item) {
 523       item_t old = *item;
 524       *item = items[items.len - 1];
 525       items.pop ();
 526       l.unlock ();
 527       old.finish ();
 528     } else {
 529       l.unlock ();
 530     }
 531   }
 532 
 533   template <typename T>
 534   inline bool find (T v, item_t *i, lock_t &l)
 535   {
 536     l.lock ();
 537     item_t *item = items.find (v);
 538     if (item)
 539       *i = *item;
 540     l.unlock ();
 541     return !!item;
 542   }
 543 
 544   template <typename T>
 545   inline item_t *find_or_insert (T v, lock_t &l)
 546   {
 547     l.lock ();
 548     item_t *item = items.find (v);
 549     if (!item) {
 550       item = items.push ();
 551       if (likely (item))
 552         *item = v;
 553     }
 554     l.unlock ();
 555     return item;
 556   }
 557 
 558   inline void finish (lock_t &l)
 559   {
 560     if (!items.len) {
 561       /* No need for locking. */
 562       items.finish ();
 563       return;
 564     }
 565     l.lock ();
 566     while (items.len) {
 567       item_t old = items[items.len - 1];
 568         items.pop ();
 569         l.unlock ();
 570         old.finish ();
 571         l.lock ();
 572     }
 573     items.finish ();
 574     l.unlock ();
 575   }
 576 
 577 };
 578 
 579 
 580 /* ASCII tag/character handling */
 581 
 582 static inline bool ISALPHA (unsigned char c)
 583 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
 584 static inline bool ISALNUM (unsigned char c)
 585 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
 586 static inline bool ISSPACE (unsigned char c)
 587 { return c == ' ' || c =='\f'|| c =='\n'|| c =='\r'|| c =='\t'|| c =='\v'; }
 588 static inline unsigned char TOUPPER (unsigned char c)
 589 { return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; }
 590 static inline unsigned char TOLOWER (unsigned char c)
 591 { return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; }
 592 
 593 #define HB_TAG_CHAR4(s)   (HB_TAG(((const char *) s)[0], \
 594                                   ((const char *) s)[1], \
 595                                   ((const char *) s)[2], \
 596                                   ((const char *) s)[3]))
 597 
 598 
 599 /* C++ helpers */
 600 
 601 /* Makes class uncopyable.  Use in private: section. */
 602 #define NO_COPY(T) \
 603   T (const T &o); \
 604   T &operator = (const T &o)
 605 
 606 
 607 /* Debug */
 608 
 609 
 610 #ifndef HB_DEBUG
 611 #define HB_DEBUG 0
 612 #endif
 613 
 614 static inline bool
 615 _hb_debug (unsigned int level,
 616            unsigned int max_level)
 617 {
 618   return level < max_level;
 619 }
 620 
 621 #define DEBUG_LEVEL_ENABLED(WHAT, LEVEL) (_hb_debug ((LEVEL), HB_DEBUG_##WHAT))
 622 #define DEBUG_ENABLED(WHAT) (DEBUG_LEVEL_ENABLED (WHAT, 0))
 623 
 624 static inline void
 625 _hb_print_func (const char *func)
 626 {
 627   if (func)
 628   {
 629     unsigned int func_len = strlen (func);
 630     /* Skip "static" */
 631     if (0 == strncmp (func, "static ", 7))
 632       func += 7;
 633     /* Skip "typename" */
 634     if (0 == strncmp (func, "typename ", 9))
 635       func += 9;
 636     /* Skip return type */
 637     const char *space = strchr (func, ' ');
 638     if (space)
 639       func = space + 1;
 640     /* Skip parameter list */
 641     const char *paren = strchr (func, '(');
 642     if (paren)
 643       func_len = paren - func;
 644     fprintf (stderr, "%.*s", func_len, func);
 645   }
 646 }
 647 
 648 template <int max_level> static inline void
 649 _hb_debug_msg_va (const char *what,
 650                   const void *obj,
 651                   const char *func,
 652                   bool indented,
 653                   unsigned int level,
 654                   int level_dir,
 655                   const char *message,
 656                   va_list ap) HB_PRINTF_FUNC(7, 0);
 657 template <int max_level> static inline void
 658 _hb_debug_msg_va (const char *what,
 659                   const void *obj,
 660                   const char *func,
 661                   bool indented,
 662                   unsigned int level,
 663                   int level_dir,
 664                   const char *message,
 665                   va_list ap)
 666 {
 667   if (!_hb_debug (level, max_level))
 668     return;
 669 
 670   fprintf (stderr, "%-10s", what ? what : "");
 671 
 672   if (obj)
 673     fprintf (stderr, "(%0*lx) ", (unsigned int) (2 * sizeof (void *)), (unsigned long) obj);
 674   else
 675     fprintf (stderr, " %*s  ", (unsigned int) (2 * sizeof (void *)), "");
 676 
 677   if (indented) {
 678 /* One may want to add ASCII version of these.  See:
 679  * https://bugs.freedesktop.org/show_bug.cgi?id=50970 */
 680 #define VBAR    "\342\224\202"  /* U+2502 BOX DRAWINGS LIGHT VERTICAL */
 681 #define VRBAR   "\342\224\234"  /* U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
 682 #define DLBAR   "\342\225\256"  /* U+256E BOX DRAWINGS LIGHT ARC DOWN AND LEFT */
 683 #define ULBAR   "\342\225\257"  /* U+256F BOX DRAWINGS LIGHT ARC UP AND LEFT */
 684 #define LBAR    "\342\225\264"  /* U+2574 BOX DRAWINGS LIGHT LEFT */
 685     static const char bars[] = VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR;
 686     fprintf (stderr, "%2u %s" VRBAR "%s",
 687              level,
 688              bars + sizeof (bars) - 1 - MIN ((unsigned int) sizeof (bars), (unsigned int) (sizeof (VBAR) - 1) * level),
 689              level_dir ? (level_dir > 0 ? DLBAR : ULBAR) : LBAR);
 690   } else
 691     fprintf (stderr, "   " VRBAR LBAR);
 692 
 693   _hb_print_func (func);
 694 
 695   if (message)
 696   {
 697     fprintf (stderr, ": ");
 698     vfprintf (stderr, message, ap);
 699   }
 700 
 701   fprintf (stderr, "\n");
 702 }
 703 template <> inline void
 704 _hb_debug_msg_va<0> (const char *what HB_UNUSED,
 705                      const void *obj HB_UNUSED,
 706                      const char *func HB_UNUSED,
 707                      bool indented HB_UNUSED,
 708                      unsigned int level HB_UNUSED,
 709                      int level_dir HB_UNUSED,
 710                      const char *message HB_UNUSED,
 711                      va_list ap HB_UNUSED) {}
 712 
 713 template <int max_level> static inline void
 714 _hb_debug_msg (const char *what,
 715                const void *obj,
 716                const char *func,
 717                bool indented,
 718                unsigned int level,
 719                int level_dir,
 720                const char *message,
 721                ...) HB_PRINTF_FUNC(7, 8);
 722 template <int max_level> static inline void
 723 _hb_debug_msg (const char *what,
 724                const void *obj,
 725                const char *func,
 726                bool indented,
 727                unsigned int level,
 728                int level_dir,
 729                const char *message,
 730                ...)
 731 {
 732   va_list ap;
 733   va_start (ap, message);
 734   _hb_debug_msg_va<max_level> (what, obj, func, indented, level, level_dir, message, ap);
 735   va_end (ap);
 736 }
 737 template <> inline void
 738 _hb_debug_msg<0> (const char *what HB_UNUSED,
 739                   const void *obj HB_UNUSED,
 740                   const char *func HB_UNUSED,
 741                   bool indented HB_UNUSED,
 742                   unsigned int level HB_UNUSED,
 743                   int level_dir HB_UNUSED,
 744                   const char *message HB_UNUSED,
 745                   ...) HB_PRINTF_FUNC(7, 8);
 746 template <> inline void
 747 _hb_debug_msg<0> (const char *what HB_UNUSED,
 748                   const void *obj HB_UNUSED,
 749                   const char *func HB_UNUSED,
 750                   bool indented HB_UNUSED,
 751                   unsigned int level HB_UNUSED,
 752                   int level_dir HB_UNUSED,
 753                   const char *message HB_UNUSED,
 754                   ...) {}
 755 
 756 #define DEBUG_MSG_LEVEL(WHAT, OBJ, LEVEL, LEVEL_DIR, ...)       _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), NULL,    true, (LEVEL), (LEVEL_DIR), __VA_ARGS__)
 757 #define DEBUG_MSG(WHAT, OBJ, ...)                               _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), NULL,    false, 0, 0, __VA_ARGS__)
 758 #define DEBUG_MSG_FUNC(WHAT, OBJ, ...)                          _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), HB_FUNC, false, 0, 0, __VA_ARGS__)
 759 
 760 
 761 /*
 762  * Printer
 763  */
 764 
 765 template <typename T>
 766 struct hb_printer_t {
 767   const char *print (const T&) { return "something"; }
 768 };
 769 
 770 template <>
 771 struct hb_printer_t<bool> {
 772   const char *print (bool v) { return v ? "true" : "false"; }
 773 };
 774 
 775 template <>
 776 struct hb_printer_t<hb_void_t> {
 777   const char *print (hb_void_t) { return ""; }
 778 };
 779 
 780 
 781 /*
 782  * Trace
 783  */
 784 
 785 template <typename T>
 786 static inline void _hb_warn_no_return (bool returned)
 787 {
 788   if (unlikely (!returned)) {
 789     fprintf (stderr, "OUCH, returned with no call to return_trace().  This is a bug, please report.\n");
 790   }
 791 }
 792 template <>
 793 /*static*/ inline void _hb_warn_no_return<hb_void_t> (bool returned HB_UNUSED)
 794 {}
 795 
 796 template <int max_level, typename ret_t>
 797 struct hb_auto_trace_t {
 798   explicit inline hb_auto_trace_t (unsigned int *plevel_,
 799                                    const char *what_,
 800                                    const void *obj_,
 801                                    const char *func,
 802                                    const char *message,
 803                                    ...) : plevel (plevel_), what (what_), obj (obj_), returned (false)
 804   {
 805     if (plevel) ++*plevel;
 806 
 807     va_list ap;
 808     va_start (ap, message);
 809     _hb_debug_msg_va<max_level> (what, obj, func, true, plevel ? *plevel : 0, +1, message, ap);
 810     va_end (ap);
 811   }
 812   inline ~hb_auto_trace_t (void)
 813   {
 814     _hb_warn_no_return<ret_t> (returned);
 815     if (!returned) {
 816       _hb_debug_msg<max_level> (what, obj, NULL, true, plevel ? *plevel : 1, -1, " ");
 817     }
 818     if (plevel) --*plevel;
 819   }
 820 
 821   inline ret_t ret (ret_t v, unsigned int line = 0)
 822   {
 823     if (unlikely (returned)) {
 824       fprintf (stderr, "OUCH, double calls to return_trace().  This is a bug, please report.\n");
 825       return v;
 826     }
 827 
 828     _hb_debug_msg<max_level> (what, obj, NULL, true, plevel ? *plevel : 1, -1,
 829                               "return %s (line %d)",
 830                               hb_printer_t<ret_t>().print (v), line);
 831     if (plevel) --*plevel;
 832     plevel = NULL;
 833     returned = true;
 834     return v;
 835   }
 836 
 837   private:
 838   unsigned int *plevel;
 839   const char *what;
 840   const void *obj;
 841   bool returned;
 842 };
 843 template <typename ret_t> /* Optimize when tracing is disabled */
 844 struct hb_auto_trace_t<0, ret_t> {
 845   explicit inline hb_auto_trace_t (unsigned int *plevel_ HB_UNUSED,
 846                                    const char *what HB_UNUSED,
 847                                    const void *obj HB_UNUSED,
 848                                    const char *func HB_UNUSED,
 849                                    const char *message HB_UNUSED,
 850                                    ...) {}
 851 
 852   inline ret_t ret (ret_t v, unsigned int line HB_UNUSED = 0) { return v; }
 853 };
 854 
 855 #define return_trace(RET) return trace.ret (RET, __LINE__)
 856 
 857 /* Misc */
 858 
 859 template <typename T> class hb_assert_unsigned_t;
 860 template <> class hb_assert_unsigned_t<unsigned char> {};
 861 template <> class hb_assert_unsigned_t<unsigned short> {};
 862 template <> class hb_assert_unsigned_t<unsigned int> {};
 863 template <> class hb_assert_unsigned_t<unsigned long> {};
 864 
 865 template <typename T> static inline bool
 866 hb_in_range (T u, T lo, T hi)
 867 {
 868   /* The sizeof() is here to force template instantiation.
 869    * I'm sure there are better ways to do this but can't think of
 870    * one right now.  Declaring a variable won't work as HB_UNUSED
 871    * is unusable on some platforms and unused types are less likely
 872    * to generate a warning than unused variables. */
 873   ASSERT_STATIC (sizeof (hb_assert_unsigned_t<T>) >= 0);
 874 
 875   /* The casts below are important as if T is smaller than int,
 876    * the subtract results will become a signed int! */
 877   return (T)(u - lo) <= (T)(hi - lo);
 878 }
 879 
 880 template <typename T> static inline bool
 881 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2)
 882 {
 883   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2);
 884 }
 885 
 886 template <typename T> static inline bool
 887 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2, T lo3, T hi3)
 888 {
 889   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2) || hb_in_range (u, lo3, hi3);
 890 }
 891 
 892 
 893 /* Useful for set-operations on small enums.
 894  * For example, for testing "x ∈ {x1, x2, x3}" use:
 895  * (FLAG_SAFE(x) & (FLAG(x1) | FLAG(x2) | FLAG(x3)))
 896  */
 897 #define FLAG(x) (ASSERT_STATIC_EXPR_ZERO ((x) < 32) + (1U << (x)))
 898 #define FLAG_SAFE(x) (1U << (x))
 899 #define FLAG_UNSAFE(x) ((x) < 32 ? FLAG_SAFE(x) : 0)
 900 #define FLAG_RANGE(x,y) (ASSERT_STATIC_EXPR_ZERO ((x) < (y)) + FLAG(y+1) - FLAG(x))
 901 
 902 
 903 template <typename T, typename T2> static inline void
 904 hb_stable_sort (T *array, unsigned int len, int(*compar)(const T *, const T *), T2 *array2)
 905 {
 906   for (unsigned int i = 1; i < len; i++)
 907   {
 908     unsigned int j = i;
 909     while (j && compar (&array[j - 1], &array[i]) > 0)
 910       j--;
 911     if (i == j)
 912       continue;
 913     /* Move item i to occupy place for item j, shift what's in between. */
 914     {
 915       T t = array[i];
 916       memmove (&array[j + 1], &array[j], (i - j) * sizeof (T));
 917       array[j] = t;
 918     }
 919     if (array2)
 920     {
 921       T2 t = array2[i];
 922       memmove (&array2[j + 1], &array2[j], (i - j) * sizeof (T2));
 923       array2[j] = t;
 924     }
 925   }
 926 }
 927 
 928 template <typename T> static inline void
 929 hb_stable_sort (T *array, unsigned int len, int(*compar)(const T *, const T *))
 930 {
 931   hb_stable_sort (array, len, compar, (int *) NULL);
 932 }
 933 
 934 static inline hb_bool_t
 935 hb_codepoint_parse (const char *s, unsigned int len, int base, hb_codepoint_t *out)
 936 {
 937   /* Pain because we don't know whether s is nul-terminated. */
 938   char buf[64];
 939   len = MIN (ARRAY_LENGTH (buf) - 1, len);
 940   strncpy (buf, s, len);
 941   buf[len] = '\0';
 942 
 943   char *end;
 944   errno = 0;
 945   unsigned long v = strtoul (buf, &end, base);
 946   if (errno) return false;
 947   if (*end) return false;
 948   *out = v;
 949   return true;
 950 }
 951 
 952 
 953 /* Global runtime options. */
 954 
 955 struct hb_options_t
 956 {
 957   unsigned int initialized : 1;
 958   unsigned int uniscribe_bug_compatible : 1;
 959 };
 960 
 961 union hb_options_union_t {
 962   unsigned int i;
 963   hb_options_t opts;
 964 };
 965 ASSERT_STATIC (sizeof (int) == sizeof (hb_options_union_t));
 966 
 967 HB_INTERNAL void
 968 _hb_options_init (void);
 969 
 970 extern HB_INTERNAL hb_options_union_t _hb_options;
 971 
 972 static inline hb_options_t
 973 hb_options (void)
 974 {
 975   if (unlikely (!_hb_options.i))
 976     _hb_options_init ();
 977 
 978   return _hb_options.opts;
 979 }
 980 
 981 
 982 #endif /* HB_PRIVATE_HH */