main.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. /*
  2. * Brute force collision tester for 64-bit hashes
  3. * Part of the xxHash project
  4. * Copyright (C) 2019-2020 Yann Collet
  5. *
  6. * GPL v2 License
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * You can contact the author at:
  23. * - xxHash homepage: https://www.xxhash.com
  24. * - xxHash source repository: https://github.com/Cyan4973/xxHash
  25. */
  26. /*
  27. * The collision tester will generate 24 billion hashes (by default),
  28. * and count how many collisions were produced by the 64-bit hash algorithm.
  29. * The optimal amount of collisions for 64-bit is ~18 collisions.
  30. * A good hash should be close to this figure.
  31. *
  32. * This program requires a lot of memory:
  33. * - Either store hash values directly => 192 GB
  34. * - Or use a filter:
  35. * - 32 GB (by default) for the filter itself
  36. * - + ~14 GB for the list of hashes (depending on the filter's outcome)
  37. * Due to these memory constraints, it requires a 64-bit system.
  38. */
  39. /* === Dependencies === */
  40. #include <stdint.h> /* uint64_t */
  41. #include <stdlib.h> /* malloc, free, qsort, exit */
  42. #include <string.h> /* memset */
  43. #include <stdio.h> /* printf, fflush */
  44. #undef NDEBUG /* ensure assert is _not_ disabled */
  45. #include <assert.h>
  46. #include "hashes.h" /* UniHash, hashfn, hashfnTable */
  47. #include "sort.hh" /* sort64 */
  48. typedef enum { ht32, ht64, ht128 } Htype_e;
  49. /* === Debug === */
  50. #define EXIT(...) { printf(__VA_ARGS__); printf("\n"); exit(1); }
  51. static void hexRaw(const void* buffer, size_t size)
  52. {
  53. const unsigned char* p = (const unsigned char*)buffer;
  54. for (size_t i=0; i<size; i++) {
  55. printf("%02X", p[i]);
  56. }
  57. }
  58. void printHash(const void* table, size_t n, Htype_e htype)
  59. {
  60. if ((htype == ht64) || (htype == ht32)){
  61. uint64_t const h64 = ((const uint64_t*)table)[n];
  62. hexRaw(&h64, sizeof(h64));
  63. } else {
  64. assert(htype == ht128);
  65. XXH128_hash_t const h128 = ((const XXH128_hash_t*)table)[n];
  66. hexRaw(&h128, sizeof(h128));
  67. }
  68. }
  69. /* === Generate Random unique Samples to hash === */
  70. /*
  71. * These functions will generate and update a sample to hash.
  72. * initSample() will fill a buffer with random bytes,
  73. * updateSample() will modify one slab in the input buffer.
  74. * updateSample() guarantees it will produce unique samples,
  75. * but it needs to know the total number of samples.
  76. */
  77. static const uint64_t prime64_1 = 11400714785074694791ULL; /* 0b1001111000110111011110011011000110000101111010111100101010000111 */
  78. static const uint64_t prime64_2 = 14029467366897019727ULL; /* 0b1100001010110010101011100011110100100111110101001110101101001111 */
  79. static const uint64_t prime64_3 = 1609587929392839161ULL; /* 0b0001011001010110011001111011000110011110001101110111100111111001 */
  80. static uint64_t avalanche64(uint64_t h64)
  81. {
  82. h64 ^= h64 >> 33;
  83. h64 *= prime64_2;
  84. h64 ^= h64 >> 29;
  85. h64 *= prime64_3;
  86. h64 ^= h64 >> 32;
  87. return h64;
  88. }
  89. static unsigned char randomByte(size_t n)
  90. {
  91. uint64_t n64 = avalanche64(n+1);
  92. n64 *= prime64_1;
  93. return (unsigned char)(n64 >> 56);
  94. }
  95. typedef enum { sf_slab5, sf_sparse } sf_genMode;
  96. #ifdef SLAB5
  97. /*
  98. * Slab5 sample generation.
  99. * This algorithm generates unique inputs flipping on average 16 bits per candidate.
  100. * It is generally much more friendly for most hash algorithms, especially
  101. * weaker ones, as it shuffles more the input.
  102. * The algorithm also avoids overfitting the per4 or per8 ingestion patterns.
  103. */
  104. #define SLAB_SIZE 5
  105. typedef struct {
  106. void* buffer;
  107. size_t size;
  108. sf_genMode mode;
  109. size_t prngSeed;
  110. uint64_t hnb;
  111. } sampleFactory;
  112. static void init_sampleFactory(sampleFactory* sf, uint64_t htotal)
  113. {
  114. uint64_t const minNbSlabs = ((htotal-1) >> 32) + 1;
  115. uint64_t const minSize = minNbSlabs * SLAB_SIZE;
  116. if (sf->size < minSize)
  117. EXIT("sample size must be >= %i bytes for this amount of hashes",
  118. (int)minSize);
  119. unsigned char* const p = (unsigned char*)sf->buffer;
  120. for (size_t n=0; n < sf->size; n++)
  121. p[n] = randomByte(n);
  122. sf->hnb = 0;
  123. }
  124. static sampleFactory*
  125. create_sampleFactory(size_t size, uint64_t htotal, uint64_t seed)
  126. {
  127. sampleFactory* const sf = malloc(sizeof(sampleFactory));
  128. if (!sf) EXIT("not enough memory");
  129. void* const buffer = malloc(size);
  130. if (!buffer) EXIT("not enough memory");
  131. sf->buffer = buffer;
  132. sf->size = size;
  133. sf->mode = sf_slab5;
  134. sf->prngSeed = seed;
  135. init_sampleFactory(sf, htotal);
  136. return sf;
  137. }
  138. static void free_sampleFactory(sampleFactory* sf)
  139. {
  140. if (!sf) return;
  141. free(sf->buffer);
  142. free(sf);
  143. }
  144. static inline void update_sampleFactory(sampleFactory* sf)
  145. {
  146. size_t const nbSlabs = sf->size / SLAB_SIZE;
  147. size_t const SlabNb = sf->hnb % nbSlabs;
  148. sf->hnb++;
  149. char* const ptr = (char*)sf->buffer;
  150. size_t const start = (SlabNb * SLAB_SIZE) + 1;
  151. uint32_t val32;
  152. memcpy(&val32, ptr+start, sizeof(val32));
  153. static const uint32_t prime32_5 = 374761393U;
  154. val32 += prime32_5;
  155. memcpy(ptr+start, &val32, sizeof(val32));
  156. }
  157. #else
  158. /*
  159. * Sparse sample generation.
  160. * This is the default pattern generator.
  161. * It only flips one bit at a time (mostly).
  162. * Low hamming distance scenario is more difficult for weak hash algorithms.
  163. * Note that CRC is immune to this scenario, since they are specifically
  164. * designed to detect low hamming distances.
  165. * Prefer the Slab5 pattern generator for collisions on CRC algorithms.
  166. */
  167. #define SPARSE_LEVEL_MAX 15
  168. /* Nb of combinations of m bits in a register of n bits */
  169. static double Cnm(int n, int m)
  170. {
  171. assert(n > 0);
  172. assert(m > 0);
  173. assert(m <= m);
  174. double acc = 1;
  175. for (int i=0; i<m; i++) {
  176. acc *= n - i;
  177. acc /= 1 + i;
  178. }
  179. return acc;
  180. }
  181. static int enoughCombos(size_t size, uint64_t htotal)
  182. {
  183. if (size < 2) return 0; /* ensure no multiplication by negative */
  184. uint64_t acc = 0;
  185. uint64_t const srcBits = size * 8; assert(srcBits < INT_MAX);
  186. int nbBitsSet = 0;
  187. while (acc < htotal) {
  188. nbBitsSet++;
  189. if (nbBitsSet >= SPARSE_LEVEL_MAX) return 0;
  190. acc += (uint64_t)Cnm((int)srcBits, nbBitsSet);
  191. }
  192. return 1;
  193. }
  194. typedef struct {
  195. void* buffer;
  196. size_t size;
  197. sf_genMode mode;
  198. /* sparse */
  199. size_t bitIdx[SPARSE_LEVEL_MAX];
  200. int level;
  201. size_t maxBitIdx;
  202. /* slab5 */
  203. size_t nbSlabs;
  204. size_t current;
  205. size_t prngSeed;
  206. } sampleFactory;
  207. static void init_sampleFactory(sampleFactory* sf, uint64_t htotal)
  208. {
  209. if (!enoughCombos(sf->size, htotal)) {
  210. EXIT("sample size must be larger for this amount of hashes");
  211. }
  212. memset(sf->bitIdx, 0, sizeof(sf->bitIdx));
  213. sf->level = 0;
  214. unsigned char* const p = (unsigned char*)sf->buffer;
  215. for (size_t n=0; n<sf->size; n++)
  216. p[n] = randomByte(sf->prngSeed + n);
  217. }
  218. static sampleFactory*
  219. create_sampleFactory(size_t size, uint64_t htotal, uint64_t seed)
  220. {
  221. sampleFactory* const sf = malloc(sizeof(sampleFactory));
  222. if (!sf) EXIT("not enough memory");
  223. void* const buffer = malloc(size);
  224. if (!buffer) EXIT("not enough memory");
  225. sf->buffer = buffer;
  226. sf->size = size;
  227. sf->mode = sf_sparse;
  228. sf->maxBitIdx = size * 8;
  229. sf->prngSeed = seed;
  230. init_sampleFactory(sf, htotal);
  231. return sf;
  232. }
  233. static void free_sampleFactory(sampleFactory* sf)
  234. {
  235. if (!sf) return;
  236. free(sf->buffer);
  237. free(sf);
  238. }
  239. static void flipbit(void* buffer, uint64_t bitID)
  240. {
  241. size_t const pos = bitID >> 3;
  242. unsigned char const mask = (unsigned char)(1 << (bitID & 7));
  243. unsigned char* const p = (unsigned char*)buffer;
  244. p[pos] ^= mask;
  245. }
  246. static int updateBit(void* buffer, size_t* bitIdx, int level, size_t max)
  247. {
  248. if (level==0) return 0; /* can't progress further */
  249. flipbit(buffer, bitIdx[level]); /* erase previous bits */
  250. if (bitIdx[level] < max-1) { /* simple case: go to next bit */
  251. bitIdx[level]++;
  252. flipbit(buffer, bitIdx[level]); /* set new bit */
  253. return 1;
  254. }
  255. /* reached last bit: need to update a bit from lower level */
  256. if (!updateBit(buffer, bitIdx, level-1, max-1)) return 0;
  257. bitIdx[level] = bitIdx[level-1] + 1;
  258. flipbit(buffer, bitIdx[level]); /* set new bit */
  259. return 1;
  260. }
  261. static inline void update_sampleFactory(sampleFactory* sf)
  262. {
  263. if (!updateBit(sf->buffer, sf->bitIdx, sf->level, sf->maxBitIdx)) {
  264. /* no more room => move to next level */
  265. sf->level++;
  266. assert(sf->level < SPARSE_LEVEL_MAX);
  267. /* set new bits */
  268. for (int i=1; i <= sf->level; i++) {
  269. sf->bitIdx[i] = (size_t)(i-1);
  270. flipbit(sf->buffer, sf->bitIdx[i]);
  271. }
  272. }
  273. }
  274. #endif /* pattern generator selection */
  275. /* === Candidate Filter === */
  276. typedef unsigned char Filter;
  277. Filter* create_Filter(int bflog)
  278. {
  279. assert(bflog < 64 && bflog > 1);
  280. size_t bfsize = (size_t)1 << bflog;
  281. Filter* bf = malloc(bfsize);
  282. assert(((void)"Filter creation failed", bf));
  283. memset(bf, 0, bfsize);
  284. return bf;
  285. }
  286. void free_Filter(Filter* bf)
  287. {
  288. free(bf);
  289. }
  290. #ifdef FILTER_1_PROBE
  291. /*
  292. * Attach hash to a slot
  293. * return: Nb of potential collision candidates detected
  294. * 0: position not yet occupied
  295. * 2: position previously occupied by a single candidate
  296. * 1: position already occupied by multiple candidates
  297. */
  298. inline int Filter_insert(Filter* bf, int bflog, uint64_t hash)
  299. {
  300. int const slotNb = hash & 3;
  301. int const shift = slotNb * 2 ;
  302. size_t const bfmask = ((size_t)1 << bflog) - 1;
  303. size_t const pos = (hash >> 2) & bfmask;
  304. int const existingCandidates = ((((unsigned char*)bf)[pos]) >> shift) & 3;
  305. static const int addCandidates[4] = { 0, 2, 1, 1 };
  306. static const int nextValue[4] = { 1, 2, 3, 3 };
  307. ((unsigned char*)bf)[pos] |= (unsigned char)(nextValue[existingCandidates] << shift);
  308. return addCandidates[existingCandidates];
  309. }
  310. /*
  311. * Check if provided 64-bit hash is a collision candidate
  312. * Requires the slot to be occupied by at least 2 candidates.
  313. * return >0 if hash is a collision candidate
  314. * 0 otherwise (slot unoccupied, or only one candidate)
  315. * note: unoccupied slots should not happen in this algorithm,
  316. * since all hashes are supposed to have been inserted at least once.
  317. */
  318. inline int Filter_check(const Filter* bf, int bflog, uint64_t hash)
  319. {
  320. int const slotNb = hash & 3;
  321. int const shift = slotNb * 2;
  322. size_t const bfmask = ((size_t)1 << bflog) - 1;
  323. size_t const pos = (hash >> 2) & bfmask;
  324. return (((const unsigned char*)bf)[pos]) >> (shift+1) & 1;
  325. }
  326. #else
  327. /*
  328. * 2-probes strategy,
  329. * more efficient at filtering candidates,
  330. * requires filter size to be > nb of hashes
  331. */
  332. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  333. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  334. /*
  335. * Attach hash to 2 slots
  336. * return: Nb of potential candidates detected
  337. * 0: position not yet occupied
  338. * 2: position previously occupied by a single candidate (at most)
  339. * 1: position already occupied by multiple candidates
  340. */
  341. static inline int Filter_insert(Filter* bf, int bflog, uint64_t hash)
  342. {
  343. hash = avalanche64(hash);
  344. unsigned const slot1 = hash & 255;
  345. hash >>= 8;
  346. unsigned const slot2 = hash & 255;
  347. hash >>= 8;
  348. size_t const fclmask = ((size_t)1 << (bflog-6)) - 1;
  349. size_t const cacheLineNb = hash & fclmask;
  350. size_t const pos1 = (cacheLineNb << 6) + (slot1 >> 2);
  351. unsigned const shift1 = (slot1 & 3) * 2;
  352. unsigned const ex1 = (bf[pos1] >> shift1) & 3;
  353. size_t const pos2 = (cacheLineNb << 6) + (slot2 >> 2);
  354. unsigned const shift2 = (slot2 & 3) * 2;
  355. unsigned const ex2 = (bf[pos2] >> shift2) & 3;
  356. unsigned const existing = MIN(ex1, ex2);
  357. static const int addCandidates[4] = { 0, 2, 1, 1 };
  358. static const unsigned nextValue[4] = { 1, 2, 3, 3 };
  359. bf[pos1] &= (Filter)(~(3 << shift1)); /* erase previous value */
  360. bf[pos1] |= (Filter)(MAX(ex1, nextValue[existing]) << shift1);
  361. bf[pos2] |= (Filter)(MAX(ex2, nextValue[existing]) << shift2);
  362. return addCandidates[existing];
  363. }
  364. /*
  365. * Check if provided 64-bit hash is a collision candidate
  366. * Requires the slot to be occupied by at least 2 candidates.
  367. * return >0 if hash is a collision candidate
  368. * 0 otherwise (slot unoccupied, or only one candidate)
  369. * note: unoccupied slots should not happen in this algorithm,
  370. * since all hashes are supposed to have been inserted at least once.
  371. */
  372. static inline int Filter_check(const Filter* bf, int bflog, uint64_t hash)
  373. {
  374. hash = avalanche64(hash);
  375. unsigned const slot1 = hash & 255;
  376. hash >>= 8;
  377. unsigned const slot2 = hash & 255;
  378. hash >>= 8;
  379. size_t const fclmask = ((size_t)1 << (bflog-6)) - 1;
  380. size_t const cacheLineNb = hash & fclmask;
  381. size_t const pos1 = (cacheLineNb << 6) + (slot1 >> 2);
  382. unsigned const shift1 = (slot1 & 3) * 2;
  383. unsigned const ex1 = (bf[pos1] >> shift1) & 3;
  384. size_t const pos2 = (cacheLineNb << 6) + (slot2 >> 2);
  385. unsigned const shift2 = (slot2 & 3) * 2;
  386. unsigned const ex2 = (bf[pos2] >> shift2) & 3;
  387. return (ex1 >= 2) && (ex2 >= 2);
  388. }
  389. #endif // FILTER_1_PROBE
  390. /* === Display === */
  391. #include <time.h> /* clock_t, clock, time_t, time, difftime */
  392. void update_indicator(uint64_t v, uint64_t total)
  393. {
  394. static clock_t start = 0;
  395. if (start==0) start = clock();
  396. clock_t const updateRate = CLOCKS_PER_SEC / 2;
  397. clock_t const clockSpan = (clock_t)(clock() - start);
  398. if (clockSpan > updateRate) {
  399. start = clock();
  400. assert(v <= total);
  401. assert(total > 0);
  402. double share = ((double)v / (double)total) * 100;
  403. printf("%6.2f%% (%llu) \r", share, (unsigned long long)v);
  404. fflush(NULL);
  405. }
  406. }
  407. /* note: not thread safe */
  408. const char* displayDelay(double delay_s)
  409. {
  410. static char delayString[50];
  411. memset(delayString, 0, sizeof(delayString));
  412. int const mn = ((int)delay_s / 60) % 60;
  413. int const h = (int)delay_s / 3600;
  414. int const sec = (int)delay_s % 60;
  415. char* p = delayString;
  416. if (h) sprintf(p, "%i h ", h);
  417. if (mn || h) {
  418. p = delayString + strlen(delayString);
  419. sprintf(p, "%i mn ", mn);
  420. }
  421. p = delayString + strlen(delayString);
  422. sprintf(p, "%is ", sec);
  423. return delayString;
  424. }
  425. /* === Math === */
  426. static double power(uint64_t base, int p)
  427. {
  428. double value = 1;
  429. assert(p>=0);
  430. for (int i=0; i<p; i++) {
  431. value *= (double)base;
  432. }
  433. return value;
  434. }
  435. static double estimateNbCollisions(uint64_t nbH, int nbBits)
  436. {
  437. return ((double)nbH * (double)(nbH-1)) / power(2, nbBits+1);
  438. }
  439. static int highestBitSet(uint64_t v)
  440. {
  441. assert(v!=0);
  442. int bitId = 0;
  443. while (v >>= 1) bitId++;
  444. return bitId;
  445. }
  446. /* === Filter and search collisions === */
  447. #undef NDEBUG /* ensure assert is not disabled */
  448. #include <assert.h>
  449. /* will recommend 24 billion samples for 64-bit hashes,
  450. * expecting 18 collisions for a good 64-bit hash */
  451. #define NB_BITS_MAX 64 /* can't store nor analyze hash wider than 64-bits for the time being */
  452. uint64_t select_nbh(int nbBits)
  453. {
  454. assert(nbBits > 0);
  455. if (nbBits > NB_BITS_MAX) nbBits = NB_BITS_MAX;
  456. double targetColls = (double)((128 + 17) - (nbBits * 2));
  457. uint64_t nbH = 24;
  458. while (estimateNbCollisions(nbH, nbBits) < targetColls) nbH *= 2;
  459. return nbH;
  460. }
  461. typedef struct {
  462. uint64_t nbCollisions;
  463. } searchCollisions_results;
  464. typedef struct {
  465. uint64_t nbH;
  466. uint64_t mask;
  467. uint64_t maskSelector;
  468. size_t sampleSize;
  469. uint64_t prngSeed;
  470. int filterLog; /* <0 = disable filter; 0 = auto-size; */
  471. int hashID;
  472. int display;
  473. int nbThreads;
  474. searchCollisions_results* resultPtr;
  475. } searchCollisions_parameters;
  476. #define DISPLAY(...) { if (display) printf(__VA_ARGS__); }
  477. static int isEqual(void* hTablePtr, size_t index1, size_t index2, Htype_e htype)
  478. {
  479. if ((htype == ht64) || (htype == ht32)) {
  480. uint64_t const h1 = ((const uint64_t*)hTablePtr)[index1];
  481. uint64_t const h2 = ((const uint64_t*)hTablePtr)[index2];
  482. return (h1 == h2);
  483. } else {
  484. assert(htype == ht128);
  485. XXH128_hash_t const h1 = ((const XXH128_hash_t*)hTablePtr)[index1];
  486. XXH128_hash_t const h2 = ((const XXH128_hash_t*)hTablePtr)[index2];
  487. return XXH128_isEqual(h1, h2);
  488. }
  489. }
  490. static int isHighEqual(void* hTablePtr, size_t index1, size_t index2, Htype_e htype, int rShift)
  491. {
  492. uint64_t h1, h2;
  493. if ((htype == ht64) || (htype == ht32)) {
  494. h1 = ((const uint64_t*)hTablePtr)[index1];
  495. h2 = ((const uint64_t*)hTablePtr)[index2];
  496. } else {
  497. assert(htype == ht128);
  498. h1 = ((const XXH128_hash_t*)hTablePtr)[index1].high64;
  499. h2 = ((const XXH128_hash_t*)hTablePtr)[index2].high64;
  500. assert(rShift >= 64);
  501. rShift -= 64;
  502. }
  503. assert(0 <= rShift && rShift < 64);
  504. return (h1 >> rShift) == (h2 >> rShift);
  505. }
  506. /* assumption: (htype*)hTablePtr[index] is valid */
  507. static void addHashCandidate(void* hTablePtr, UniHash h, Htype_e htype, size_t index)
  508. {
  509. if ((htype == ht64) || (htype == ht32)) {
  510. ((uint64_t*)hTablePtr)[index] = h.h64;
  511. } else {
  512. assert(htype == ht128);
  513. ((XXH128_hash_t*)hTablePtr)[index] = h.h128;
  514. }
  515. }
  516. static int getNbBits_fromHtype(Htype_e htype) {
  517. switch(htype) {
  518. case ht32: return 32;
  519. case ht64: return 64;
  520. case ht128:return 128;
  521. default: EXIT("hash size not supported");
  522. }
  523. }
  524. static Htype_e getHtype_fromHbits(int nbBits) {
  525. switch(nbBits) {
  526. case 32 : return ht32;
  527. case 64 : return ht64;
  528. case 128: return ht128;
  529. default: EXIT("hash size not supported");
  530. }
  531. }
  532. static size_t search_collisions(
  533. searchCollisions_parameters param)
  534. {
  535. uint64_t totalH = param.nbH;
  536. const uint64_t hMask = param.mask;
  537. const uint64_t hSelector = param.maskSelector;
  538. int bflog = param.filterLog;
  539. const int filter = (param.filterLog >= 0);
  540. const size_t sampleSize = param.sampleSize;
  541. const int hashID = param.hashID;
  542. const Htype_e htype = getHtype_fromHbits(hashfnTable[hashID].bits);
  543. const int display = param.display;
  544. /* init */
  545. sampleFactory* const sf = create_sampleFactory(sampleSize, totalH, param.prngSeed);
  546. if (!sf) EXIT("not enough memory");
  547. //const char* const hname = hashfnTable[hashID].name;
  548. hashfn const hfunction = hashfnTable[hashID].fn;
  549. int const hwidth = hashfnTable[hashID].bits;
  550. if (totalH == 0) totalH = select_nbh(hwidth);
  551. if (bflog == 0) bflog = highestBitSet(totalH) + 1; /* auto-size filter */
  552. uint64_t const bfsize = (1ULL << bflog);
  553. /* === filter hashes (optional) === */
  554. Filter* bf = NULL;
  555. uint64_t nbPresents = totalH;
  556. if (filter) {
  557. time_t const filterTBegin = time(NULL);
  558. DISPLAY(" Creating filter (%i GB) \n", (int)(bfsize >> 30));
  559. bf = create_Filter(bflog);
  560. if (!bf) EXIT("not enough memory for filter");
  561. DISPLAY(" Generate %llu hashes from samples of %u bytes \n",
  562. (unsigned long long)totalH, (unsigned)sampleSize);
  563. nbPresents = 0;
  564. for (uint64_t n=0; n < totalH; n++) {
  565. if (display && ((n&0xFFFFF) == 1) )
  566. update_indicator(n, totalH);
  567. update_sampleFactory(sf);
  568. UniHash const h = hfunction(sf->buffer, sampleSize);
  569. if ((h.h64 & hMask) != hSelector) continue;
  570. nbPresents += (uint64_t)Filter_insert(bf, bflog, h.h64);
  571. }
  572. if (nbPresents==0) {
  573. DISPLAY(" Analysis completed: No collision detected \n");
  574. if (param.resultPtr) param.resultPtr->nbCollisions = 0;
  575. free_Filter(bf);
  576. free_sampleFactory(sf);
  577. return 0;
  578. }
  579. { double const filterDelay = difftime(time(NULL), filterTBegin);
  580. DISPLAY(" Generation and filter completed in %s, detected up to %llu candidates \n",
  581. displayDelay(filterDelay), (unsigned long long) nbPresents);
  582. } }
  583. /* === store hash candidates: duplicates will be present here === */
  584. time_t const storeTBegin = time(NULL);
  585. size_t const hashByteSize = (htype == ht128) ? 16 : 8;
  586. size_t const tableSize = (nbPresents+1) * hashByteSize;
  587. assert(tableSize > nbPresents); /* check tableSize calculation overflow */
  588. DISPLAY(" Storing hash candidates (%i MB) \n", (int)(tableSize >> 20));
  589. /* Generate and store hashes */
  590. void* const hashCandidates = malloc(tableSize);
  591. if (!hashCandidates) EXIT("not enough memory to store candidates");
  592. init_sampleFactory(sf, totalH);
  593. size_t nbCandidates = 0;
  594. for (uint64_t n=0; n < totalH; n++) {
  595. if (display && ((n&0xFFFFF) == 1) ) update_indicator(n, totalH);
  596. update_sampleFactory(sf);
  597. UniHash const h = hfunction(sf->buffer, sampleSize);
  598. if ((h.h64 & hMask) != hSelector) continue;
  599. if (filter) {
  600. if (Filter_check(bf, bflog, h.h64)) {
  601. assert(nbCandidates < nbPresents);
  602. addHashCandidate(hashCandidates, h, htype, nbCandidates++);
  603. }
  604. } else {
  605. assert(nbCandidates < nbPresents);
  606. addHashCandidate(hashCandidates, h, htype, nbCandidates++);
  607. }
  608. }
  609. if (nbCandidates < nbPresents) {
  610. /* Try to mitigate gnuc_quicksort behavior, by reducing allocated memory,
  611. * since gnuc_quicksort uses a lot of additional memory for mergesort */
  612. void* const checkPtr = realloc(hashCandidates, nbCandidates * hashByteSize);
  613. assert(checkPtr != NULL);
  614. assert(checkPtr == hashCandidates); /* simplification: since we are reducing the size,
  615. * we hope to keep the same ptr position.
  616. * Otherwise, hashCandidates must be mutable. */
  617. DISPLAY(" List of hashes reduced to %u MB from %u MB (saved %u MB) \n",
  618. (unsigned)((nbCandidates * hashByteSize) >> 20),
  619. (unsigned)(tableSize >> 20),
  620. (unsigned)((tableSize - (nbCandidates * hashByteSize)) >> 20) );
  621. }
  622. double const storeTDelay = difftime(time(NULL), storeTBegin);
  623. DISPLAY(" Stored %llu hash candidates in %s \n",
  624. (unsigned long long) nbCandidates, displayDelay(storeTDelay));
  625. free_Filter(bf);
  626. free_sampleFactory(sf);
  627. /* === step 3: look for duplicates === */
  628. time_t const sortTBegin = time(NULL);
  629. DISPLAY(" Sorting candidates... ");
  630. fflush(NULL);
  631. if ((htype == ht64) || (htype == ht32)) {
  632. /*
  633. * Use C++'s std::sort, as it's faster than C stdlib's qsort, and
  634. * doesn't suffer from gnuc_libsort's memory expansion
  635. */
  636. sort64(hashCandidates, nbCandidates);
  637. } else {
  638. assert(htype == ht128);
  639. sort128(hashCandidates, nbCandidates); /* sort with custom comparator */
  640. }
  641. double const sortTDelay = difftime(time(NULL), sortTBegin);
  642. DISPLAY(" Completed in %s \n", displayDelay(sortTDelay));
  643. /* scan and count duplicates */
  644. time_t const countBegin = time(NULL);
  645. DISPLAY(" Looking for duplicates: ");
  646. fflush(NULL);
  647. size_t collisions = 0;
  648. for (size_t n=1; n<nbCandidates; n++) {
  649. if (isEqual(hashCandidates, n, n-1, htype)) {
  650. #if defined(COL_DISPLAY_DUPLICATES)
  651. printf("collision: ");
  652. printHash(hashCandidates, n, htype);
  653. printf(" / ");
  654. printHash(hashCandidates, n-1, htype);
  655. printf(" \n");
  656. #endif
  657. collisions++;
  658. } }
  659. if (!filter /* all candidates */ && display /*single thead*/ ) {
  660. /* check partial bitfields (high bits) */
  661. DISPLAY(" \n");
  662. int const hashBits = getNbBits_fromHtype(htype);
  663. double worstRatio = 0.;
  664. int worstNbHBits = 0;
  665. for (int nbHBits = 1; nbHBits < hashBits; nbHBits++) {
  666. uint64_t const nbSlots = (uint64_t)1 << nbHBits;
  667. double const expectedCollisions = estimateNbCollisions(nbCandidates, nbHBits);
  668. if ( (nbSlots > nbCandidates * 100) /* within range for meaningfull collision analysis results */
  669. && (expectedCollisions > 18.0) ) {
  670. int const rShift = hashBits - nbHBits;
  671. size_t HBits_collisions = 0;
  672. for (size_t n=1; n<nbCandidates; n++) {
  673. if (isHighEqual(hashCandidates, n, n-1, htype, rShift)) {
  674. HBits_collisions++;
  675. } }
  676. double const collisionRatio = (double)HBits_collisions / expectedCollisions;
  677. if (collisionRatio > 2.0) DISPLAY("WARNING !!! ===> ");
  678. DISPLAY(" high %i bits: %zu collision (%.1f expected): x%.2f \n",
  679. nbHBits, HBits_collisions, expectedCollisions, collisionRatio);
  680. if (collisionRatio > worstRatio) {
  681. worstNbHBits = nbHBits;
  682. worstRatio = collisionRatio;
  683. } } }
  684. DISPLAY("Worst collision ratio at %i high bits: x%.2f \n",
  685. worstNbHBits, worstRatio);
  686. }
  687. double const countDelay = difftime(time(NULL), countBegin);
  688. DISPLAY(" Completed in %s \n", displayDelay(countDelay));
  689. /* clean and exit */
  690. free (hashCandidates);
  691. #if 0 /* debug */
  692. for (size_t n=0; n<nbCandidates; n++)
  693. printf("0x%016llx \n", (unsigned long long)hashCandidates[n]);
  694. #endif
  695. if (param.resultPtr) param.resultPtr->nbCollisions = collisions;
  696. return collisions;
  697. }
  698. #if defined(__MACH__) || defined(__linux__)
  699. #include <sys/resource.h>
  700. static size_t getProcessMemUsage(int children)
  701. {
  702. struct rusage stats;
  703. if (getrusage(children ? RUSAGE_CHILDREN : RUSAGE_SELF, &stats) == 0)
  704. return (size_t)stats.ru_maxrss;
  705. return 0;
  706. }
  707. #else
  708. static size_t getProcessMemUsage(int ignore) { return 0; }
  709. #endif
  710. void time_collisions(searchCollisions_parameters param)
  711. {
  712. uint64_t totalH = param.nbH;
  713. int hashID = param.hashID;
  714. int display = param.display;
  715. /* init */
  716. assert(0 <= hashID && hashID < HASH_FN_TOTAL);
  717. //const char* const hname = hashfnTable[hashID].name;
  718. int const hwidth = hashfnTable[hashID].bits;
  719. if (totalH == 0) totalH = select_nbh(hwidth);
  720. double const targetColls = estimateNbCollisions(totalH, hwidth);
  721. /* Start the timer to measure start/end of hashing + collision detection. */
  722. time_t const programTBegin = time(NULL);
  723. /* Generate hashes, and count collisions */
  724. size_t const collisions = search_collisions(param);
  725. /* display results */
  726. double const programTDelay = difftime(time(NULL), programTBegin);
  727. size_t const programBytesSelf = getProcessMemUsage(0);
  728. size_t const programBytesChildren = getProcessMemUsage(1);
  729. DISPLAY("\n\n");
  730. DISPLAY("===> Found %llu collisions (x%.2f, %.1f expected) in %s\n",
  731. (unsigned long long)collisions,
  732. (double)collisions / targetColls,
  733. targetColls,
  734. displayDelay(programTDelay));
  735. if (programBytesSelf)
  736. DISPLAY("===> MaxRSS(self) %zuMB, MaxRSS(children) %zuMB\n",
  737. programBytesSelf>>20,
  738. programBytesChildren>>20);
  739. DISPLAY("------------------------------------------ \n");
  740. }
  741. // wrapper for pthread interface
  742. void MT_searchCollisions(void* payload)
  743. {
  744. search_collisions(*(searchCollisions_parameters*)payload);
  745. }
  746. /* === Command Line === */
  747. /*!
  748. * readU64FromChar():
  749. * Allows and interprets K, KB, KiB, M, MB and MiB suffix.
  750. * Will also modify `*stringPtr`, advancing it to the position where it stopped reading.
  751. */
  752. static uint64_t readU64FromChar(const char** stringPtr)
  753. {
  754. static uint64_t const max = (((uint64_t)(-1)) / 10) - 1;
  755. uint64_t result = 0;
  756. while ((**stringPtr >='0') && (**stringPtr <='9')) {
  757. assert(result < max);
  758. result *= 10;
  759. result += (unsigned)(**stringPtr - '0');
  760. (*stringPtr)++ ;
  761. }
  762. if ((**stringPtr=='K') || (**stringPtr=='M') || (**stringPtr=='G')) {
  763. uint64_t const maxK = ((uint64_t)(-1)) >> 10;
  764. assert(result < maxK);
  765. result <<= 10;
  766. if ((**stringPtr=='M') || (**stringPtr=='G')) {
  767. assert(result < maxK);
  768. result <<= 10;
  769. if (**stringPtr=='G') {
  770. assert(result < maxK);
  771. result <<= 10;
  772. }
  773. }
  774. (*stringPtr)++; /* skip `K` or `M` */
  775. if (**stringPtr=='i') (*stringPtr)++;
  776. if (**stringPtr=='B') (*stringPtr)++;
  777. }
  778. return result;
  779. }
  780. /**
  781. * longCommandWArg():
  782. * Checks if *stringPtr is the same as longCommand.
  783. * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
  784. * @return 0 and doesn't modify *stringPtr otherwise.
  785. */
  786. static int longCommandWArg(const char** stringPtr, const char* longCommand)
  787. {
  788. assert(longCommand); assert(stringPtr); assert(*stringPtr);
  789. size_t const comSize = strlen(longCommand);
  790. int const result = !strncmp(*stringPtr, longCommand, comSize);
  791. if (result) *stringPtr += comSize;
  792. return result;
  793. }
  794. #include "pool.h"
  795. /*
  796. * As some hashes use different algorithms depending on input size,
  797. * it can be necessary to test multiple input sizes
  798. * to paint an accurate picture of collision performance
  799. */
  800. #define SAMPLE_SIZE_DEFAULT 256
  801. #define HASHFN_ID_DEFAULT 0
  802. void help(const char* exeName)
  803. {
  804. printf("usage: %s [hashName] [opt] \n\n", exeName);
  805. printf("list of hashNames:");
  806. printf("%s ", hashfnTable[0].name);
  807. for (int i=1; i < HASH_FN_TOTAL; i++) {
  808. printf(", %s ", hashfnTable[i].name);
  809. }
  810. printf(" \n");
  811. printf("Default hashName is %s\n", hashfnTable[HASHFN_ID_DEFAULT].name);
  812. printf(" \n");
  813. printf("Optional parameters: \n");
  814. printf(" --nbh=NB Select nb of hashes to generate (%llu by default) \n", (unsigned long long)select_nbh(64));
  815. printf(" --filter Activates the filter. Slower, but reduces memory usage for the same nb of hashes.\n");
  816. printf(" --threadlog=NB Use 2^NB threads.\n");
  817. printf(" --len=MB Set length of the input (%i bytes by default) \n", SAMPLE_SIZE_DEFAULT);
  818. }
  819. int bad_argument(const char* exeName)
  820. {
  821. printf("incorrect command: \n");
  822. help(exeName);
  823. return 1;
  824. }
  825. int main(int argc, const char** argv)
  826. {
  827. if (sizeof(size_t) < 8) return 1; // cannot work on systems without ability to allocate objects >= 4 GB
  828. assert(argc > 0);
  829. const char* const exeName = argv[0];
  830. uint64_t totalH = 0; /* auto, based on nbBits */
  831. int bflog = 0; /* auto */
  832. int filter = 0; /* disabled */
  833. size_t sampleSize = SAMPLE_SIZE_DEFAULT;
  834. int hashID = HASHFN_ID_DEFAULT;
  835. int threadlog = 0;
  836. uint64_t prngSeed = 0;
  837. int arg_nb;
  838. for (arg_nb = 1; arg_nb < argc; arg_nb++) {
  839. const char** arg = argv + arg_nb;
  840. if (!strcmp(*arg, "-h")) { help(exeName); return 0; }
  841. if (longCommandWArg(arg, "-T")) { threadlog = (int)readU64FromChar(arg); continue; }
  842. if (!strcmp(*arg, "--filter")) { filter=1; continue; }
  843. if (!strcmp(*arg, "--no-filter")) { filter=0; continue; }
  844. if (longCommandWArg(arg, "--seed")) { prngSeed = readU64FromChar(arg); continue; }
  845. if (longCommandWArg(arg, "--nbh=")) { totalH = readU64FromChar(arg); continue; }
  846. if (longCommandWArg(arg, "--filter=")) { filter=1; bflog = (int)readU64FromChar(arg); assert(bflog < 64); continue; }
  847. if (longCommandWArg(arg, "--filterlog=")) { filter=1; bflog = (int)readU64FromChar(arg); assert(bflog < 64); continue; }
  848. if (longCommandWArg(arg, "--size=")) { sampleSize = (size_t)readU64FromChar(arg); continue; }
  849. if (longCommandWArg(arg, "--len=")) { sampleSize = (size_t)readU64FromChar(arg); continue; }
  850. if (longCommandWArg(arg, "--threadlog=")) { threadlog = (int)readU64FromChar(arg); continue; }
  851. /* argument understood as hash name (must be correct) */
  852. int hnb;
  853. for (hnb=0; hnb < HASH_FN_TOTAL; hnb++) {
  854. if (!strcmp(*arg, hashfnTable[hnb].name)) { hashID = hnb; break; }
  855. }
  856. if (hnb == HASH_FN_TOTAL) return bad_argument(exeName);
  857. }
  858. /* init */
  859. const char* const hname = hashfnTable[hashID].name;
  860. int const hwidth = hashfnTable[hashID].bits;
  861. if (totalH == 0) totalH = select_nbh(hwidth);
  862. double const targetColls = estimateNbCollisions(totalH, hwidth);
  863. if (bflog == 0) bflog = highestBitSet(totalH) + 1; /* auto-size filter */
  864. if (!filter) bflog = -1; // disable filter
  865. if (sizeof(size_t) < 8)
  866. EXIT("This program has not been validated on architectures other than "
  867. "64bit \n");
  868. printf(" *** Collision tester for 64+ bit hashes *** \n\n");
  869. printf("Testing %s algorithm (%i-bit) \n", hname, hwidth);
  870. printf("This program will allocate a lot of memory,\n");
  871. printf("generate %llu %i-bit hashes from samples of %u bytes, \n",
  872. (unsigned long long)totalH, hwidth, (unsigned)sampleSize);
  873. printf("and attempt to produce %.0f collisions. \n\n", targetColls);
  874. int const nbThreads = 1 << threadlog;
  875. if (nbThreads <= 0) EXIT("Invalid --threadlog value.");
  876. if (nbThreads == 1) {
  877. searchCollisions_parameters params;
  878. params.nbH = totalH;
  879. params.mask = 0;
  880. params.maskSelector = 0;
  881. params.sampleSize = sampleSize;
  882. params.filterLog = bflog;
  883. params.hashID = hashID;
  884. params.display = 1;
  885. params.resultPtr = NULL;
  886. params.prngSeed = prngSeed;
  887. params.nbThreads = 1;
  888. time_collisions(params);
  889. } else { /* nbThreads > 1 */
  890. /* use multithreading */
  891. if (threadlog >= 30) EXIT("too many threads requested");
  892. if ((uint64_t)nbThreads > (totalH >> 16))
  893. EXIT("too many threads requested");
  894. if (bflog > 0 && threadlog > (bflog-10))
  895. EXIT("too many threads requested");
  896. printf("using %i threads ... \n", nbThreads);
  897. /* allocation */
  898. time_t const programTBegin = time(NULL);
  899. POOL_ctx* const pt = POOL_create((size_t)nbThreads, 1);
  900. if (!pt) EXIT("not enough memory for threads");
  901. searchCollisions_results* const MTresults = calloc (sizeof(searchCollisions_results), (size_t)nbThreads);
  902. if (!MTresults) EXIT("not enough memory");
  903. searchCollisions_parameters* const MTparams = calloc (sizeof(searchCollisions_parameters), (size_t)nbThreads);
  904. if (!MTparams) EXIT("not enough memory");
  905. /* distribute jobs */
  906. for (int tnb=0; tnb<nbThreads; tnb++) {
  907. MTparams[tnb].nbH = totalH;
  908. MTparams[tnb].mask = (uint64_t)nbThreads - 1;
  909. MTparams[tnb].sampleSize = sampleSize;
  910. MTparams[tnb].filterLog = bflog ? bflog - threadlog : 0;
  911. MTparams[tnb].hashID = hashID;
  912. MTparams[tnb].display = 0;
  913. MTparams[tnb].resultPtr = MTresults+tnb;
  914. MTparams[tnb].prngSeed = prngSeed;
  915. MTparams[tnb].maskSelector = (uint64_t)tnb;
  916. POOL_add(pt, MT_searchCollisions, MTparams + tnb);
  917. }
  918. POOL_free(pt); /* actually joins and free */
  919. /* Gather results */
  920. uint64_t nbCollisions=0;
  921. for (int tnb=0; tnb<nbThreads; tnb++) {
  922. nbCollisions += MTresults[tnb].nbCollisions;
  923. }
  924. double const programTDelay = difftime(time(NULL), programTBegin);
  925. size_t const programBytesSelf = getProcessMemUsage(0);
  926. size_t const programBytesChildren = getProcessMemUsage(1);
  927. printf("\n\n");
  928. printf("===> Found %llu collisions (x%.2f, %.1f expected) in %s\n",
  929. (unsigned long long)nbCollisions,
  930. (double)nbCollisions / targetColls,
  931. targetColls,
  932. displayDelay(programTDelay));
  933. if (programBytesSelf)
  934. printf("===> MaxRSS(self) %zuMB, MaxRSS(children) %zuMB\n",
  935. programBytesSelf>>20,
  936. programBytesChildren>>20);
  937. printf("------------------------------------------ \n");
  938. /* Clean up */
  939. free(MTparams);
  940. free(MTresults);
  941. }
  942. return 0;
  943. }