Utils.hpp 22 KB

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