Utils.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_UTILS_HPP
  14. #define ZT_UTILS_HPP
  15. #include "Constants.hpp"
  16. #include <utility>
  17. #include <algorithm>
  18. #include <memory>
  19. namespace ZeroTier {
  20. namespace Utils {
  21. #ifndef __WINDOWS__
  22. #include <sys/mman.h>
  23. #endif
  24. // Macros to convert endian-ness at compile time for constants.
  25. #if __BYTE_ORDER == __LITTLE_ENDIAN
  26. #define ZT_CONST_TO_BE_UINT16(x) ((uint16_t)((uint16_t)((uint16_t)(x) << 8U) | (uint16_t)((uint16_t)(x) >> 8U)))
  27. #define ZT_CONST_TO_BE_UINT64(x) ( \
  28. (((uint64_t)(x) & 0x00000000000000ffULL) << 56U) | \
  29. (((uint64_t)(x) & 0x000000000000ff00ULL) << 40U) | \
  30. (((uint64_t)(x) & 0x0000000000ff0000ULL) << 24U) | \
  31. (((uint64_t)(x) & 0x00000000ff000000ULL) << 8U) | \
  32. (((uint64_t)(x) & 0x000000ff00000000ULL) >> 8U) | \
  33. (((uint64_t)(x) & 0x0000ff0000000000ULL) >> 24U) | \
  34. (((uint64_t)(x) & 0x00ff000000000000ULL) >> 40U) | \
  35. (((uint64_t)(x) & 0xff00000000000000ULL) >> 56U))
  36. #else
  37. #define ZT_CONST_TO_BE_UINT16(x) ((uint16_t)(x))
  38. #define ZT_CONST_TO_BE_UINT64(x) ((uint64_t)(x))
  39. #endif
  40. #define ZT_ROR64(x, r) (((x) >> (r)) | ((x) << (64 - (r))))
  41. #define ZT_ROL64(x, r) (((x) << (r)) | ((x) >> (64 - (r))))
  42. #define ZT_ROR32(x, r) (((x) >> (r)) | ((x) << (32 - (r))))
  43. #define ZT_ROL32(x, r) (((x) << (r)) | ((x) >> (32 - (r))))
  44. #ifdef ZT_ARCH_X64
  45. struct CPUIDRegisters
  46. {
  47. CPUIDRegisters() noexcept;
  48. bool rdrand;
  49. bool aes;
  50. bool avx;
  51. bool vaes; // implies AVX
  52. bool vpclmulqdq; // implies AVX
  53. bool avx2;
  54. bool avx512f;
  55. bool sha;
  56. bool fsrm;
  57. };
  58. extern const CPUIDRegisters CPUID;
  59. #endif
  60. /**
  61. * 256 zero bits / 32 zero bytes
  62. */
  63. extern const uint64_t ZERO256[4];
  64. /**
  65. * Hexadecimal characters 0-f
  66. */
  67. extern const char HEXCHARS[16];
  68. /**
  69. * A random integer generated at startup for Map's hash bucket calculation.
  70. */
  71. extern const uint64_t s_mapNonce;
  72. /**
  73. * Lock memory to prevent swapping out to secondary storage (if possible)
  74. *
  75. * This is used to attempt to prevent the swapping out of long-term stored secure
  76. * credentials like secret keys. It isn't supported on all platforms and may not
  77. * be absolutely guaranteed to work, but it's a countermeasure.
  78. *
  79. * @param p Memory to lock
  80. * @param l Size of memory
  81. */
  82. static ZT_INLINE void memoryLock(const void *const p, const unsigned int l) noexcept
  83. {
  84. #ifndef __WINDOWS__
  85. mlock(p, l);
  86. #endif
  87. }
  88. /**
  89. * Unlock memory locked with memoryLock()
  90. *
  91. * @param p Memory to unlock
  92. * @param l Size of memory
  93. */
  94. static ZT_INLINE void memoryUnlock(const void *const p, const unsigned int l) noexcept
  95. {
  96. #ifndef __WINDOWS__
  97. munlock(p, l);
  98. #endif
  99. }
  100. /**
  101. * Perform a time-invariant binary comparison
  102. *
  103. * @param a First binary string
  104. * @param b Second binary string
  105. * @param len Length of strings
  106. * @return True if strings are equal
  107. */
  108. bool secureEq(const void *a, const void *b, unsigned int len) noexcept;
  109. /**
  110. * Be absolutely sure to zero memory
  111. *
  112. * This uses some hacks to be totally sure the compiler does not optimize it out.
  113. *
  114. * @param ptr Memory to zero
  115. * @param len Length of memory in bytes
  116. */
  117. void burn(void *ptr, unsigned int len);
  118. /**
  119. * @param n Number to convert
  120. * @param s Buffer, at least 24 bytes in size
  121. * @return String containing 'n' in base 10 form
  122. */
  123. char *decimal(unsigned long n, char s[24]) noexcept;
  124. /**
  125. * Convert an unsigned integer into hex
  126. *
  127. * The returned pointer won't point to the start of 'buf', since
  128. * hex writing is done in reverse order.
  129. *
  130. * @param i Any unsigned integer
  131. * @param s Buffer to receive hex, must be at least (2*sizeof(i))+1 in size or overflow will occur.
  132. * @return Pointer to s containing hex string with trailing zero byte
  133. */
  134. char *hex(uint64_t i, char buf[17]) noexcept;
  135. /**
  136. * Decode an unsigned integer in hex format
  137. *
  138. * @param s String to decode, non-hex chars are ignored
  139. * @return Unsigned integer
  140. */
  141. uint64_t unhex(const char *s) noexcept;
  142. /**
  143. * Convert a byte array into hex
  144. *
  145. * @param d Bytes
  146. * @param l Length of bytes
  147. * @param s String buffer, must be at least (l*2)+1 in size or overflow will occur
  148. * @return Pointer to filled string buffer
  149. */
  150. char *hex(const void *d, unsigned int l, char *s) noexcept;
  151. /**
  152. * Decode a hex string
  153. *
  154. * @param h Hex C-string (non hex chars are ignored)
  155. * @param hlen Maximum length of string (will stop at terminating zero)
  156. * @param buf Output buffer
  157. * @param buflen Length of output buffer
  158. * @return Number of written bytes
  159. */
  160. unsigned int unhex(const char *h, unsigned int hlen, void *buf, unsigned int buflen) noexcept;
  161. /**
  162. * Generate secure random bytes
  163. *
  164. * This will try to use whatever OS sources of entropy are available. It's
  165. * guarded by an internal mutex so it's thread-safe.
  166. *
  167. * @param buf Buffer to fill
  168. * @param bytes Number of random bytes to generate
  169. */
  170. void getSecureRandom(void *buf, unsigned int bytes) noexcept;
  171. /**
  172. * @return Secure random 64-bit integer
  173. */
  174. uint64_t getSecureRandomU64() noexcept;
  175. /**
  176. * Encode string to base32
  177. *
  178. * @param data Binary data to encode
  179. * @param length Length of data in bytes
  180. * @param result Result buffer
  181. * @param bufSize Size of result buffer
  182. * @return Number of bytes written
  183. */
  184. int b32e(const uint8_t *data, int length, char *result, int bufSize) noexcept;
  185. /**
  186. * Decode base32 string
  187. *
  188. * @param encoded C-string in base32 format (non-base32 characters are ignored)
  189. * @param result Result buffer
  190. * @param bufSize Size of result buffer
  191. * @return Number of bytes written or -1 on error
  192. */
  193. int b32d(const char *encoded, uint8_t *result, int bufSize) noexcept;
  194. /**
  195. * Get a non-cryptographic random integer.
  196. *
  197. * This should never be used for cryptographic use cases, not even for choosing
  198. * message nonce/IV values if they should not repeat. It should only be used when
  199. * a fast and potentially "dirty" random source is needed.
  200. */
  201. uint64_t random() noexcept;
  202. /**
  203. * Perform a safe C string copy, ALWAYS null-terminating the result
  204. *
  205. * This will never ever EVER result in dest[] not being null-terminated
  206. * regardless of any input parameter (other than len==0 which is invalid).
  207. *
  208. * @param dest Destination buffer (must not be NULL)
  209. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  210. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  211. * @return True on success, false on overflow (buffer will still be 0-terminated)
  212. */
  213. bool scopy(char *dest, unsigned int len, const char *src) noexcept;
  214. /**
  215. * Mix bits in a 64-bit integer (non-cryptographic, for hash tables)
  216. *
  217. * https://nullprogram.com/blog/2018/07/31/
  218. *
  219. * @param x Integer to mix
  220. * @return Hashed value
  221. */
  222. static ZT_INLINE uint64_t hash64(uint64_t x) noexcept
  223. {
  224. x ^= x >> 30U;
  225. x *= 0xbf58476d1ce4e5b9ULL;
  226. x ^= x >> 27U;
  227. x *= 0x94d049bb133111ebULL;
  228. x ^= x >> 31U;
  229. return x;
  230. }
  231. /**
  232. * Mix bits in a 32-bit integer (non-cryptographic, for hash tables)
  233. *
  234. * https://nullprogram.com/blog/2018/07/31/
  235. *
  236. * @param x Integer to mix
  237. * @return Hashed value
  238. */
  239. static ZT_INLINE uint32_t hash32(uint32_t x) noexcept
  240. {
  241. x ^= x >> 16U;
  242. x *= 0x7feb352dU;
  243. x ^= x >> 15U;
  244. x *= 0x846ca68bU;
  245. x ^= x >> 16U;
  246. return x;
  247. }
  248. /**
  249. * Check if a buffer's contents are all zero
  250. */
  251. static ZT_INLINE bool allZero(const void *const b, unsigned int l) noexcept
  252. {
  253. for (unsigned int i = 0; i < l; ++i) {
  254. if (reinterpret_cast<const uint8_t *>(b)[i] != 0)
  255. return false;
  256. }
  257. return true;
  258. }
  259. /**
  260. * Wrapper around reentrant strtok functions, which differ in name by platform
  261. *
  262. * @param str String to tokenize or NULL for subsequent calls
  263. * @param delim Delimiter
  264. * @param saveptr Pointer to pointer where function can save state
  265. * @return Next token or NULL if none
  266. */
  267. static ZT_INLINE char *stok(char *str, const char *delim, char **saveptr) noexcept
  268. {
  269. #ifdef __WINDOWS__
  270. return strtok_s(str,delim,saveptr);
  271. #else
  272. return strtok_r(str, delim, saveptr);
  273. #endif
  274. }
  275. static ZT_INLINE unsigned int strToUInt(const char *s) noexcept
  276. {
  277. return (unsigned int)strtoul(s, nullptr, 10);
  278. }
  279. static ZT_INLINE unsigned long long hexStrToU64(const char *s) noexcept
  280. {
  281. #ifdef __WINDOWS__
  282. return (unsigned long long)_strtoui64(s,nullptr,16);
  283. #else
  284. return strtoull(s, nullptr, 16);
  285. #endif
  286. }
  287. /**
  288. * Compute 32-bit FNV-1a checksum
  289. *
  290. * See: http://www.isthe.com/chongo/tech/comp/fnv/
  291. *
  292. * @param data Data to checksum
  293. * @param len Length of data
  294. * @return FNV1a checksum
  295. */
  296. static ZT_INLINE uint32_t fnv1a32(const void *const data, const unsigned int len) noexcept
  297. {
  298. uint32_t h = 0x811c9dc5;
  299. const uint32_t p = 0x01000193;
  300. for (unsigned int i = 0; i < len; ++i)
  301. h = (h ^ (uint32_t)reinterpret_cast<const uint8_t *>(data)[i]) * p;
  302. return h;
  303. }
  304. #ifdef __GNUC__
  305. static ZT_INLINE unsigned int countBits(const uint8_t v) noexcept
  306. { return (unsigned int)__builtin_popcount((unsigned int)v); }
  307. static ZT_INLINE unsigned int countBits(const uint16_t v) noexcept
  308. { return (unsigned int)__builtin_popcount((unsigned int)v); }
  309. static ZT_INLINE unsigned int countBits(const uint32_t v) noexcept
  310. { return (unsigned int)__builtin_popcountl((unsigned long)v); }
  311. static ZT_INLINE unsigned int countBits(const uint64_t v) noexcept
  312. { return (unsigned int)__builtin_popcountll((unsigned long long)v); }
  313. #else
  314. template<typename T>
  315. static ZT_INLINE unsigned int countBits(T v) noexcept
  316. {
  317. v = v - ((v >> 1) & (T)~(T)0/3);
  318. v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);
  319. v = (v + (v >> 4)) & (T)~(T)0/255*15;
  320. return (unsigned int)((v * ((~((T)0))/((T)255))) >> ((sizeof(T) - 1) * 8));
  321. }
  322. #endif
  323. /**
  324. * Unconditionally swap bytes regardless of host byte order
  325. *
  326. * @param n Integer to swap
  327. * @return Integer with bytes reversed
  328. */
  329. static ZT_INLINE uint64_t swapBytes(const uint64_t n) noexcept
  330. {
  331. #ifdef __GNUC__
  332. return __builtin_bswap64(n);
  333. #else
  334. #ifdef _MSC_VER
  335. return (uint64_t)_byteswap_uint64((unsigned __int64)n);
  336. #else
  337. return (
  338. ((n & 0x00000000000000ffULL) << 56) |
  339. ((n & 0x000000000000ff00ULL) << 40) |
  340. ((n & 0x0000000000ff0000ULL) << 24) |
  341. ((n & 0x00000000ff000000ULL) << 8) |
  342. ((n & 0x000000ff00000000ULL) >> 8) |
  343. ((n & 0x0000ff0000000000ULL) >> 24) |
  344. ((n & 0x00ff000000000000ULL) >> 40) |
  345. ((n & 0xff00000000000000ULL) >> 56)
  346. );
  347. #endif
  348. #endif
  349. }
  350. /**
  351. * Unconditionally swap bytes regardless of host byte order
  352. *
  353. * @param n Integer to swap
  354. * @return Integer with bytes reversed
  355. */
  356. static ZT_INLINE uint32_t swapBytes(const uint32_t n) noexcept
  357. {
  358. #if defined(__GNUC__)
  359. return __builtin_bswap32(n);
  360. #else
  361. #ifdef _MSC_VER
  362. return (uint32_t)_byteswap_ulong((unsigned long)n);
  363. #else
  364. return htonl(n);
  365. #endif
  366. #endif
  367. }
  368. /**
  369. * Unconditionally swap bytes regardless of host byte order
  370. *
  371. * @param n Integer to swap
  372. * @return Integer with bytes reversed
  373. */
  374. static ZT_INLINE uint16_t swapBytes(const uint16_t n) noexcept
  375. {
  376. #if defined(__GNUC__)
  377. return __builtin_bswap16(n);
  378. #else
  379. #ifdef _MSC_VER
  380. return (uint16_t)_byteswap_ushort((unsigned short)n);
  381. #else
  382. return htons(n);
  383. #endif
  384. #endif
  385. }
  386. // These are helper adapters to load and swap integer types special cased by size
  387. // to work with all typedef'd variants, signed/unsigned, etc.
  388. template< typename I, unsigned int S >
  389. class _swap_bytes_bysize;
  390. template< typename I >
  391. class _swap_bytes_bysize< I, 1 >
  392. {
  393. public:
  394. static ZT_INLINE I s(const I n) noexcept
  395. { return n; }
  396. };
  397. template< typename I >
  398. class _swap_bytes_bysize< I, 2 >
  399. {
  400. public:
  401. static ZT_INLINE I s(const I n) noexcept
  402. { return (I)swapBytes((uint16_t)n); }
  403. };
  404. template< typename I >
  405. class _swap_bytes_bysize< I, 4 >
  406. {
  407. public:
  408. static ZT_INLINE I s(const I n) noexcept
  409. { return (I)swapBytes((uint32_t)n); }
  410. };
  411. template< typename I >
  412. class _swap_bytes_bysize< I, 8 >
  413. {
  414. public:
  415. static ZT_INLINE I s(const I n) noexcept
  416. { return (I)swapBytes((uint64_t)n); }
  417. };
  418. template< typename I, unsigned int S >
  419. class _load_be_bysize;
  420. template< typename I >
  421. class _load_be_bysize< I, 1 >
  422. {
  423. public:
  424. static ZT_INLINE I l(const uint8_t *const p) noexcept
  425. { return p[0]; }
  426. };
  427. template< typename I >
  428. class _load_be_bysize< I, 2 >
  429. {
  430. public:
  431. static ZT_INLINE I l(const uint8_t *const p) noexcept
  432. { return (I)(((unsigned int)p[0] << 8U) | (unsigned int)p[1]); }
  433. };
  434. template< typename I >
  435. class _load_be_bysize< I, 4 >
  436. {
  437. public:
  438. static ZT_INLINE I l(const uint8_t *const p) noexcept
  439. { return (I)(((uint32_t)p[0] << 24U) | ((uint32_t)p[1] << 16U) | ((uint32_t)p[2] << 8U) | (uint32_t)p[3]); }
  440. };
  441. template< typename I >
  442. class _load_be_bysize< I, 8 >
  443. {
  444. public:
  445. static ZT_INLINE I l(const uint8_t *const p) noexcept
  446. { return (I)(((uint64_t)p[0] << 56U) | ((uint64_t)p[1] << 48U) | ((uint64_t)p[2] << 40U) | ((uint64_t)p[3] << 32U) | ((uint64_t)p[4] << 24U) | ((uint64_t)p[5] << 16U) | ((uint64_t)p[6] << 8U) | (uint64_t)p[7]); }
  447. };
  448. template< typename I, unsigned int S >
  449. class _load_le_bysize;
  450. template< typename I >
  451. class _load_le_bysize< I, 1 >
  452. {
  453. public:
  454. static ZT_INLINE I l(const uint8_t *const p) noexcept
  455. { return p[0]; }
  456. };
  457. template< typename I >
  458. class _load_le_bysize< I, 2 >
  459. {
  460. public:
  461. static ZT_INLINE I l(const uint8_t *const p) noexcept
  462. { return (I)((unsigned int)p[0] | ((unsigned int)p[1] << 8U)); }
  463. };
  464. template< typename I >
  465. class _load_le_bysize< I, 4 >
  466. {
  467. public:
  468. static ZT_INLINE I l(const uint8_t *const p) noexcept
  469. { return (I)((uint32_t)p[0] | ((uint32_t)p[1] << 8U) | ((uint32_t)p[2] << 16U) | ((uint32_t)p[3] << 24U)); }
  470. };
  471. template< typename I >
  472. class _load_le_bysize< I, 8 >
  473. {
  474. public:
  475. static ZT_INLINE I l(const uint8_t *const p) noexcept
  476. { return (I)((uint64_t)p[0] | ((uint64_t)p[1] << 8U) | ((uint64_t)p[2] << 16U) | ((uint64_t)p[3] << 24U) | ((uint64_t)p[4] << 32U) | ((uint64_t)p[5] << 40U) | ((uint64_t)p[6] << 48U) | ((uint64_t)p[7]) << 56U); }
  477. };
  478. /**
  479. * Convert any signed or unsigned integer type to big-endian ("network") byte order
  480. *
  481. * @tparam I Integer type (usually inferred)
  482. * @param n Value to convert
  483. * @return Value in big-endian order
  484. */
  485. template< typename I >
  486. static ZT_INLINE I hton(const I n) noexcept
  487. {
  488. #if __BYTE_ORDER == __LITTLE_ENDIAN
  489. return _swap_bytes_bysize< I, sizeof(I) >::s(n);
  490. #else
  491. return n;
  492. #endif
  493. }
  494. /**
  495. * Convert any signed or unsigned integer type to host byte order from big-endian ("network") byte order
  496. *
  497. * @tparam I Integer type (usually inferred)
  498. * @param n Value to convert
  499. * @return Value in host byte order
  500. */
  501. template< typename I >
  502. static ZT_INLINE I ntoh(const I n) noexcept
  503. {
  504. #if __BYTE_ORDER == __LITTLE_ENDIAN
  505. return _swap_bytes_bysize< I, sizeof(I) >::s(n);
  506. #else
  507. return n;
  508. #endif
  509. }
  510. /**
  511. * Copy bits from memory into an integer type without modifying their order
  512. *
  513. * @tparam I Type to load
  514. * @param p Byte stream, must be at least sizeof(I) in size
  515. * @return Loaded raw integer
  516. */
  517. template< typename I >
  518. static ZT_INLINE I loadAsIsEndian(const void *const p) noexcept
  519. {
  520. #ifdef ZT_NO_UNALIGNED_ACCESS
  521. I tmp;
  522. for(int i=0;i<(int)sizeof(I);++i)
  523. reinterpret_cast<uint8_t *>(&tmp)[i] = reinterpret_cast<const uint8_t *>(p)[i];
  524. return tmp;
  525. #else
  526. return *reinterpret_cast<const I *>(p);
  527. #endif
  528. }
  529. /**
  530. * Copy bits from memory into an integer type without modifying their order
  531. *
  532. * @tparam I Type to store
  533. * @param p Byte array (must be at least sizeof(I))
  534. * @param i Integer to store
  535. */
  536. template< typename I >
  537. static ZT_INLINE void storeAsIsEndian(void *const p, const I i) noexcept
  538. {
  539. #ifdef ZT_NO_UNALIGNED_ACCESS
  540. for(unsigned int k=0;k<sizeof(I);++k)
  541. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[k];
  542. #else
  543. *reinterpret_cast<I *>(p) = i;
  544. #endif
  545. }
  546. /**
  547. * Decode a big-endian value from a byte stream
  548. *
  549. * @tparam I Type to decode (should be unsigned e.g. uint32_t or uint64_t)
  550. * @param p Byte stream, must be at least sizeof(I) in size
  551. * @return Decoded integer
  552. */
  553. template< typename I >
  554. static ZT_INLINE I loadBigEndian(const void *const p) noexcept
  555. {
  556. #ifdef ZT_NO_UNALIGNED_ACCESS
  557. return _load_be_bysize<I,sizeof(I)>::l(reinterpret_cast<const uint8_t *>(p));
  558. #else
  559. return ntoh(*reinterpret_cast<const I *>(p));
  560. #endif
  561. }
  562. /**
  563. * Save an integer in big-endian format
  564. *
  565. * @tparam I Integer type to store (usually inferred)
  566. * @param p Byte stream to write (must be at least sizeof(I))
  567. * #param i Integer to write
  568. */
  569. template< typename I >
  570. static ZT_INLINE void storeBigEndian(void *const p, I i) noexcept
  571. {
  572. #ifdef ZT_NO_UNALIGNED_ACCESS
  573. storeAsIsEndian(p,hton(i));
  574. #else
  575. *reinterpret_cast<I *>(p) = hton(i);
  576. #endif
  577. }
  578. /**
  579. * Decode a little-endian value from a byte stream
  580. *
  581. * @tparam I Type to decode
  582. * @param p Byte stream, must be at least sizeof(I) in size
  583. * @return Decoded integer
  584. */
  585. template< typename I >
  586. static ZT_INLINE I loadLittleEndian(const void *const p) noexcept
  587. {
  588. #if __BYTE_ORDER == __BIG_ENDIAN || defined(ZT_NO_UNALIGNED_ACCESS)
  589. return _load_le_bysize<I,sizeof(I)>::l(reinterpret_cast<const uint8_t *>(p));
  590. #else
  591. return *reinterpret_cast<const I *>(p);
  592. #endif
  593. }
  594. /**
  595. * Save an integer in little-endian format
  596. *
  597. * @tparam I Integer type to store (usually inferred)
  598. * @param p Byte stream to write (must be at least sizeof(I))
  599. * #param i Integer to write
  600. */
  601. template< typename I >
  602. static ZT_INLINE void storeLittleEndian(void *const p, const I i) noexcept
  603. {
  604. #if __BYTE_ORDER == __BIG_ENDIAN
  605. storeAsIsEndian(p,_swap_bytes_bysize<I,sizeof(I)>::s(i));
  606. #else
  607. #ifdef ZT_NO_UNALIGNED_ACCESS
  608. storeAsIsEndian(p,i);
  609. #else
  610. *reinterpret_cast<I *>(p) = i;
  611. #endif
  612. #endif
  613. }
  614. /**
  615. * Copy memory block whose size is known at compile time.
  616. *
  617. * @tparam L Size of memory
  618. * @param dest Destination memory
  619. * @param src Source memory
  620. */
  621. template< unsigned int L >
  622. static ZT_INLINE void copy(void *const dest, const void *const src) noexcept
  623. {
  624. #ifdef ZT_ARCH_X64
  625. uint8_t *volatile d = reinterpret_cast<uint8_t *>(dest);
  626. const uint8_t *s = reinterpret_cast<const uint8_t *>(src);
  627. for (unsigned int i = 0; i < (L >> 6U); ++i) {
  628. __m128i x0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s));
  629. __m128i x1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 16));
  630. __m128i x2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 32));
  631. __m128i x3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 48));
  632. s += 64;
  633. _mm_storeu_si128(reinterpret_cast<__m128i *>(d), x0);
  634. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16), x1);
  635. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 32), x2);
  636. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 48), x3);
  637. d += 64;
  638. }
  639. if ((L & 32U) != 0) {
  640. __m128i x0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s));
  641. __m128i x1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 16));
  642. s += 32;
  643. _mm_storeu_si128(reinterpret_cast<__m128i *>(d), x0);
  644. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16), x1);
  645. d += 32;
  646. }
  647. if ((L & 16U) != 0) {
  648. __m128i x0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s));
  649. s += 16;
  650. _mm_storeu_si128(reinterpret_cast<__m128i *>(d), x0);
  651. d += 16;
  652. }
  653. if ((L & 8U) != 0) {
  654. *reinterpret_cast<volatile uint64_t *>(d) = *reinterpret_cast<const uint64_t *>(s);
  655. s += 8;
  656. d += 8;
  657. }
  658. if ((L & 4U) != 0) {
  659. *reinterpret_cast<volatile uint32_t *>(d) = *reinterpret_cast<const uint32_t *>(s);
  660. s += 4;
  661. d += 4;
  662. }
  663. if ((L & 2U) != 0) {
  664. *reinterpret_cast<volatile uint16_t *>(d) = *reinterpret_cast<const uint16_t *>(s);
  665. s += 2;
  666. d += 2;
  667. }
  668. if ((L & 1U) != 0) {
  669. *d = *s;
  670. }
  671. #else
  672. memcpy(dest,src,L);
  673. #endif
  674. }
  675. /**
  676. * Copy memory block whose size is known at run time
  677. *
  678. * @param dest Destination memory
  679. * @param src Source memory
  680. * @param len Bytes to copy
  681. */
  682. static ZT_INLINE void copy(void *const dest, const void *const src, unsigned int len) noexcept
  683. { memcpy(dest, src, len); }
  684. /**
  685. * Zero memory block whose size is known at compile time
  686. *
  687. * @tparam L Size in bytes
  688. * @param dest Memory to zero
  689. */
  690. template< unsigned int L >
  691. static ZT_INLINE void zero(void *const dest) noexcept
  692. {
  693. #ifdef ZT_ARCH_X64
  694. uint8_t *volatile d = reinterpret_cast<uint8_t *>(dest);
  695. __m128i z = _mm_setzero_si128();
  696. for (unsigned int i = 0; i < (L >> 6U); ++i) {
  697. _mm_storeu_si128(reinterpret_cast<__m128i *>(d), z);
  698. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16), z);
  699. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 32), z);
  700. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 48), z);
  701. d += 64;
  702. }
  703. if ((L & 32U) != 0) {
  704. _mm_storeu_si128(reinterpret_cast<__m128i *>(d), z);
  705. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16), z);
  706. d += 32;
  707. }
  708. if ((L & 16U) != 0) {
  709. _mm_storeu_si128(reinterpret_cast<__m128i *>(d), z);
  710. d += 16;
  711. }
  712. if ((L & 8U) != 0) {
  713. *reinterpret_cast<volatile uint64_t *>(d) = 0;
  714. d += 8;
  715. }
  716. if ((L & 4U) != 0) {
  717. *reinterpret_cast<volatile uint32_t *>(d) = 0;
  718. d += 4;
  719. }
  720. if ((L & 2U) != 0) {
  721. *reinterpret_cast<volatile uint16_t *>(d) = 0;
  722. d += 2;
  723. }
  724. if ((L & 1U) != 0) {
  725. *d = 0;
  726. }
  727. #else
  728. memset(dest,0,L);
  729. #endif
  730. }
  731. /**
  732. * Zero memory block whose size is known at run time
  733. *
  734. * @param dest Memory to zero
  735. * @param len Size in bytes
  736. */
  737. static ZT_INLINE void zero(void *const dest, const unsigned int len) noexcept
  738. { memset(dest, 0, len); }
  739. /**
  740. * Simple malloc/free based C++ STL allocator.
  741. *
  742. * This is used to make sure our containers don't use weird libc++
  743. * allocators but instead use whatever malloc() is, which in turn
  744. * can be overridden by things like jemaclloc or tcmalloc.
  745. *
  746. * @tparam T Allocated type
  747. */
  748. template< typename T >
  749. struct Mallocator
  750. {
  751. typedef size_t size_type;
  752. typedef ptrdiff_t difference_type;
  753. typedef T *pointer;
  754. typedef const T *const_pointer;
  755. typedef T &reference;
  756. typedef const T &const_reference;
  757. typedef T value_type;
  758. template< class U >
  759. struct rebind
  760. {
  761. typedef Mallocator< U > other;
  762. };
  763. ZT_INLINE Mallocator() noexcept
  764. {}
  765. ZT_INLINE Mallocator(const Mallocator &) noexcept
  766. {}
  767. template< class U >
  768. ZT_INLINE Mallocator(const Mallocator< U > &) noexcept
  769. {}
  770. ZT_INLINE ~Mallocator() noexcept
  771. {}
  772. ZT_INLINE pointer allocate(size_type s, void const * = nullptr)
  773. {
  774. if (0 == s)
  775. return nullptr;
  776. pointer temp = (pointer)malloc(s * sizeof(T));
  777. if (temp == nullptr)
  778. throw std::bad_alloc();
  779. return temp;
  780. }
  781. ZT_INLINE pointer address(reference x) const
  782. { return &x; }
  783. ZT_INLINE const_pointer address(const_reference x) const
  784. { return &x; }
  785. ZT_INLINE void deallocate(pointer p, size_type)
  786. { free(p); }
  787. ZT_INLINE size_type max_size() const noexcept
  788. { return std::numeric_limits< size_t >::max() / sizeof(T); }
  789. ZT_INLINE void construct(pointer p, const T &val)
  790. { new((void *)p) T(val); }
  791. ZT_INLINE void destroy(pointer p)
  792. { p->~T(); }
  793. constexpr bool operator==(const Mallocator &) const noexcept
  794. { return true; }
  795. constexpr bool operator!=(const Mallocator &) const noexcept
  796. { return false; }
  797. };
  798. } // namespace Utils
  799. } // namespace ZeroTier
  800. #endif