Debian Codegraph @

third-party/xxhash/tests/collisions/main.c

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