pyhash.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /* Set of hash utility functions to help maintaining the invariant that
  2. if a==b then hash(a)==hash(b)
  3. All the utility functions (_Py_Hash*()) return "-1" to signify an error.
  4. */
  5. #include "Python.h"
  6. #ifdef __APPLE__
  7. # include <libkern/OSByteOrder.h>
  8. #elif defined(HAVE_LE64TOH) && defined(HAVE_ENDIAN_H)
  9. # include <endian.h>
  10. #elif defined(HAVE_LE64TOH) && defined(HAVE_SYS_ENDIAN_H)
  11. # include <sys/endian.h>
  12. #endif
  13. #ifdef __cplusplus
  14. extern "C" {
  15. #endif
  16. _Py_HashSecret_t _Py_HashSecret = {{0}};
  17. #if Py_HASH_ALGORITHM == Py_HASH_EXTERNAL
  18. extern PyHash_FuncDef PyHash_Func;
  19. #else
  20. static PyHash_FuncDef PyHash_Func;
  21. #endif
  22. /* Count _Py_HashBytes() calls */
  23. #ifdef Py_HASH_STATS
  24. #define Py_HASH_STATS_MAX 32
  25. static Py_ssize_t hashstats[Py_HASH_STATS_MAX + 1] = {0};
  26. #endif
  27. /* For numeric types, the hash of a number x is based on the reduction
  28. of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
  29. hash(x) == hash(y) whenever x and y are numerically equal, even if
  30. x and y have different types.
  31. A quick summary of the hashing strategy:
  32. (1) First define the 'reduction of x modulo P' for any rational
  33. number x; this is a standard extension of the usual notion of
  34. reduction modulo P for integers. If x == p/q (written in lowest
  35. terms), the reduction is interpreted as the reduction of p times
  36. the inverse of the reduction of q, all modulo P; if q is exactly
  37. divisible by P then define the reduction to be infinity. So we've
  38. got a well-defined map
  39. reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
  40. (2) Now for a rational number x, define hash(x) by:
  41. reduce(x) if x >= 0
  42. -reduce(-x) if x < 0
  43. If the result of the reduction is infinity (this is impossible for
  44. integers, floats and Decimals) then use the predefined hash value
  45. _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
  46. _PyHASH_INF and -_PyHASH_INF are also used for the
  47. hashes of float and Decimal infinities.
  48. NaNs hash with a pointer hash. Having distinct hash values prevents
  49. catastrophic pileups from distinct NaN instances which used to always
  50. have the same hash value but would compare unequal.
  51. A selling point for the above strategy is that it makes it possible
  52. to compute hashes of decimal and binary floating-point numbers
  53. efficiently, even if the exponent of the binary or decimal number
  54. is large. The key point is that
  55. reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
  56. provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
  57. binary or decimal float is never infinity, since the denominator is a power
  58. of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
  59. for nonnegative x,
  60. reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
  61. reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
  62. and reduce(10**e) can be computed efficiently by the usual modular
  63. exponentiation algorithm. For reduce(2**e) it's even better: since
  64. P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
  65. by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
  66. */
  67. Py_hash_t _Py_HashPointer(const void *);
  68. Py_hash_t
  69. _Py_HashDouble(PyObject *inst, double v)
  70. {
  71. int e, sign;
  72. double m;
  73. Py_uhash_t x, y;
  74. if (!Py_IS_FINITE(v)) {
  75. if (Py_IS_INFINITY(v))
  76. return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
  77. else
  78. return _Py_HashPointer(inst);
  79. }
  80. m = frexp(v, &e);
  81. sign = 1;
  82. if (m < 0) {
  83. sign = -1;
  84. m = -m;
  85. }
  86. /* process 28 bits at a time; this should work well both for binary
  87. and hexadecimal floating point. */
  88. x = 0;
  89. while (m) {
  90. x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
  91. m *= 268435456.0; /* 2**28 */
  92. e -= 28;
  93. y = (Py_uhash_t)m; /* pull out integer part */
  94. m -= y;
  95. x += y;
  96. if (x >= _PyHASH_MODULUS)
  97. x -= _PyHASH_MODULUS;
  98. }
  99. /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
  100. e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
  101. x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
  102. x = x * sign;
  103. if (x == (Py_uhash_t)-1)
  104. x = (Py_uhash_t)-2;
  105. return (Py_hash_t)x;
  106. }
  107. Py_hash_t
  108. _Py_HashPointerRaw(const void *p)
  109. {
  110. size_t y = (size_t)p;
  111. /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
  112. excessive hash collisions for dicts and sets */
  113. y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
  114. return (Py_hash_t)y;
  115. }
  116. Py_hash_t
  117. _Py_HashPointer(const void *p)
  118. {
  119. Py_hash_t x = _Py_HashPointerRaw(p);
  120. if (x == -1) {
  121. x = -2;
  122. }
  123. return x;
  124. }
  125. Py_hash_t
  126. _Py_HashBytes(const void *src, Py_ssize_t len)
  127. {
  128. Py_hash_t x;
  129. /*
  130. We make the hash of the empty string be 0, rather than using
  131. (prefix ^ suffix), since this slightly obfuscates the hash secret
  132. */
  133. if (len == 0) {
  134. return 0;
  135. }
  136. #ifdef Py_HASH_STATS
  137. hashstats[(len <= Py_HASH_STATS_MAX) ? len : 0]++;
  138. #endif
  139. #if Py_HASH_CUTOFF > 0
  140. if (len < Py_HASH_CUTOFF) {
  141. /* Optimize hashing of very small strings with inline DJBX33A. */
  142. Py_uhash_t hash;
  143. const unsigned char *p = src;
  144. hash = 5381; /* DJBX33A starts with 5381 */
  145. switch(len) {
  146. /* ((hash << 5) + hash) + *p == hash * 33 + *p */
  147. case 7: hash = ((hash << 5) + hash) + *p++; /* fallthrough */
  148. case 6: hash = ((hash << 5) + hash) + *p++; /* fallthrough */
  149. case 5: hash = ((hash << 5) + hash) + *p++; /* fallthrough */
  150. case 4: hash = ((hash << 5) + hash) + *p++; /* fallthrough */
  151. case 3: hash = ((hash << 5) + hash) + *p++; /* fallthrough */
  152. case 2: hash = ((hash << 5) + hash) + *p++; /* fallthrough */
  153. case 1: hash = ((hash << 5) + hash) + *p++; break;
  154. default:
  155. Py_UNREACHABLE();
  156. }
  157. hash ^= len;
  158. hash ^= (Py_uhash_t) _Py_HashSecret.djbx33a.suffix;
  159. x = (Py_hash_t)hash;
  160. }
  161. else
  162. #endif /* Py_HASH_CUTOFF */
  163. x = PyHash_Func.hash(src, len);
  164. if (x == -1)
  165. return -2;
  166. return x;
  167. }
  168. void
  169. _PyHash_Fini(void)
  170. {
  171. #ifdef Py_HASH_STATS
  172. fprintf(stderr, "len calls total\n");
  173. Py_ssize_t total = 0;
  174. for (int i = 1; i <= Py_HASH_STATS_MAX; i++) {
  175. total += hashstats[i];
  176. fprintf(stderr, "%2i %8zd %8zd\n", i, hashstats[i], total);
  177. }
  178. total += hashstats[0];
  179. fprintf(stderr, "> %8zd %8zd\n", hashstats[0], total);
  180. #endif
  181. }
  182. PyHash_FuncDef *
  183. PyHash_GetFuncDef(void)
  184. {
  185. return &PyHash_Func;
  186. }
  187. /* Optimized memcpy() for Windows */
  188. #ifdef _MSC_VER
  189. # if SIZEOF_PY_UHASH_T == 4
  190. # define PY_UHASH_CPY(dst, src) do { \
  191. dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; \
  192. } while(0)
  193. # elif SIZEOF_PY_UHASH_T == 8
  194. # define PY_UHASH_CPY(dst, src) do { \
  195. dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; \
  196. dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; \
  197. } while(0)
  198. # else
  199. # error SIZEOF_PY_UHASH_T must be 4 or 8
  200. # endif /* SIZEOF_PY_UHASH_T */
  201. #else /* not Windows */
  202. # define PY_UHASH_CPY(dst, src) memcpy(dst, src, SIZEOF_PY_UHASH_T)
  203. #endif /* _MSC_VER */
  204. #if Py_HASH_ALGORITHM == Py_HASH_FNV
  205. /* **************************************************************************
  206. * Modified Fowler-Noll-Vo (FNV) hash function
  207. */
  208. static Py_hash_t
  209. fnv(const void *src, Py_ssize_t len)
  210. {
  211. const unsigned char *p = src;
  212. Py_uhash_t x;
  213. Py_ssize_t remainder, blocks;
  214. union {
  215. Py_uhash_t value;
  216. unsigned char bytes[SIZEOF_PY_UHASH_T];
  217. } block;
  218. #ifdef Py_DEBUG
  219. assert(_Py_HashSecret_Initialized);
  220. #endif
  221. remainder = len % SIZEOF_PY_UHASH_T;
  222. if (remainder == 0) {
  223. /* Process at least one block byte by byte to reduce hash collisions
  224. * for strings with common prefixes. */
  225. remainder = SIZEOF_PY_UHASH_T;
  226. }
  227. blocks = (len - remainder) / SIZEOF_PY_UHASH_T;
  228. x = (Py_uhash_t) _Py_HashSecret.fnv.prefix;
  229. x ^= (Py_uhash_t) *p << 7;
  230. while (blocks--) {
  231. PY_UHASH_CPY(block.bytes, p);
  232. x = (_PyHASH_MULTIPLIER * x) ^ block.value;
  233. p += SIZEOF_PY_UHASH_T;
  234. }
  235. /* add remainder */
  236. for (; remainder > 0; remainder--)
  237. x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++;
  238. x ^= (Py_uhash_t) len;
  239. x ^= (Py_uhash_t) _Py_HashSecret.fnv.suffix;
  240. if (x == (Py_uhash_t) -1) {
  241. x = (Py_uhash_t) -2;
  242. }
  243. return x;
  244. }
  245. static PyHash_FuncDef PyHash_Func = {fnv, "fnv", 8 * SIZEOF_PY_HASH_T,
  246. 16 * SIZEOF_PY_HASH_T};
  247. #endif /* Py_HASH_ALGORITHM == Py_HASH_FNV */
  248. /* **************************************************************************
  249. <MIT License>
  250. Copyright (c) 2013 Marek Majkowski <marek@popcount.org>
  251. Permission is hereby granted, free of charge, to any person obtaining a copy
  252. of this software and associated documentation files (the "Software"), to deal
  253. in the Software without restriction, including without limitation the rights
  254. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  255. copies of the Software, and to permit persons to whom the Software is
  256. furnished to do so, subject to the following conditions:
  257. The above copyright notice and this permission notice shall be included in
  258. all copies or substantial portions of the Software.
  259. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  260. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  261. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  262. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  263. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  264. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  265. THE SOFTWARE.
  266. </MIT License>
  267. Original location:
  268. https://github.com/majek/csiphash/
  269. Solution inspired by code from:
  270. Samuel Neves (supercop/crypto_auth/siphash24/little)
  271. djb (supercop/crypto_auth/siphash24/little2)
  272. Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)
  273. Modified for Python by Christian Heimes:
  274. - C89 / MSVC compatibility
  275. - _rotl64() on Windows
  276. - letoh64() fallback
  277. */
  278. /* byte swap little endian to host endian
  279. * Endian conversion not only ensures that the hash function returns the same
  280. * value on all platforms. It is also required to for a good dispersion of
  281. * the hash values' least significant bits.
  282. */
  283. #if PY_LITTLE_ENDIAN
  284. # define _le64toh(x) ((uint64_t)(x))
  285. #elif defined(__APPLE__)
  286. # define _le64toh(x) OSSwapLittleToHostInt64(x)
  287. #elif defined(HAVE_LETOH64)
  288. # define _le64toh(x) le64toh(x)
  289. #else
  290. # define _le64toh(x) (((uint64_t)(x) << 56) | \
  291. (((uint64_t)(x) << 40) & 0xff000000000000ULL) | \
  292. (((uint64_t)(x) << 24) & 0xff0000000000ULL) | \
  293. (((uint64_t)(x) << 8) & 0xff00000000ULL) | \
  294. (((uint64_t)(x) >> 8) & 0xff000000ULL) | \
  295. (((uint64_t)(x) >> 24) & 0xff0000ULL) | \
  296. (((uint64_t)(x) >> 40) & 0xff00ULL) | \
  297. ((uint64_t)(x) >> 56))
  298. #endif
  299. #ifdef _MSC_VER
  300. # define ROTATE(x, b) _rotl64(x, b)
  301. #else
  302. # define ROTATE(x, b) (uint64_t)( ((x) << (b)) | ( (x) >> (64 - (b))) )
  303. #endif
  304. #define HALF_ROUND(a,b,c,d,s,t) \
  305. a += b; c += d; \
  306. b = ROTATE(b, s) ^ a; \
  307. d = ROTATE(d, t) ^ c; \
  308. a = ROTATE(a, 32);
  309. #define SINGLE_ROUND(v0,v1,v2,v3) \
  310. HALF_ROUND(v0,v1,v2,v3,13,16); \
  311. HALF_ROUND(v2,v1,v0,v3,17,21);
  312. #define DOUBLE_ROUND(v0,v1,v2,v3) \
  313. SINGLE_ROUND(v0,v1,v2,v3); \
  314. SINGLE_ROUND(v0,v1,v2,v3);
  315. static uint64_t
  316. siphash13(uint64_t k0, uint64_t k1, const void *src, Py_ssize_t src_sz) {
  317. uint64_t b = (uint64_t)src_sz << 56;
  318. const uint8_t *in = (const uint8_t*)src;
  319. uint64_t v0 = k0 ^ 0x736f6d6570736575ULL;
  320. uint64_t v1 = k1 ^ 0x646f72616e646f6dULL;
  321. uint64_t v2 = k0 ^ 0x6c7967656e657261ULL;
  322. uint64_t v3 = k1 ^ 0x7465646279746573ULL;
  323. uint64_t t;
  324. uint8_t *pt;
  325. while (src_sz >= 8) {
  326. uint64_t mi;
  327. memcpy(&mi, in, sizeof(mi));
  328. mi = _le64toh(mi);
  329. in += sizeof(mi);
  330. src_sz -= sizeof(mi);
  331. v3 ^= mi;
  332. SINGLE_ROUND(v0,v1,v2,v3);
  333. v0 ^= mi;
  334. }
  335. t = 0;
  336. pt = (uint8_t *)&t;
  337. switch (src_sz) {
  338. case 7: pt[6] = in[6]; /* fall through */
  339. case 6: pt[5] = in[5]; /* fall through */
  340. case 5: pt[4] = in[4]; /* fall through */
  341. case 4: memcpy(pt, in, sizeof(uint32_t)); break;
  342. case 3: pt[2] = in[2]; /* fall through */
  343. case 2: pt[1] = in[1]; /* fall through */
  344. case 1: pt[0] = in[0]; /* fall through */
  345. }
  346. b |= _le64toh(t);
  347. v3 ^= b;
  348. SINGLE_ROUND(v0,v1,v2,v3);
  349. v0 ^= b;
  350. v2 ^= 0xff;
  351. SINGLE_ROUND(v0,v1,v2,v3);
  352. SINGLE_ROUND(v0,v1,v2,v3);
  353. SINGLE_ROUND(v0,v1,v2,v3);
  354. /* modified */
  355. t = (v0 ^ v1) ^ (v2 ^ v3);
  356. return t;
  357. }
  358. #if Py_HASH_ALGORITHM == Py_HASH_SIPHASH24
  359. static uint64_t
  360. siphash24(uint64_t k0, uint64_t k1, const void *src, Py_ssize_t src_sz) {
  361. uint64_t b = (uint64_t)src_sz << 56;
  362. const uint8_t *in = (const uint8_t*)src;
  363. uint64_t v0 = k0 ^ 0x736f6d6570736575ULL;
  364. uint64_t v1 = k1 ^ 0x646f72616e646f6dULL;
  365. uint64_t v2 = k0 ^ 0x6c7967656e657261ULL;
  366. uint64_t v3 = k1 ^ 0x7465646279746573ULL;
  367. uint64_t t;
  368. uint8_t *pt;
  369. while (src_sz >= 8) {
  370. uint64_t mi;
  371. memcpy(&mi, in, sizeof(mi));
  372. mi = _le64toh(mi);
  373. in += sizeof(mi);
  374. src_sz -= sizeof(mi);
  375. v3 ^= mi;
  376. DOUBLE_ROUND(v0,v1,v2,v3);
  377. v0 ^= mi;
  378. }
  379. t = 0;
  380. pt = (uint8_t *)&t;
  381. switch (src_sz) {
  382. case 7: pt[6] = in[6]; /* fall through */
  383. case 6: pt[5] = in[5]; /* fall through */
  384. case 5: pt[4] = in[4]; /* fall through */
  385. case 4: memcpy(pt, in, sizeof(uint32_t)); break;
  386. case 3: pt[2] = in[2]; /* fall through */
  387. case 2: pt[1] = in[1]; /* fall through */
  388. case 1: pt[0] = in[0]; /* fall through */
  389. }
  390. b |= _le64toh(t);
  391. v3 ^= b;
  392. DOUBLE_ROUND(v0,v1,v2,v3);
  393. v0 ^= b;
  394. v2 ^= 0xff;
  395. DOUBLE_ROUND(v0,v1,v2,v3);
  396. DOUBLE_ROUND(v0,v1,v2,v3);
  397. /* modified */
  398. t = (v0 ^ v1) ^ (v2 ^ v3);
  399. return t;
  400. }
  401. #endif
  402. uint64_t
  403. _Py_KeyedHash(uint64_t key, const void *src, Py_ssize_t src_sz)
  404. {
  405. return siphash13(key, 0, src, src_sz);
  406. }
  407. #if Py_HASH_ALGORITHM == Py_HASH_SIPHASH13
  408. static Py_hash_t
  409. pysiphash(const void *src, Py_ssize_t src_sz) {
  410. return (Py_hash_t)siphash13(
  411. _le64toh(_Py_HashSecret.siphash.k0), _le64toh(_Py_HashSecret.siphash.k1),
  412. src, src_sz);
  413. }
  414. static PyHash_FuncDef PyHash_Func = {pysiphash, "siphash13", 64, 128};
  415. #endif
  416. #if Py_HASH_ALGORITHM == Py_HASH_SIPHASH24
  417. static Py_hash_t
  418. pysiphash(const void *src, Py_ssize_t src_sz) {
  419. return (Py_hash_t)siphash24(
  420. _le64toh(_Py_HashSecret.siphash.k0), _le64toh(_Py_HashSecret.siphash.k1),
  421. src, src_sz);
  422. }
  423. static PyHash_FuncDef PyHash_Func = {pysiphash, "siphash24", 64, 128};
  424. #endif
  425. #ifdef __cplusplus
  426. }
  427. #endif