snappy-stubs-internal.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Copyright 2011 Google Inc. All Rights Reserved.
  2. //
  3. // Redistribution and use in source and binary forms, with or without
  4. // modification, are permitted provided that the following conditions are
  5. // met:
  6. //
  7. // * Redistributions of source code must retain the above copyright
  8. // notice, this list of conditions and the following disclaimer.
  9. // * Redistributions in binary form must reproduce the above
  10. // copyright notice, this list of conditions and the following disclaimer
  11. // in the documentation and/or other materials provided with the
  12. // distribution.
  13. // * Neither the name of Google Inc. nor the names of its
  14. // contributors may be used to endorse or promote products derived from
  15. // this software without specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Various stubs for the open-source version of Snappy.
  30. #ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
  31. #define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
  32. #ifdef HAVE_CONFIG_H
  33. #include "config.h"
  34. #endif
  35. #include <stdint.h>
  36. #include <cassert>
  37. #include <cstdlib>
  38. #include <cstring>
  39. #include <limits>
  40. #include <string>
  41. #ifdef HAVE_SYS_MMAN_H
  42. #include <sys/mman.h>
  43. #endif
  44. #ifdef HAVE_UNISTD_H
  45. #include <unistd.h>
  46. #endif
  47. #if defined(_MSC_VER)
  48. #include <intrin.h>
  49. #endif // defined(_MSC_VER)
  50. #ifndef __has_feature
  51. #define __has_feature(x) 0
  52. #endif
  53. #if __has_feature(memory_sanitizer)
  54. #include <sanitizer/msan_interface.h>
  55. #define SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \
  56. __msan_unpoison((address), (size))
  57. #else
  58. #define SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) /* empty */
  59. #endif // __has_feature(memory_sanitizer)
  60. #include "snappy-stubs-public.h"
  61. // Used to enable 64-bit optimized versions of some routines.
  62. #if defined(__PPC64__) || defined(__powerpc64__)
  63. #define ARCH_PPC 1
  64. #elif defined(__aarch64__) || defined(_M_ARM64)
  65. #define ARCH_ARM 1
  66. #endif
  67. // Needed by OS X, among others.
  68. #ifndef MAP_ANONYMOUS
  69. #define MAP_ANONYMOUS MAP_ANON
  70. #endif
  71. // The size of an array, if known at compile-time.
  72. // Will give unexpected results if used on a pointer.
  73. // We undefine it first, since some compilers already have a definition.
  74. #ifdef ARRAYSIZE
  75. #undef ARRAYSIZE
  76. #endif
  77. #define ARRAYSIZE(a) int{sizeof(a) / sizeof(*(a))}
  78. // Static prediction hints.
  79. #ifdef HAVE_BUILTIN_EXPECT
  80. #define SNAPPY_PREDICT_FALSE(x) (__builtin_expect(x, 0))
  81. #define SNAPPY_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
  82. #else
  83. #define SNAPPY_PREDICT_FALSE(x) x
  84. #define SNAPPY_PREDICT_TRUE(x) x
  85. #endif
  86. // Inlining hints.
  87. #ifdef HAVE_ATTRIBUTE_ALWAYS_INLINE
  88. #define SNAPPY_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline))
  89. #else
  90. #define SNAPPY_ATTRIBUTE_ALWAYS_INLINE
  91. #endif
  92. // Stubbed version of ABSL_FLAG.
  93. //
  94. // In the open source version, flags can only be changed at compile time.
  95. #define SNAPPY_FLAG(flag_type, flag_name, default_value, help) \
  96. flag_type FLAGS_ ## flag_name = default_value
  97. namespace snappy {
  98. // Stubbed version of absl::GetFlag().
  99. template <typename T>
  100. inline T GetFlag(T flag) { return flag; }
  101. static const uint32_t kuint32max = std::numeric_limits<uint32_t>::max();
  102. static const int64_t kint64max = std::numeric_limits<int64_t>::max();
  103. // Potentially unaligned loads and stores.
  104. inline uint16_t UNALIGNED_LOAD16(const void *p) {
  105. // Compiles to a single movzx/ldrh on clang/gcc/msvc.
  106. uint16_t v;
  107. std::memcpy(&v, p, sizeof(v));
  108. return v;
  109. }
  110. inline uint32_t UNALIGNED_LOAD32(const void *p) {
  111. // Compiles to a single mov/ldr on clang/gcc/msvc.
  112. uint32_t v;
  113. std::memcpy(&v, p, sizeof(v));
  114. return v;
  115. }
  116. inline uint64_t UNALIGNED_LOAD64(const void *p) {
  117. // Compiles to a single mov/ldr on clang/gcc/msvc.
  118. uint64_t v;
  119. std::memcpy(&v, p, sizeof(v));
  120. return v;
  121. }
  122. inline void UNALIGNED_STORE16(void *p, uint16_t v) {
  123. // Compiles to a single mov/strh on clang/gcc/msvc.
  124. std::memcpy(p, &v, sizeof(v));
  125. }
  126. inline void UNALIGNED_STORE32(void *p, uint32_t v) {
  127. // Compiles to a single mov/str on clang/gcc/msvc.
  128. std::memcpy(p, &v, sizeof(v));
  129. }
  130. inline void UNALIGNED_STORE64(void *p, uint64_t v) {
  131. // Compiles to a single mov/str on clang/gcc/msvc.
  132. std::memcpy(p, &v, sizeof(v));
  133. }
  134. // Convert to little-endian storage, opposite of network format.
  135. // Convert x from host to little endian: x = LittleEndian.FromHost(x);
  136. // convert x from little endian to host: x = LittleEndian.ToHost(x);
  137. //
  138. // Store values into unaligned memory converting to little endian order:
  139. // LittleEndian.Store16(p, x);
  140. //
  141. // Load unaligned values stored in little endian converting to host order:
  142. // x = LittleEndian.Load16(p);
  143. class LittleEndian {
  144. public:
  145. // Functions to do unaligned loads and stores in little-endian order.
  146. static inline uint16_t Load16(const void *ptr) {
  147. const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
  148. // Compiles to a single mov/str on recent clang and gcc.
  149. return (static_cast<uint16_t>(buffer[0])) |
  150. (static_cast<uint16_t>(buffer[1]) << 8);
  151. }
  152. static inline uint32_t Load32(const void *ptr) {
  153. const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
  154. // Compiles to a single mov/str on recent clang and gcc.
  155. return (static_cast<uint32_t>(buffer[0])) |
  156. (static_cast<uint32_t>(buffer[1]) << 8) |
  157. (static_cast<uint32_t>(buffer[2]) << 16) |
  158. (static_cast<uint32_t>(buffer[3]) << 24);
  159. }
  160. static inline uint64_t Load64(const void *ptr) {
  161. const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
  162. // Compiles to a single mov/str on recent clang and gcc.
  163. return (static_cast<uint64_t>(buffer[0])) |
  164. (static_cast<uint64_t>(buffer[1]) << 8) |
  165. (static_cast<uint64_t>(buffer[2]) << 16) |
  166. (static_cast<uint64_t>(buffer[3]) << 24) |
  167. (static_cast<uint64_t>(buffer[4]) << 32) |
  168. (static_cast<uint64_t>(buffer[5]) << 40) |
  169. (static_cast<uint64_t>(buffer[6]) << 48) |
  170. (static_cast<uint64_t>(buffer[7]) << 56);
  171. }
  172. static inline void Store16(void *dst, uint16_t value) {
  173. uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
  174. // Compiles to a single mov/str on recent clang and gcc.
  175. buffer[0] = static_cast<uint8_t>(value);
  176. buffer[1] = static_cast<uint8_t>(value >> 8);
  177. }
  178. static void Store32(void *dst, uint32_t value) {
  179. uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
  180. // Compiles to a single mov/str on recent clang and gcc.
  181. buffer[0] = static_cast<uint8_t>(value);
  182. buffer[1] = static_cast<uint8_t>(value >> 8);
  183. buffer[2] = static_cast<uint8_t>(value >> 16);
  184. buffer[3] = static_cast<uint8_t>(value >> 24);
  185. }
  186. static void Store64(void* dst, uint64_t value) {
  187. uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
  188. // Compiles to a single mov/str on recent clang and gcc.
  189. buffer[0] = static_cast<uint8_t>(value);
  190. buffer[1] = static_cast<uint8_t>(value >> 8);
  191. buffer[2] = static_cast<uint8_t>(value >> 16);
  192. buffer[3] = static_cast<uint8_t>(value >> 24);
  193. buffer[4] = static_cast<uint8_t>(value >> 32);
  194. buffer[5] = static_cast<uint8_t>(value >> 40);
  195. buffer[6] = static_cast<uint8_t>(value >> 48);
  196. buffer[7] = static_cast<uint8_t>(value >> 56);
  197. }
  198. static inline constexpr bool IsLittleEndian() {
  199. #if defined(SNAPPY_IS_BIG_ENDIAN)
  200. return false;
  201. #else
  202. return true;
  203. #endif // defined(SNAPPY_IS_BIG_ENDIAN)
  204. }
  205. };
  206. // Some bit-manipulation functions.
  207. class Bits {
  208. public:
  209. // Return floor(log2(n)) for positive integer n.
  210. static int Log2FloorNonZero(uint32_t n);
  211. // Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0.
  212. static int Log2Floor(uint32_t n);
  213. // Return the first set least / most significant bit, 0-indexed. Returns an
  214. // undefined value if n == 0. FindLSBSetNonZero() is similar to ffs() except
  215. // that it's 0-indexed.
  216. static int FindLSBSetNonZero(uint32_t n);
  217. static int FindLSBSetNonZero64(uint64_t n);
  218. private:
  219. // No copying
  220. Bits(const Bits&);
  221. void operator=(const Bits&);
  222. };
  223. #if defined(HAVE_BUILTIN_CTZ)
  224. inline int Bits::Log2FloorNonZero(uint32_t n) {
  225. assert(n != 0);
  226. // (31 ^ x) is equivalent to (31 - x) for x in [0, 31]. An easy proof
  227. // represents subtraction in base 2 and observes that there's no carry.
  228. //
  229. // GCC and Clang represent __builtin_clz on x86 as 31 ^ _bit_scan_reverse(x).
  230. // Using "31 ^" here instead of "31 -" allows the optimizer to strip the
  231. // function body down to _bit_scan_reverse(x).
  232. return 31 ^ __builtin_clz(n);
  233. }
  234. inline int Bits::Log2Floor(uint32_t n) {
  235. return (n == 0) ? -1 : Bits::Log2FloorNonZero(n);
  236. }
  237. inline int Bits::FindLSBSetNonZero(uint32_t n) {
  238. assert(n != 0);
  239. return __builtin_ctz(n);
  240. }
  241. #elif defined(_MSC_VER)
  242. inline int Bits::Log2FloorNonZero(uint32_t n) {
  243. assert(n != 0);
  244. // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
  245. unsigned long where;
  246. _BitScanReverse(&where, n);
  247. return static_cast<int>(where);
  248. }
  249. inline int Bits::Log2Floor(uint32_t n) {
  250. // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
  251. unsigned long where;
  252. if (_BitScanReverse(&where, n))
  253. return static_cast<int>(where);
  254. return -1;
  255. }
  256. inline int Bits::FindLSBSetNonZero(uint32_t n) {
  257. assert(n != 0);
  258. // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
  259. unsigned long where;
  260. if (_BitScanForward(&where, n))
  261. return static_cast<int>(where);
  262. return 32;
  263. }
  264. #else // Portable versions.
  265. inline int Bits::Log2FloorNonZero(uint32_t n) {
  266. assert(n != 0);
  267. int log = 0;
  268. uint32_t value = n;
  269. for (int i = 4; i >= 0; --i) {
  270. int shift = (1 << i);
  271. uint32_t x = value >> shift;
  272. if (x != 0) {
  273. value = x;
  274. log += shift;
  275. }
  276. }
  277. assert(value == 1);
  278. return log;
  279. }
  280. inline int Bits::Log2Floor(uint32_t n) {
  281. return (n == 0) ? -1 : Bits::Log2FloorNonZero(n);
  282. }
  283. inline int Bits::FindLSBSetNonZero(uint32_t n) {
  284. assert(n != 0);
  285. int rc = 31;
  286. for (int i = 4, shift = 1 << 4; i >= 0; --i) {
  287. const uint32_t x = n << shift;
  288. if (x != 0) {
  289. n = x;
  290. rc -= shift;
  291. }
  292. shift >>= 1;
  293. }
  294. return rc;
  295. }
  296. #endif // End portable versions.
  297. #if defined(HAVE_BUILTIN_CTZ)
  298. inline int Bits::FindLSBSetNonZero64(uint64_t n) {
  299. assert(n != 0);
  300. return __builtin_ctzll(n);
  301. }
  302. #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
  303. // _BitScanForward64() is only available on x64 and ARM64.
  304. inline int Bits::FindLSBSetNonZero64(uint64_t n) {
  305. assert(n != 0);
  306. // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
  307. unsigned long where;
  308. if (_BitScanForward64(&where, n))
  309. return static_cast<int>(where);
  310. return 64;
  311. }
  312. #else // Portable version.
  313. // FindLSBSetNonZero64() is defined in terms of FindLSBSetNonZero().
  314. inline int Bits::FindLSBSetNonZero64(uint64_t n) {
  315. assert(n != 0);
  316. const uint32_t bottombits = static_cast<uint32_t>(n);
  317. if (bottombits == 0) {
  318. // Bottom bits are zero, so scan the top bits.
  319. return 32 + FindLSBSetNonZero(static_cast<uint32_t>(n >> 32));
  320. } else {
  321. return FindLSBSetNonZero(bottombits);
  322. }
  323. }
  324. #endif // End portable version.
  325. // Variable-length integer encoding.
  326. class Varint {
  327. public:
  328. // Maximum lengths of varint encoding of uint32_t.
  329. static const int kMax32 = 5;
  330. // Attempts to parse a varint32 from a prefix of the bytes in [ptr,limit-1].
  331. // Never reads a character at or beyond limit. If a valid/terminated varint32
  332. // was found in the range, stores it in *OUTPUT and returns a pointer just
  333. // past the last byte of the varint32. Else returns NULL. On success,
  334. // "result <= limit".
  335. static const char* Parse32WithLimit(const char* ptr, const char* limit,
  336. uint32_t* OUTPUT);
  337. // REQUIRES "ptr" points to a buffer of length sufficient to hold "v".
  338. // EFFECTS Encodes "v" into "ptr" and returns a pointer to the
  339. // byte just past the last encoded byte.
  340. static char* Encode32(char* ptr, uint32_t v);
  341. // EFFECTS Appends the varint representation of "value" to "*s".
  342. static void Append32(std::string* s, uint32_t value);
  343. };
  344. inline const char* Varint::Parse32WithLimit(const char* p,
  345. const char* l,
  346. uint32_t* OUTPUT) {
  347. const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p);
  348. const unsigned char* limit = reinterpret_cast<const unsigned char*>(l);
  349. uint32_t b, result;
  350. if (ptr >= limit) return NULL;
  351. b = *(ptr++); result = b & 127; if (b < 128) goto done;
  352. if (ptr >= limit) return NULL;
  353. b = *(ptr++); result |= (b & 127) << 7; if (b < 128) goto done;
  354. if (ptr >= limit) return NULL;
  355. b = *(ptr++); result |= (b & 127) << 14; if (b < 128) goto done;
  356. if (ptr >= limit) return NULL;
  357. b = *(ptr++); result |= (b & 127) << 21; if (b < 128) goto done;
  358. if (ptr >= limit) return NULL;
  359. b = *(ptr++); result |= (b & 127) << 28; if (b < 16) goto done;
  360. return NULL; // Value is too long to be a varint32
  361. done:
  362. *OUTPUT = result;
  363. return reinterpret_cast<const char*>(ptr);
  364. }
  365. inline char* Varint::Encode32(char* sptr, uint32_t v) {
  366. // Operate on characters as unsigneds
  367. uint8_t* ptr = reinterpret_cast<uint8_t*>(sptr);
  368. static const uint8_t B = 128;
  369. if (v < (1 << 7)) {
  370. *(ptr++) = static_cast<uint8_t>(v);
  371. } else if (v < (1 << 14)) {
  372. *(ptr++) = static_cast<uint8_t>(v | B);
  373. *(ptr++) = static_cast<uint8_t>(v >> 7);
  374. } else if (v < (1 << 21)) {
  375. *(ptr++) = static_cast<uint8_t>(v | B);
  376. *(ptr++) = static_cast<uint8_t>((v >> 7) | B);
  377. *(ptr++) = static_cast<uint8_t>(v >> 14);
  378. } else if (v < (1 << 28)) {
  379. *(ptr++) = static_cast<uint8_t>(v | B);
  380. *(ptr++) = static_cast<uint8_t>((v >> 7) | B);
  381. *(ptr++) = static_cast<uint8_t>((v >> 14) | B);
  382. *(ptr++) = static_cast<uint8_t>(v >> 21);
  383. } else {
  384. *(ptr++) = static_cast<uint8_t>(v | B);
  385. *(ptr++) = static_cast<uint8_t>((v>>7) | B);
  386. *(ptr++) = static_cast<uint8_t>((v>>14) | B);
  387. *(ptr++) = static_cast<uint8_t>((v>>21) | B);
  388. *(ptr++) = static_cast<uint8_t>(v >> 28);
  389. }
  390. return reinterpret_cast<char*>(ptr);
  391. }
  392. // If you know the internal layout of the std::string in use, you can
  393. // replace this function with one that resizes the string without
  394. // filling the new space with zeros (if applicable) --
  395. // it will be non-portable but faster.
  396. inline void STLStringResizeUninitialized(std::string* s, size_t new_size) {
  397. s->resize(new_size);
  398. }
  399. // Return a mutable char* pointing to a string's internal buffer,
  400. // which may not be null-terminated. Writing through this pointer will
  401. // modify the string.
  402. //
  403. // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
  404. // next call to a string method that invalidates iterators.
  405. //
  406. // As of 2006-04, there is no standard-blessed way of getting a
  407. // mutable reference to a string's internal buffer. However, issue 530
  408. // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#530)
  409. // proposes this as the method. It will officially be part of the standard
  410. // for C++0x. This should already work on all current implementations.
  411. inline char* string_as_array(std::string* str) {
  412. return str->empty() ? NULL : &*str->begin();
  413. }
  414. } // namespace snappy
  415. #endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_