PMurHash.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*-----------------------------------------------------------------------------
  2. * MurmurHash3 was written by Austin Appleby, and is placed in the public
  3. * domain.
  4. *
  5. * This implementation was written by Shane Day, and is also public domain.
  6. *
  7. * This is a portable ANSI C implementation of MurmurHash3_x86_32 (Murmur3A)
  8. * with support for progressive processing.
  9. */
  10. /*-----------------------------------------------------------------------------
  11. If you want to understand the MurmurHash algorithm you would be much better
  12. off reading the original source. Just point your browser at:
  13. http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
  14. What this version provides?
  15. 1. Progressive data feeding. Useful when the entire payload to be hashed
  16. does not fit in memory or when the data is streamed through the application.
  17. Also useful when hashing a number of strings with a common prefix. A partial
  18. hash of a prefix string can be generated and reused for each suffix string.
  19. 2. Portability. Plain old C so that it should compile on any old compiler.
  20. Both CPU endian and access-alignment neutral, but avoiding inefficient code
  21. when possible depending on CPU capabilities.
  22. 3. Drop in. I personally like nice self contained public domain code, making it
  23. easy to pilfer without loads of refactoring to work properly in the existing
  24. application code & makefile structure and mucking around with licence files.
  25. Just copy PMurHash.h and PMurHash.c and you're ready to go.
  26. How does it work?
  27. We can only process entire 32 bit chunks of input, except for the very end
  28. that may be shorter. So along with the partial hash we need to give back to
  29. the caller a carry containing up to 3 bytes that we were unable to process.
  30. This carry also needs to record the number of bytes the carry holds. I use
  31. the low 2 bits as a count (0..3) and the carry bytes are shifted into the
  32. high byte in stream order.
  33. To handle endianess I simply use a macro that reads a uint32_t and define
  34. that macro to be a direct read on little endian machines, a read and swap
  35. on big endian machines, or a byte-by-byte read if the endianess is unknown.
  36. -----------------------------------------------------------------------------*/
  37. #include "PMurHash.h"
  38. /* I used ugly type names in the header to avoid potential conflicts with
  39. * application or system typedefs & defines. Since I'm not including any more
  40. * headers below here I can rename these so that the code reads like C99 */
  41. #undef uint32_t
  42. #define uint32_t MH_UINT32
  43. #undef uint8_t
  44. #define uint8_t MH_UINT8
  45. /* MSVC warnings we choose to ignore */
  46. #if defined(_MSC_VER)
  47. #pragma warning(disable: 4127) /* conditional expression is constant */
  48. #endif
  49. /*-----------------------------------------------------------------------------
  50. * Endianess, misalignment capabilities and util macros
  51. *
  52. * The following 3 macros are defined in this section. The other macros defined
  53. * are only needed to help derive these 3.
  54. *
  55. * READ_UINT32(x) Read a little endian unsigned 32-bit int
  56. * UNALIGNED_SAFE Defined if READ_UINT32 works on non-word boundaries
  57. * ROTL32(x,r) Rotate x left by r bits
  58. */
  59. /* Convention is to define __BYTE_ORDER == to one of these values */
  60. #if !defined(__BIG_ENDIAN)
  61. #define __BIG_ENDIAN 4321
  62. #endif
  63. #if !defined(__LITTLE_ENDIAN)
  64. #define __LITTLE_ENDIAN 1234
  65. #endif
  66. /* I386 */
  67. #if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(i386)
  68. #define __BYTE_ORDER __LITTLE_ENDIAN
  69. #define UNALIGNED_SAFE
  70. #endif
  71. /* gcc 'may' define __LITTLE_ENDIAN__ or __BIG_ENDIAN__ to 1 (Note the trailing __),
  72. * or even _LITTLE_ENDIAN or _BIG_ENDIAN (Note the single _ prefix) */
  73. #if !defined(__BYTE_ORDER)
  74. #if defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__==1 || defined(_LITTLE_ENDIAN) && _LITTLE_ENDIAN==1
  75. #define __BYTE_ORDER __LITTLE_ENDIAN
  76. #elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1 || defined(_BIG_ENDIAN) && _BIG_ENDIAN==1
  77. #define __BYTE_ORDER __BIG_ENDIAN
  78. #endif
  79. #endif
  80. /* gcc (usually) defines xEL/EB macros for ARM and MIPS endianess */
  81. #if !defined(__BYTE_ORDER)
  82. #if defined(__ARMEL__) || defined(__MIPSEL__)
  83. #define __BYTE_ORDER __LITTLE_ENDIAN
  84. #endif
  85. #if defined(__ARMEB__) || defined(__MIPSEB__)
  86. #define __BYTE_ORDER __BIG_ENDIAN
  87. #endif
  88. #endif
  89. /* Now find best way we can to READ_UINT32 */
  90. #if __BYTE_ORDER==__LITTLE_ENDIAN
  91. /* CPU endian matches murmurhash algorithm, so read 32-bit word directly */
  92. #define READ_UINT32(ptr) (*((uint32_t*)(ptr)))
  93. #elif __BYTE_ORDER==__BIG_ENDIAN
  94. /* TODO: Add additional cases below where a compiler provided bswap32 is available */
  95. #if defined(__GNUC__) && (__GNUC__>4 || (__GNUC__==4 && __GNUC_MINOR__>=3))
  96. #define READ_UINT32(ptr) (__builtin_bswap32(*((uint32_t*)(ptr))))
  97. #else
  98. /* Without a known fast bswap32 we're just as well off doing this */
  99. #define READ_UINT32(ptr) (ptr[0]|ptr[1]<<8|ptr[2]<<16|ptr[3]<<24)
  100. #define UNALIGNED_SAFE
  101. #endif
  102. #else
  103. /* Unknown endianess so last resort is to read individual bytes */
  104. #define READ_UINT32(ptr) (ptr[0]|ptr[1]<<8|ptr[2]<<16|ptr[3]<<24)
  105. /* Since we're not doing word-reads we can skip the messing about with realignment */
  106. #define UNALIGNED_SAFE
  107. #endif
  108. /* Find best way to ROTL32 */
  109. #if defined(_MSC_VER)
  110. #include <stdlib.h> /* Microsoft put _rotl declaration in here */
  111. #define ROTL32(x,r) _rotl(x,r)
  112. #else
  113. /* gcc recognises this code and generates a rotate instruction for CPUs with one */
  114. #define ROTL32(x,r) (((uint32_t)x << r) | ((uint32_t)x >> (32 - r)))
  115. #endif
  116. /*-----------------------------------------------------------------------------
  117. * Core murmurhash algorithm macros */
  118. #define C1 (0xcc9e2d51)
  119. #define C2 (0x1b873593)
  120. /* This is the main processing body of the algorithm. It operates
  121. * on each full 32-bits of input. */
  122. #define DOBLOCK(h1, k1) do{ \
  123. k1 *= C1; \
  124. k1 = ROTL32(k1,15); \
  125. k1 *= C2; \
  126. \
  127. h1 ^= k1; \
  128. h1 = ROTL32(h1,13); \
  129. h1 = h1*5+0xe6546b64; \
  130. }while(0)
  131. /* Append unaligned bytes to carry, forcing hash churn if we have 4 bytes */
  132. /* cnt=bytes to process, h1=name of h1 var, c=carry, n=bytes in c, ptr/len=payload */
  133. #define DOBYTES(cnt, h1, c, n, ptr, len) do{ \
  134. int _i = cnt; \
  135. while(_i--) { \
  136. c = c>>8 | *ptr++<<24; \
  137. n++; len--; \
  138. if(n==4) { \
  139. DOBLOCK(h1, c); \
  140. n = 0; \
  141. } \
  142. } }while(0)
  143. /*---------------------------------------------------------------------------*/
  144. /* Main hashing function. Initialise carry to 0 and h1 to 0 or an initial seed
  145. * if wanted. Both ph1 and pcarry are required arguments. */
  146. void PMurHash32_Process(uint32_t *ph1, uint32_t *pcarry, const void *key, int len)
  147. {
  148. uint32_t h1 = *ph1;
  149. uint32_t c = *pcarry;
  150. const uint8_t *ptr = (uint8_t*)key;
  151. const uint8_t *end;
  152. /* Extract carry count from low 2 bits of c value */
  153. int n = c & 3;
  154. #if defined(UNALIGNED_SAFE)
  155. /* This CPU handles unaligned word access */
  156. /* Consume any carry bytes */
  157. int i = (4-n) & 3;
  158. if(i && i <= len) {
  159. DOBYTES(i, h1, c, n, ptr, len);
  160. }
  161. /* Process 32-bit chunks */
  162. end = ptr + len/4*4;
  163. for( ; ptr < end ; ptr+=4) {
  164. uint32_t k1 = READ_UINT32(ptr);
  165. DOBLOCK(h1, k1);
  166. }
  167. #else /*UNALIGNED_SAFE*/
  168. /* This CPU does not handle unaligned word access */
  169. /* Consume enough so that the next data byte is word aligned */
  170. int i = -(long)ptr & 3;
  171. if(i && i <= len) {
  172. DOBYTES(i, h1, c, n, ptr, len);
  173. }
  174. /* We're now aligned. Process in aligned blocks. Specialise for each possible carry count */
  175. end = ptr + len/4*4;
  176. switch(n) { /* how many bytes in c */
  177. case 0: /* c=[----] w=[3210] b=[3210]=w c'=[----] */
  178. for( ; ptr < end ; ptr+=4) {
  179. uint32_t k1 = READ_UINT32(ptr);
  180. DOBLOCK(h1, k1);
  181. }
  182. break;
  183. case 1: /* c=[0---] w=[4321] b=[3210]=c>>24|w<<8 c'=[4---] */
  184. for( ; ptr < end ; ptr+=4) {
  185. uint32_t k1 = c>>24;
  186. c = READ_UINT32(ptr);
  187. k1 |= c<<8;
  188. DOBLOCK(h1, k1);
  189. }
  190. break;
  191. case 2: /* c=[10--] w=[5432] b=[3210]=c>>16|w<<16 c'=[54--] */
  192. for( ; ptr < end ; ptr+=4) {
  193. uint32_t k1 = c>>16;
  194. c = READ_UINT32(ptr);
  195. k1 |= c<<16;
  196. DOBLOCK(h1, k1);
  197. }
  198. break;
  199. case 3: /* c=[210-] w=[6543] b=[3210]=c>>8|w<<24 c'=[654-] */
  200. for( ; ptr < end ; ptr+=4) {
  201. uint32_t k1 = c>>8;
  202. c = READ_UINT32(ptr);
  203. k1 |= c<<24;
  204. DOBLOCK(h1, k1);
  205. }
  206. }
  207. #endif /*UNALIGNED_SAFE*/
  208. /* Advance over whole 32-bit chunks, possibly leaving 1..3 bytes */
  209. len -= len/4*4;
  210. /* Append any remaining bytes into carry */
  211. DOBYTES(len, h1, c, n, ptr, len);
  212. /* Copy out new running hash and carry */
  213. *ph1 = h1;
  214. *pcarry = (c & ~0xff) | n;
  215. }
  216. /*---------------------------------------------------------------------------*/
  217. /* Finalize a hash. To match the original Murmur3A the total_length must be provided */
  218. uint32_t PMurHash32_Result(uint32_t h, uint32_t carry, uint32_t total_length)
  219. {
  220. uint32_t k1;
  221. int n = carry & 3;
  222. if(n) {
  223. k1 = carry >> (4-n)*8;
  224. k1 *= C1; k1 = ROTL32(k1,15); k1 *= C2; h ^= k1;
  225. }
  226. h ^= total_length;
  227. /* fmix */
  228. h ^= h >> 16;
  229. h *= 0x85ebca6b;
  230. h ^= h >> 13;
  231. h *= 0xc2b2ae35;
  232. h ^= h >> 16;
  233. return h;
  234. }
  235. /*---------------------------------------------------------------------------*/
  236. /* Murmur3A compatable all-at-once */
  237. uint32_t PMurHash32(uint32_t seed, const void *key, int len)
  238. {
  239. uint32_t h1=seed, carry=0;
  240. PMurHash32_Process(&h1, &carry, key, len);
  241. return PMurHash32_Result(h1, carry, len);
  242. }
  243. /*---------------------------------------------------------------------------*/
  244. /* Provide an API suitable for smhasher */
  245. void PMurHash32_test(const void *key, int len, uint32_t seed, void *out)
  246. {
  247. uint32_t h1=seed, carry=0;
  248. const uint8_t *ptr = (uint8_t*)key;
  249. const uint8_t *end = ptr + len;
  250. #if 0 /* Exercise the progressive processing */
  251. while(ptr < end) {
  252. //const uint8_t *mid = ptr + rand()%(end-ptr)+1;
  253. const uint8_t *mid = ptr + (rand()&0xF);
  254. mid = mid<end?mid:end;
  255. PMurHash32_Process(&h1, &carry, ptr, mid-ptr);
  256. ptr = mid;
  257. }
  258. #else
  259. PMurHash32_Process(&h1, &carry, ptr, (int)(end-ptr));
  260. #endif
  261. h1 = PMurHash32_Result(h1, carry, len);
  262. *(uint32_t*)out = h1;
  263. }
  264. /*---------------------------------------------------------------------------*/
  265. #ifdef TEST
  266. int main() {
  267. // http://www.cprover.org/cbmc/
  268. // cbmc PMurHash.c --function PMurHash32 --unwind 255 --bounds-check --pointer-check
  269. //=> seed=308736u (00000000000001001011011000000000)
  270. // key=INVALID-128 (1000000011111111111111111111111111111111111111111111110101100111)
  271. // len=640
  272. // Violated property:
  273. //file PMurHash.c line 201 function PMurHash32_Process
  274. //dereference failure: object bounds
  275. //!(POINTER_OFFSET(ptr) < 0) && OBJECT_SIZE(ptr) >= 1 + POINTER_OFFSET(ptr) || DYNAMIC_OBJECT(ptr)
  276. uint32_t seed = 308736;
  277. unsigned long long key = 0x80fffffffffffd67ULL;
  278. PMurHash32(seed, &key, sizeof(key));
  279. }
  280. #endif