186 points · by pcwalton · 9y ago · 114 comments
I wonder how the Rust version compares with plain-jane C.
-Austin (murmurhash guy).
For example, if IV1 and IV2 match and the block pattern is ABCDABCDABCD, then BACDBACDBACD will produce the same hash value.
A minor finalizer change would fix it for any IV (pseudocode as I don't actually know Rust) -
vec[0] ^= diffuse(vec[1]); vec[1] ^= diffuse(vec[0]); vec[2] ^= diffuse(vec[3]); vec[3] ^= diffuse(vec[2]);
u64 result = diffuse(vec[1] ^ diffuse(vec[3]));
that's probably overkill but should work.
The operating mode of this hash is broken by default. The author calls it Merkle-Damgard, but that is not what it is. Merkle-Damgard uses a compression function, whereas what we have here is more like a sponge with full state absorption (you can pretend F(IV ^ m) is a compression function, but it is trivially susceptible to collisions F(IV ^ m) = F(m ^ IV)). Meaning, without a secret IV and some sort of truncation there's no way this mode can be secure, even with an ideal diffuse() function.
> Warning! This is not a cryptographic function, and it certainly should not be used as one.
So the focus here is speed, not resistance to malicious actors attempting to generate collisions.
That said, I haven't really looked into the theory much.
[0] https://docs.rs/crate/seahash/2.0.0/source/src/buffer.rs
It might be nice to factor this out into a separate library, but it's fairly harmless.
I think this code could potentially be refactored with smaller unsafe blocks, if that were a goal.
The benefit in general is present for many reasons, among which is that you still have to opt-in to unsafe{} and SeaHash consumers wouldn't need to in order to leverage these features.
The benefit for SeaHash specifically is that Rust isn't merely a safer language, it's also one with arguably newer/better language features than C++. And it's one that has support for several targets today.
I'm no expert on the topic. IIRC, Rust does not have the same kind/amount of unspecified behavior as C/C++ do.
FYI: This is a "highly optimized version of SeaHash" (see comment in first line) with "optimized" meaning fiddling with raw pointers. You can find a version without any unsafe code is in `reference.rs`. I have no idea how fast the reference implementation is.
Another advantage over C++ is that it's much more clear what code is safe and what isn't, as unsafe code is wrapped in `unsafe` blocks, as you mentioned.
let mut ptr = buf.as_ptr();
let end_ptr = buf.as_ptr().offset(buf.len() as isize & !0x1F) as usize;
while end_ptr > ptr as usize {
a = a ^ read_u64(ptr);
ptr = ptr.offset(8);
b = b ^ read_u64(ptr);
ptr = ptr.offset(8);
c = c ^ read_u64(ptr);
ptr = ptr.offset(8);
d = d ^ read_u64(ptr);
ptr = ptr.offset(8);
....
match excessive {
0 => {},
1...7 => {
a = a ^ read_int(slice::from_raw_parts(ptr as *const u8, excessive));
a = diffuse(a);
},
8 => {
a = a ^ read_u64(ptr);
a = diffuse(a);
},
9...15 => {
a = a ^ read_u64(ptr);
ptr = ptr.offset(8);
excessive = excessive - 8;
....
This bothers me about Rust. There's too much "unsafe" code in libraries. The language is unable to express some essential concepts. Known areas of trouble include partial initialization of an array, needed to implement growable collections, and single ownership doubly linked lists. Neither of those is expressible within Rust, which leads to unsafe code to implement them. Here, though, it's purely a performance issue. That's disturbing. If you can't do fast big-banging in safe Rust, there's a problem somewhere.If Rust let you access a slice of bytes as an slice of ints, alignment and length permitting, the code above could be much more straightforward. That's what I mean about expressive power. The hack to do that used here:
let end_ptr = buf.as_ptr().offset(buf.len() as isize & !0x1F) as usize;
is iffy. Why is there an "isize" (a signed quantity) in there? They want to align with a 32-bit cache line, yes, but why the signed quantity? The documentation for Rust's "std::ops::BitAnd" doesn't say what the semantics are for signed numbers. What would happen on a 32-bit machine if someone allocated a buffer bigger than 2GB? Exploitable?We used to implement things like vectors directly in the compiler, but it was a big headache for no gain. Writing actual code is way easier than writing code to generate LLVM IR.
Anyway, there is a commonly-used crate for this: byteorder. Had I written the library, I would have just used that crate. But it's not a big deal either way.
> Why is there an "isize" (a signed quantity) in there?
Because pointer arithmetic is signed.
> The documentation for Rust's "std::ops::BitAnd" doesn't say what the semantics are for signed numbers
Bitwise operations on signed integers are applied to their twos complement representations.
> What would happen on a 32-bit machine if someone allocated a buffer bigger than 2GB?
It would work.
> Exploitable?
No.
This bothers me about Rust.
There's too much "unsafe" code in libraries.
I like how with Rust you use one or two unsafe blocks and everyone loses their mind. But in C/C++ you spatter your code with undefined behavior and nobody bats an eye. I get Rust is _safe_ so violating this contract is in a way self defeating. But even with a handful of unsafe blocks you are miles ahead of other guarantees C/C++ give you. Lastly unlike C/C++ Rust makes you call out I'm doing dangerous stuff here! The language is unable to express some essential concepts.
Not really. The same code the parent poster highlighted [1] is undefined behavior in C/C++ (with standard types). So really no language has the ability to express those concepts. Your doing pointer casts and possibly unaligned dereferences at the same time. This has zero consistency between CPU vendors.[1] https://docs.rs/crate/seahash/2.0.0/source/src/buffer.rs
Known areas of trouble include partial initialization of an array, needed to implement growable collections
You mean Vector? C Doesn't have grow-able array's. They have re-alloc but Rust's Vector does that.https://doc.rust-lang.org/std/vec/struct.Vec.html
and single ownership doubly linked lists.
They already did, and it is in the standard library.https://doc.rust-lang.org/std/collections/struct.LinkedList....
If Rust let you access a slice of bytes as an slice of ints, alignment and length permitting,
the code above could be much more straightforward.
I mean C/C++ do, but without stdint.h you do this at your own peril. Even then you'll likely use Unions which are undefined behavior. What would happen on a 32-bit machine if someone allocated a buffer bigger than 2GB? Exploitable?
You can state this about C/C++ also. > The same code the parent poster highlighted [1] is
> undefined behavior in C/C++ (with standard types). So
> really no language has the ability to express those
> concepts. Your doing pointer casts and possibly unaligned
> dereferences at the same time. This has zero consistency
> between CPU vendors.
It's undefined behavior in Rust, too. Rust code that type-puns an unaligned pointer into an integer would crash on MIPS or SPARC just like the C code would. And that crash could potentially be triggered by malicious input. "unsafe" doesn't make behavior well-defined in Rust anymore than an explicit cast makes it well-defined in C.Moreover, type-punning is generally a warning of bad code in C. Both C and Rust will generally[1] diagnose a type-pun. And you can silence the diagnostic in both languages by using special syntax--unsafe in Rust, a cast in C. But in both cases the way that you silence the warning is over-broad; you often need to silence it for good reason, X, while accidentally silencing the diagnostic for usage Y.
The correct way to read in a little-endian integer in C is the same way you'd do it anywhere else:
unsigned char *p;
size_t plen;
uint64_t n;
// initialize p and plen
_Static_assert(CHAR_BIT == 8, "CHAR_BIT != 8"); // [2]
n = 0;
for (size_t i = 0; i < MIN(plen, sizeof n); i++) {
n |= p[i] << (8 * i);
}
It's correct regardless of endianness and regardless of whether the address is aligned. And the above loop can be unrolled, too, so that it pipelines well. If performance is so important that you can't be bothered to care about alignment constraints, you may as well drop down into assembly and use SIMD instructions directly. Type-punning with a C-style cast or Rust-style unsafe block is just a bad idea, IMO.I've never seen a situation in C where type-punning of this sort was a good idea. The performance aspect is negligible. My parsers generally runs rings around code that uses type-punning. The gains are nothing compared to what you can get by better restructuring of higher-level code. For example, with hashing functions you're generally hashing small strings; thus the alignment checks you would need to add would typically cost more than the benefit because they couldn't be amortized well.
If you really had to, then C11 provides _Alignof that can be used to type-pun in a safe manner just like you could in Rust. (If a builtin type has padding issues, so would the same Rust code. It just so happens that Rust affirmatively has selected at the outset to never support such architectures. Thus, running the same code on the same architecture would work correctly in both languages.) It's not even type-punning if in addition to correct alignment you can prove that all bits are value bits. That would be the case for both the fixed-sized integer types, as well as for unsigned types where you can prove there are no padding bits (which can be accomplished using well-defined code as well).
So for general usage, if you really want to you could implement two versions of the code--one that type-punned correctly for long strings, and a simpler, more concise, more obviously correct one for typical strings. So it can be done correctly while still reaping the same performance; it's just more hassle than writing incorrect code. But even the incorrect code is more obtuse than the trivially correct version, which is why I've never had a good reason to type-pun.
[1] The exception in C is implicit conversions through a void pointer. But in C++, which lacks implicit void pointer conversions, engineers will often instinctively add an explicit cast where you would normally use a void pointer in C, substantially blunting the benefit of removing the implicit conversion from the language. And that habit to cast can easily lead to more bugs, just like in this case, where unsafe was used to permit the use of a broken idiom that is poor code even in C.
Good C rarely uses casts. Avoiding casts is a good habit to get into in C. And I've personally never seen good reason to type-pun anything, period, in C.
[2] The code could be trivially made correct on platforms where CHAR_BIT > 8 if the convention was that input strings only filled the bottom 8 bits of char. It would just be a distraction here, though.
Which libraries? I see very few that do this, and all of them are safe abstractions containing some unsafe code.
You keep repeating this claim but I haven't seen any evidence to back it up.
> If Rust let you access a slice of bytes as an slice of ints, alignment and length permitting, the code above could be much more straightforward. That's what I mean about expressive power. The hack to do that used here:
The byteorder crate lets you do this. Of course, it uses unsafe code, but that's safely encapsulated away (and easy to verify). This crate doesn't use it, but it could. Not every operation needs to be baked into the language semantics.
The Rust core team is relatively relaxed about the community's usage of `unsafe`. I say this because they do not seem to be interested in actively discouraging it's usage. i.e. `unsafe` is discouraged in documentation, not via tools.
"Hey please don't use `unsafe` unless you know what you're doing". Is like writing a comment in Javascript, `function(x /* int */) {`.
Ideally, the usage of `unsafe` should be discouraged by the compiler via friction. The compiler should, at the least, spit out some metrics after a compile cycle about the percentage of `unsafe` lines/instructions. Even more ideal, when the compiler detects an `unsafe` it would pause and ask, "Is Crate Z trusted [y/N]?". Cargo can then make this easy in Cargo.toml.
All of a sudden Crate writers need to think twice about their usage of `unsafe`, will users be willing to trust my code? is using `unsafe` here really worth the risk of adopting fewer users? is there already a library that solves this which is generally trusted?
The pseudocode for FNV looks like this:
hash = FNV_offset_value
for each byte_of_data to be hashed
{
hash = hash XOR byte_of_data
hash = hash × FNV_prime
}
return hash
The pseudocode for seahash looks like this (with '×' as the wrapping multplier operator, and some simplification for padding if the data length in bytes is not a multiple of 8 bytes per word × 4 words in the hash state): hash = {offset_1, offset_2, offset_3, offset_4}
for (int data_index = 0;
data_index < data.length_in_64_bit_words;
data_index = data_index + 4_words_in_hash)
{
for (int hash_index = 0; hash_index < 4; hash_index++)
{
// Mix in data
hash[hash_index] = hash[hash_index] XOR data[data_index + hash_index]
// Diffuse
hash[hash_index] = hash[hash_index] XOR (hash[hash_index] RSHIFT 32)
hash[hash_index] = hash[hash_index] × seahash_prime
hash[hash_index] = hash[hash_index] XOR (hash[hash_index] RSHIFT 32)
hash[hash_index] = hash[hash_index] × seahash_prime
hash[hash_index] = hash[hash_index] XOR (hash[hash_index] RSHIFT 32)
}
}
result = hash[0] XOR hash[1] XOR hash[2] XOR hash[3] XOR data.length_in_bytes
result = result XOR (result RSHIFT 32)
result = result × seahash_prime
result = result XOR (result RSHIFT 32)
result = result × seahash_prime
result = result XOR (result RSHIFT 32)
return result
FNV is operating on bytes of data, while seahash is operating on 64-bit words. A modern processor will be able to handle 64 bits at once. True, it can probably handle 8 bits independently in one instruction without having to create a temporary value, but it still needs to do more operations.FNV is completely sequential. Until the first byte is hashed, no work can be done on the second byte. In seahash, as you observed, parallelism can be exploited. The second, third, and fourth bytes are all completely independent of the first byte, as bytes 6, 7, and 8 are independent of byte 5, and so on. You can have four independent threads each do a quarter of the work, and then put the result back together at the end.
I might have to bookmark this as a project to take on. A heavily parallel hashing algorithm that takes advantage of OpenCL would immensely increase the efficiency wouldn't it?
(I'm dipping my toes in parallel processing as of late and am genuinely curious in this topic and question)
> SeaHash achieves the performance by heavily exploiting Instruction-Level Parallelism.
> This means that almost always the CPU will be able to run the instructions in parallel.
The first line, "x ← x ≫ 32", might have a typo? It's actually assigning (x XOR (x >> 32)).
With "x ← px", p is a fixed prime number being multiplied by x.
I predict Rust will also begin to find use as a backend server language, and begin to eat into Java, Go, Python, and Ruby mindshare. Though there's a learning curve with Rust, it doesn't take too long to become productive. I'm also excited to see how Rust makes inroads in game development.
I think we're all going to start seeing more Rust in our headlines. It's a great language, and the people I know that use it are in love with it (myself included).
BTW, the hyperlink for "reference" in the "Specification" section is broken.
But it only seeds one of the lanes, so you can still make collisions trivially in one of the other lanes. I guess it could still be useful for namespacing.
"Warning!
This is not a cryptographic function, and it certainly should not be used as one. If you want a good cryptograhic hash function, you should use SHA-3 (Keccak) or BLAKE2."