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. #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 { return (unsigned int)__builtin_popcount((unsigned int)v); }
  306. static ZT_INLINE unsigned int countBits(const uint16_t v) noexcept { return (unsigned int)__builtin_popcount((unsigned int)v); }
  307. static ZT_INLINE unsigned int countBits(const uint32_t v) noexcept { return (unsigned int)__builtin_popcountl((unsigned long)v); }
  308. static ZT_INLINE unsigned int countBits(const uint64_t v) noexcept{ return (unsigned int)__builtin_popcountll((unsigned long long)v); }
  309. #else
  310. template<typename T>
  311. static ZT_INLINE unsigned int countBits(T v) noexcept
  312. {
  313. v = v - ((v >> 1) & (T)~(T)0/3);
  314. v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);
  315. v = (v + (v >> 4)) & (T)~(T)0/255*15;
  316. return (unsigned int)((v * ((~((T)0))/((T)255))) >> ((sizeof(T) - 1) * 8));
  317. }
  318. #endif
  319. /**
  320. * Unconditionally swap bytes regardless of host byte order
  321. *
  322. * @param n Integer to swap
  323. * @return Integer with bytes reversed
  324. */
  325. static ZT_INLINE uint64_t swapBytes(const uint64_t n) noexcept
  326. {
  327. #ifdef __GNUC__
  328. return __builtin_bswap64(n);
  329. #else
  330. #ifdef _MSC_VER
  331. return (uint64_t)_byteswap_uint64((unsigned __int64)n);
  332. #else
  333. return (
  334. ((n & 0x00000000000000ffULL) << 56) |
  335. ((n & 0x000000000000ff00ULL) << 40) |
  336. ((n & 0x0000000000ff0000ULL) << 24) |
  337. ((n & 0x00000000ff000000ULL) << 8) |
  338. ((n & 0x000000ff00000000ULL) >> 8) |
  339. ((n & 0x0000ff0000000000ULL) >> 24) |
  340. ((n & 0x00ff000000000000ULL) >> 40) |
  341. ((n & 0xff00000000000000ULL) >> 56)
  342. );
  343. #endif
  344. #endif
  345. }
  346. /**
  347. * Unconditionally swap bytes regardless of host byte order
  348. *
  349. * @param n Integer to swap
  350. * @return Integer with bytes reversed
  351. */
  352. static ZT_INLINE uint32_t swapBytes(const uint32_t n) noexcept
  353. {
  354. #if defined(__GNUC__)
  355. return __builtin_bswap32(n);
  356. #else
  357. #ifdef _MSC_VER
  358. return (uint32_t)_byteswap_ulong((unsigned long)n);
  359. #else
  360. return htonl(n);
  361. #endif
  362. #endif
  363. }
  364. /**
  365. * Unconditionally swap bytes regardless of host byte order
  366. *
  367. * @param n Integer to swap
  368. * @return Integer with bytes reversed
  369. */
  370. static ZT_INLINE uint16_t swapBytes(const uint16_t n) noexcept
  371. {
  372. #if defined(__GNUC__)
  373. return __builtin_bswap16(n);
  374. #else
  375. #ifdef _MSC_VER
  376. return (uint16_t)_byteswap_ushort((unsigned short)n);
  377. #else
  378. return htons(n);
  379. #endif
  380. #endif
  381. }
  382. // These are helper adapters to load and swap integer types special cased by size
  383. // to work with all typedef'd variants, signed/unsigned, etc.
  384. template<typename I,unsigned int S>
  385. class _swap_bytes_bysize;
  386. template<typename I>
  387. class _swap_bytes_bysize<I,1> { public: static ZT_INLINE I s(const I n) noexcept { return n; } };
  388. template<typename I>
  389. class _swap_bytes_bysize<I,2> { public: static ZT_INLINE I s(const I n) noexcept { return (I)swapBytes((uint16_t)n); } };
  390. template<typename I>
  391. class _swap_bytes_bysize<I,4> { public: static ZT_INLINE I s(const I n) noexcept { return (I)swapBytes((uint32_t)n); } };
  392. template<typename I>
  393. class _swap_bytes_bysize<I,8> { public: static ZT_INLINE I s(const I n) noexcept { return (I)swapBytes((uint64_t)n); } };
  394. template<typename I,unsigned int S>
  395. class _load_be_bysize;
  396. template<typename I>
  397. class _load_be_bysize<I,1> { public: static ZT_INLINE I l(const uint8_t *const p) noexcept { return p[0]; }};
  398. template<typename I>
  399. 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]); }};
  400. template<typename I>
  401. 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]); }};
  402. template<typename I>
  403. 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]); }};
  404. template<typename I,unsigned int S>
  405. class _load_le_bysize;
  406. template<typename I>
  407. class _load_le_bysize<I,1> { public: static ZT_INLINE I l(const uint8_t *const p) noexcept { return p[0]; }};
  408. template<typename I>
  409. 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)); }};
  410. template<typename I>
  411. 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)); }};
  412. template<typename I>
  413. 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); }};
  414. /**
  415. * Convert any signed or unsigned integer type to big-endian ("network") byte order
  416. *
  417. * @tparam I Integer type (usually inferred)
  418. * @param n Value to convert
  419. * @return Value in big-endian order
  420. */
  421. template<typename I>
  422. static ZT_INLINE I hton(const I n) noexcept
  423. {
  424. #if __BYTE_ORDER == __LITTLE_ENDIAN
  425. return _swap_bytes_bysize<I,sizeof(I)>::s(n);
  426. #else
  427. return n;
  428. #endif
  429. }
  430. /**
  431. * Convert any signed or unsigned integer type to host byte order from big-endian ("network") byte order
  432. *
  433. * @tparam I Integer type (usually inferred)
  434. * @param n Value to convert
  435. * @return Value in host byte order
  436. */
  437. template<typename I>
  438. static ZT_INLINE I ntoh(const I n) noexcept
  439. {
  440. #if __BYTE_ORDER == __LITTLE_ENDIAN
  441. return _swap_bytes_bysize<I,sizeof(I)>::s(n);
  442. #else
  443. return n;
  444. #endif
  445. }
  446. /**
  447. * Copy bits from memory into an integer type without modifying their order
  448. *
  449. * @tparam I Type to load
  450. * @param p Byte stream, must be at least sizeof(I) in size
  451. * @return Loaded raw integer
  452. */
  453. template<typename I>
  454. static ZT_INLINE I loadAsIsEndian(const void *const p) noexcept
  455. {
  456. #ifdef ZT_NO_UNALIGNED_ACCESS
  457. I tmp;
  458. for(int i=0;i<(int)sizeof(I);++i)
  459. reinterpret_cast<uint8_t *>(&tmp)[i] = reinterpret_cast<const uint8_t *>(p)[i];
  460. return tmp;
  461. #else
  462. return *reinterpret_cast<const I *>(p);
  463. #endif
  464. }
  465. /**
  466. * Copy bits from memory into an integer type without modifying their order
  467. *
  468. * @tparam I Type to store
  469. * @param p Byte array (must be at least sizeof(I))
  470. * @param i Integer to store
  471. */
  472. template<typename I>
  473. static ZT_INLINE void storeAsIsEndian(void *const p,const I i) noexcept
  474. {
  475. #ifdef ZT_NO_UNALIGNED_ACCESS
  476. for(unsigned int k=0;k<sizeof(I);++k)
  477. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[k];
  478. #else
  479. *reinterpret_cast<I *>(p) = i;
  480. #endif
  481. }
  482. /**
  483. * Decode a big-endian value from a byte stream
  484. *
  485. * @tparam I Type to decode (should be unsigned e.g. uint32_t or uint64_t)
  486. * @param p Byte stream, must be at least sizeof(I) in size
  487. * @return Decoded integer
  488. */
  489. template<typename I>
  490. static ZT_INLINE I loadBigEndian(const void *const p) noexcept
  491. {
  492. #ifdef ZT_NO_UNALIGNED_ACCESS
  493. return _load_be_bysize<I,sizeof(I)>::l(reinterpret_cast<const uint8_t *>(p));
  494. #else
  495. return ntoh(*reinterpret_cast<const I *>(p));
  496. #endif
  497. }
  498. /**
  499. * Save an integer in big-endian format
  500. *
  501. * @tparam I Integer type to store (usually inferred)
  502. * @param p Byte stream to write (must be at least sizeof(I))
  503. * #param i Integer to write
  504. */
  505. template<typename I>
  506. static ZT_INLINE void storeBigEndian(void *const p,I i) noexcept
  507. {
  508. #ifdef ZT_NO_UNALIGNED_ACCESS
  509. storeAsIsEndian(p,hton(i));
  510. #else
  511. *reinterpret_cast<I *>(p) = hton(i);
  512. #endif
  513. }
  514. /**
  515. * Decode a little-endian value from a byte stream
  516. *
  517. * @tparam I Type to decode
  518. * @param p Byte stream, must be at least sizeof(I) in size
  519. * @return Decoded integer
  520. */
  521. template<typename I>
  522. static ZT_INLINE I loadLittleEndian(const void *const p) noexcept
  523. {
  524. #if __BYTE_ORDER == __BIG_ENDIAN || defined(ZT_NO_UNALIGNED_ACCESS)
  525. return _load_le_bysize<I,sizeof(I)>::l(reinterpret_cast<const uint8_t *>(p));
  526. #else
  527. return *reinterpret_cast<const I *>(p);
  528. #endif
  529. }
  530. /**
  531. * Save an integer in little-endian format
  532. *
  533. * @tparam I Integer type to store (usually inferred)
  534. * @param p Byte stream to write (must be at least sizeof(I))
  535. * #param i Integer to write
  536. */
  537. template<typename I>
  538. static ZT_INLINE void storeLittleEndian(void *const p,const I i) noexcept
  539. {
  540. #if __BYTE_ORDER == __BIG_ENDIAN
  541. storeAsIsEndian(p,_swap_bytes_bysize<I,sizeof(I)>::s(i));
  542. #else
  543. #ifdef ZT_NO_UNALIGNED_ACCESS
  544. storeAsIsEndian(p,i);
  545. #else
  546. *reinterpret_cast<I *>(p) = i;
  547. #endif
  548. #endif
  549. }
  550. /**
  551. * Copy memory block whose size is known at compile time.
  552. *
  553. * @tparam L Size of memory
  554. * @param dest Destination memory
  555. * @param src Source memory
  556. */
  557. template<unsigned int L>
  558. static ZT_INLINE void copy(void *const dest,const void *const src) noexcept
  559. {
  560. #ifdef ZT_ARCH_X64
  561. uint8_t *volatile d = reinterpret_cast<uint8_t *>(dest);
  562. const uint8_t *s = reinterpret_cast<const uint8_t *>(src);
  563. for(unsigned int i=0;i<(L >> 6U);++i) {
  564. __m128i x0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s));
  565. __m128i x1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 16));
  566. __m128i x2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 32));
  567. __m128i x3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 48));
  568. s += 64;
  569. _mm_storeu_si128(reinterpret_cast<__m128i *>(d),x0);
  570. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16),x1);
  571. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 32),x2);
  572. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 48),x3);
  573. d += 64;
  574. }
  575. if ((L & 32U) != 0) {
  576. __m128i x0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s));
  577. __m128i x1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s + 16));
  578. s += 32;
  579. _mm_storeu_si128(reinterpret_cast<__m128i *>(d),x0);
  580. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16),x1);
  581. d += 32;
  582. }
  583. if ((L & 16U) != 0) {
  584. __m128i x0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s));
  585. s += 16;
  586. _mm_storeu_si128(reinterpret_cast<__m128i *>(d),x0);
  587. d += 16;
  588. }
  589. if ((L & 8U) != 0) {
  590. *reinterpret_cast<volatile uint64_t *>(d) = *reinterpret_cast<const uint64_t *>(s);
  591. s += 8;
  592. d += 8;
  593. }
  594. if ((L & 4U) != 0) {
  595. *reinterpret_cast<volatile uint32_t *>(d) = *reinterpret_cast<const uint32_t *>(s);
  596. s += 4;
  597. d += 4;
  598. }
  599. if ((L & 2U) != 0) {
  600. *reinterpret_cast<volatile uint16_t *>(d) = *reinterpret_cast<const uint16_t *>(s);
  601. s += 2;
  602. d += 2;
  603. }
  604. if ((L & 1U) != 0) {
  605. *d = *s;
  606. }
  607. #else
  608. memcpy(dest,src,L);
  609. #endif
  610. }
  611. /**
  612. * Copy memory block whose size is known at run time
  613. *
  614. * @param dest Destination memory
  615. * @param src Source memory
  616. * @param len Bytes to copy
  617. */
  618. static ZT_INLINE void copy(void *const dest,const void *const src,unsigned int len) noexcept { memcpy(dest,src,len); }
  619. /**
  620. * Zero memory block whose size is known at compile time
  621. *
  622. * @tparam L Size in bytes
  623. * @param dest Memory to zero
  624. */
  625. template<unsigned int L>
  626. static ZT_INLINE void zero(void *const dest) noexcept
  627. {
  628. #ifdef ZT_ARCH_X64
  629. uint8_t *volatile d = reinterpret_cast<uint8_t *>(dest);
  630. __m128i z = _mm_setzero_si128();
  631. for(unsigned int i=0;i<(L >> 6U);++i) {
  632. _mm_storeu_si128(reinterpret_cast<__m128i *>(d),z);
  633. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16),z);
  634. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 32),z);
  635. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 48),z);
  636. d += 64;
  637. }
  638. if ((L & 32U) != 0) {
  639. _mm_storeu_si128(reinterpret_cast<__m128i *>(d),z);
  640. _mm_storeu_si128(reinterpret_cast<__m128i *>(d + 16),z);
  641. d += 32;
  642. }
  643. if ((L & 16U) != 0) {
  644. _mm_storeu_si128(reinterpret_cast<__m128i *>(d),z);
  645. d += 16;
  646. }
  647. if ((L & 8U) != 0) {
  648. *reinterpret_cast<volatile uint64_t *>(d) = 0;
  649. d += 8;
  650. }
  651. if ((L & 4U) != 0) {
  652. *reinterpret_cast<volatile uint32_t *>(d) = 0;
  653. d += 4;
  654. }
  655. if ((L & 2U) != 0) {
  656. *reinterpret_cast<volatile uint16_t *>(d) = 0;
  657. d += 2;
  658. }
  659. if ((L & 1U) != 0) {
  660. *d = 0;
  661. }
  662. #else
  663. memset(dest,0,L);
  664. #endif
  665. }
  666. /**
  667. * Zero memory block whose size is known at run time
  668. *
  669. * @param dest Memory to zero
  670. * @param len Size in bytes
  671. */
  672. static ZT_INLINE void zero(void *const dest,const unsigned int len) noexcept { memset(dest,0,len); }
  673. /**
  674. * Simple malloc/free based C++ STL allocator.
  675. *
  676. * This is used to make sure our containers don't use weird libc++
  677. * allocators but instead use whatever malloc() is, which in turn
  678. * can be overridden by things like jemaclloc or tcmalloc.
  679. *
  680. * @tparam T Allocated type
  681. */
  682. template<typename T>
  683. struct Mallocator
  684. {
  685. typedef size_t size_type;
  686. typedef ptrdiff_t difference_type;
  687. typedef T * pointer;
  688. typedef const T * const_pointer;
  689. typedef T & reference;
  690. typedef const T & const_reference;
  691. typedef T value_type;
  692. template <class U> struct rebind { typedef Mallocator<U> other; };
  693. ZT_INLINE Mallocator() noexcept {}
  694. ZT_INLINE Mallocator(const Mallocator&) noexcept {}
  695. template <class U> ZT_INLINE Mallocator(const Mallocator<U>&) noexcept {}
  696. ZT_INLINE ~Mallocator() noexcept {}
  697. ZT_INLINE pointer allocate(size_type s,void const * = nullptr)
  698. {
  699. if (0 == s)
  700. return nullptr;
  701. pointer temp = (pointer)malloc(s * sizeof(T));
  702. if (temp == nullptr)
  703. throw std::bad_alloc();
  704. return temp;
  705. }
  706. ZT_INLINE pointer address(reference x) const { return &x; }
  707. ZT_INLINE const_pointer address(const_reference x) const { return &x; }
  708. ZT_INLINE void deallocate(pointer p,size_type) { free(p); }
  709. ZT_INLINE size_type max_size() const noexcept { return std::numeric_limits<size_t>::max() / sizeof(T); }
  710. ZT_INLINE void construct(pointer p,const T& val) { new((void *)p) T(val); }
  711. ZT_INLINE void destroy(pointer p) { p->~T(); }
  712. constexpr bool operator==(const Mallocator &) const noexcept { return true; }
  713. constexpr bool operator!=(const Mallocator &) const noexcept { return false; }
  714. };
  715. } // namespace Utils
  716. } // namespace ZeroTier
  717. #endif