HashFunctions.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /* Utilities for hashing. */
  6. /*
  7. * This file exports functions for hashing data down to a 32-bit value,
  8. * including:
  9. *
  10. * - HashString Hash a char* or char16_t/wchar_t* of known or unknown
  11. * length.
  12. *
  13. * - HashBytes Hash a byte array of known length.
  14. *
  15. * - HashGeneric Hash one or more values. Currently, we support uint32_t,
  16. * types which can be implicitly cast to uint32_t, data
  17. * pointers, and function pointers.
  18. *
  19. * - AddToHash Add one or more values to the given hash. This supports the
  20. * same list of types as HashGeneric.
  21. *
  22. *
  23. * You can chain these functions together to hash complex objects. For example:
  24. *
  25. * class ComplexObject
  26. * {
  27. * char* mStr;
  28. * uint32_t mUint1, mUint2;
  29. * void (*mCallbackFn)();
  30. *
  31. * public:
  32. * uint32_t hash()
  33. * {
  34. * uint32_t hash = HashString(mStr);
  35. * hash = AddToHash(hash, mUint1, mUint2);
  36. * return AddToHash(hash, mCallbackFn);
  37. * }
  38. * };
  39. *
  40. * If you want to hash an nsAString or nsACString, use the HashString functions
  41. * in nsHashKeys.h.
  42. */
  43. #ifndef mozilla_HashFunctions_h
  44. #define mozilla_HashFunctions_h
  45. #include "mozilla/Assertions.h"
  46. #include "mozilla/Attributes.h"
  47. #include "mozilla/Char16.h"
  48. #include "mozilla/MathAlgorithms.h"
  49. #include "mozilla/Types.h"
  50. #include <stdint.h>
  51. #ifdef __cplusplus
  52. namespace mozilla {
  53. /**
  54. * The golden ratio as a 32-bit fixed-point value.
  55. */
  56. static const uint32_t kGoldenRatioU32 = 0x9E3779B9U;
  57. inline uint32_t
  58. RotateBitsLeft32(uint32_t aValue, uint8_t aBits)
  59. {
  60. MOZ_ASSERT(aBits < 32);
  61. return (aValue << aBits) | (aValue >> (32 - aBits));
  62. }
  63. namespace detail {
  64. inline uint32_t
  65. AddU32ToHash(uint32_t aHash, uint32_t aValue)
  66. {
  67. /*
  68. * This is the meat of all our hash routines. This hash function is not
  69. * particularly sophisticated, but it seems to work well for our mostly
  70. * plain-text inputs. Implementation notes follow.
  71. *
  72. * Our use of the golden ratio here is arbitrary; we could pick almost any
  73. * number which:
  74. *
  75. * * is odd (because otherwise, all our hash values will be even)
  76. *
  77. * * has a reasonably-even mix of 1's and 0's (consider the extreme case
  78. * where we multiply by 0x3 or 0xeffffff -- this will not produce good
  79. * mixing across all bits of the hash).
  80. *
  81. * The rotation length of 5 is also arbitrary, although an odd number is again
  82. * preferable so our hash explores the whole universe of possible rotations.
  83. *
  84. * Finally, we multiply by the golden ratio *after* xor'ing, not before.
  85. * Otherwise, if |aHash| is 0 (as it often is for the beginning of a
  86. * message), the expression
  87. *
  88. * (kGoldenRatioU32 * RotateBitsLeft(aHash, 5)) |xor| aValue
  89. *
  90. * evaluates to |aValue|.
  91. *
  92. * (Number-theoretic aside: Because any odd number |m| is relatively prime to
  93. * our modulus (2^32), the list
  94. *
  95. * [x * m (mod 2^32) for 0 <= x < 2^32]
  96. *
  97. * has no duplicate elements. This means that multiplying by |m| does not
  98. * cause us to skip any possible hash values.
  99. *
  100. * It's also nice if |m| has large-ish order mod 2^32 -- that is, if the
  101. * smallest k such that m^k == 1 (mod 2^32) is large -- so we can safely
  102. * multiply our hash value by |m| a few times without negating the
  103. * multiplicative effect. Our golden ratio constant has order 2^29, which is
  104. * more than enough for our purposes.)
  105. */
  106. return kGoldenRatioU32 * (RotateBitsLeft32(aHash, 5) ^ aValue);
  107. }
  108. /**
  109. * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter.
  110. */
  111. template<size_t PtrSize>
  112. inline uint32_t
  113. AddUintptrToHash(uint32_t aHash, uintptr_t aValue);
  114. template<>
  115. inline uint32_t
  116. AddUintptrToHash<4>(uint32_t aHash, uintptr_t aValue)
  117. {
  118. return AddU32ToHash(aHash, static_cast<uint32_t>(aValue));
  119. }
  120. template<>
  121. inline uint32_t
  122. AddUintptrToHash<8>(uint32_t aHash, uintptr_t aValue)
  123. {
  124. /*
  125. * The static cast to uint64_t below is necessary because this function
  126. * sometimes gets compiled on 32-bit platforms (yes, even though it's a
  127. * template and we never call this particular override in a 32-bit build). If
  128. * we do aValue >> 32 on a 32-bit machine, we're shifting a 32-bit uintptr_t
  129. * right 32 bits, and the compiler throws an error.
  130. */
  131. uint32_t v1 = static_cast<uint32_t>(aValue);
  132. uint32_t v2 = static_cast<uint32_t>(static_cast<uint64_t>(aValue) >> 32);
  133. return AddU32ToHash(AddU32ToHash(aHash, v1), v2);
  134. }
  135. } /* namespace detail */
  136. /**
  137. * AddToHash takes a hash and some values and returns a new hash based on the
  138. * inputs.
  139. *
  140. * Currently, we support hashing uint32_t's, values which we can implicitly
  141. * convert to uint32_t, data pointers, and function pointers.
  142. */
  143. template<typename A>
  144. MOZ_MUST_USE inline uint32_t
  145. AddToHash(uint32_t aHash, A aA)
  146. {
  147. /*
  148. * Try to convert |A| to uint32_t implicitly. If this works, great. If not,
  149. * we'll error out.
  150. */
  151. return detail::AddU32ToHash(aHash, aA);
  152. }
  153. template<typename A>
  154. MOZ_MUST_USE inline uint32_t
  155. AddToHash(uint32_t aHash, A* aA)
  156. {
  157. /*
  158. * You might think this function should just take a void*. But then we'd only
  159. * catch data pointers and couldn't handle function pointers.
  160. */
  161. static_assert(sizeof(aA) == sizeof(uintptr_t), "Strange pointer!");
  162. return detail::AddUintptrToHash<sizeof(uintptr_t)>(aHash, uintptr_t(aA));
  163. }
  164. template<>
  165. MOZ_MUST_USE inline uint32_t
  166. AddToHash(uint32_t aHash, uintptr_t aA)
  167. {
  168. return detail::AddUintptrToHash<sizeof(uintptr_t)>(aHash, aA);
  169. }
  170. template<typename A, typename... Args>
  171. MOZ_MUST_USE uint32_t
  172. AddToHash(uint32_t aHash, A aArg, Args... aArgs)
  173. {
  174. return AddToHash(AddToHash(aHash, aArg), aArgs...);
  175. }
  176. /**
  177. * The HashGeneric class of functions let you hash one or more values.
  178. *
  179. * If you want to hash together two values x and y, calling HashGeneric(x, y) is
  180. * much better than calling AddToHash(x, y), because AddToHash(x, y) assumes
  181. * that x has already been hashed.
  182. */
  183. template<typename... Args>
  184. MOZ_MUST_USE inline uint32_t
  185. HashGeneric(Args... aArgs)
  186. {
  187. return AddToHash(0, aArgs...);
  188. }
  189. namespace detail {
  190. template<typename T>
  191. uint32_t
  192. HashUntilZero(const T* aStr)
  193. {
  194. uint32_t hash = 0;
  195. for (T c; (c = *aStr); aStr++) {
  196. hash = AddToHash(hash, c);
  197. }
  198. return hash;
  199. }
  200. template<typename T>
  201. uint32_t
  202. HashKnownLength(const T* aStr, size_t aLength)
  203. {
  204. uint32_t hash = 0;
  205. for (size_t i = 0; i < aLength; i++) {
  206. hash = AddToHash(hash, aStr[i]);
  207. }
  208. return hash;
  209. }
  210. } /* namespace detail */
  211. /**
  212. * The HashString overloads below do just what you'd expect.
  213. *
  214. * If you have the string's length, you might as well call the overload which
  215. * includes the length. It may be marginally faster.
  216. */
  217. MOZ_MUST_USE inline uint32_t
  218. HashString(const char* aStr)
  219. {
  220. return detail::HashUntilZero(reinterpret_cast<const unsigned char*>(aStr));
  221. }
  222. MOZ_MUST_USE inline uint32_t
  223. HashString(const char* aStr, size_t aLength)
  224. {
  225. return detail::HashKnownLength(reinterpret_cast<const unsigned char*>(aStr), aLength);
  226. }
  227. MOZ_MUST_USE
  228. inline uint32_t
  229. HashString(const unsigned char* aStr, size_t aLength)
  230. {
  231. return detail::HashKnownLength(aStr, aLength);
  232. }
  233. MOZ_MUST_USE inline uint32_t
  234. HashString(const char16_t* aStr)
  235. {
  236. return detail::HashUntilZero(aStr);
  237. }
  238. MOZ_MUST_USE inline uint32_t
  239. HashString(const char16_t* aStr, size_t aLength)
  240. {
  241. return detail::HashKnownLength(aStr, aLength);
  242. }
  243. /*
  244. * On Windows, wchar_t is not the same as char16_t, even though it's
  245. * the same width!
  246. */
  247. #ifdef WIN32
  248. MOZ_MUST_USE inline uint32_t
  249. HashString(const wchar_t* aStr)
  250. {
  251. return detail::HashUntilZero(aStr);
  252. }
  253. MOZ_MUST_USE inline uint32_t
  254. HashString(const wchar_t* aStr, size_t aLength)
  255. {
  256. return detail::HashKnownLength(aStr, aLength);
  257. }
  258. #endif
  259. /**
  260. * Hash some number of bytes.
  261. *
  262. * This hash walks word-by-word, rather than byte-by-byte, so you won't get the
  263. * same result out of HashBytes as you would out of HashString.
  264. */
  265. MOZ_MUST_USE extern MFBT_API uint32_t
  266. HashBytes(const void* bytes, size_t aLength);
  267. /**
  268. * A pseudorandom function mapping 32-bit integers to 32-bit integers.
  269. *
  270. * This is for when you're feeding private data (like pointer values or credit
  271. * card numbers) to a non-crypto hash function (like HashBytes) and then using
  272. * the hash code for something that untrusted parties could observe (like a JS
  273. * Map). Plug in a HashCodeScrambler before that last step to avoid leaking the
  274. * private data.
  275. *
  276. * By itself, this does not prevent hash-flooding DoS attacks, because an
  277. * attacker can still generate many values with exactly equal hash codes by
  278. * attacking the non-crypto hash function alone. Equal hash codes will, of
  279. * course, still be equal however much you scramble them.
  280. *
  281. * The algorithm is SipHash-1-3. See <https://131002.net/siphash/>.
  282. */
  283. class HashCodeScrambler
  284. {
  285. struct SipHasher;
  286. uint64_t mK0, mK1;
  287. public:
  288. /** Creates a new scrambler with the given 128-bit key. */
  289. constexpr HashCodeScrambler(uint64_t aK0, uint64_t aK1) : mK0(aK0), mK1(aK1) {}
  290. /**
  291. * Scramble a hash code. Always produces the same result for the same
  292. * combination of key and hash code.
  293. */
  294. uint32_t scramble(uint32_t aHashCode) const
  295. {
  296. SipHasher hasher(mK0, mK1);
  297. return uint32_t(hasher.sipHash(aHashCode));
  298. }
  299. private:
  300. struct SipHasher
  301. {
  302. SipHasher(uint64_t aK0, uint64_t aK1)
  303. {
  304. // 1. Initialization.
  305. mV0 = aK0 ^ UINT64_C(0x736f6d6570736575);
  306. mV1 = aK1 ^ UINT64_C(0x646f72616e646f6d);
  307. mV2 = aK0 ^ UINT64_C(0x6c7967656e657261);
  308. mV3 = aK1 ^ UINT64_C(0x7465646279746573);
  309. }
  310. uint64_t sipHash(uint64_t aM)
  311. {
  312. // 2. Compression.
  313. mV3 ^= aM;
  314. sipRound();
  315. mV0 ^= aM;
  316. // 3. Finalization.
  317. mV2 ^= 0xff;
  318. for (int i = 0; i < 3; i++)
  319. sipRound();
  320. return mV0 ^ mV1 ^ mV2 ^ mV3;
  321. }
  322. void sipRound()
  323. {
  324. mV0 += mV1;
  325. mV1 = RotateLeft(mV1, 13);
  326. mV1 ^= mV0;
  327. mV0 = RotateLeft(mV0, 32);
  328. mV2 += mV3;
  329. mV3 = RotateLeft(mV3, 16);
  330. mV3 ^= mV2;
  331. mV0 += mV3;
  332. mV3 = RotateLeft(mV3, 21);
  333. mV3 ^= mV0;
  334. mV2 += mV1;
  335. mV1 = RotateLeft(mV1, 17);
  336. mV1 ^= mV2;
  337. mV2 = RotateLeft(mV2, 32);
  338. }
  339. uint64_t mV0, mV1, mV2, mV3;
  340. };
  341. };
  342. } /* namespace mozilla */
  343. #endif /* __cplusplus */
  344. #endif /* mozilla_HashFunctions_h */