Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix misaligned pointer use in hash code #229

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jwwalker
Copy link
Contributor

The MurmurHash code was using misaligned pointers, which is undefined behavior according to the C++ standard and probably unsafe on multiple platforms. See Is it well-defined to hold a misaligned pointer, as long as you don't ever dereference it? on Stack Overflow.

@darksylinc
Copy link
Member

darksylinc commented Sep 29, 2021

My biggest concern is performance. MurmurHash was considered for its speed. This patch:

  • Replaces a raw cast with a copy (via memcpy) that may or may not be optimized (likely not, due to the visibility constraints)
  • Replaces uint32_t/uint64_t ptrs for uint8_t which has a different performance profile due to strict aliasing rules

Sounds like we should analyze the feasibility of feeding aligned-ptrs-only instead:

  1. malloc allocations are already guaranteed to be aligned (unless offseted of course)
  2. Stack allocations are aligned to whatever the data is. It's "usually aligned" to what we need, but it may need a stricter enforcement
  3. Data coming from structures should have the proper OGRE_ALIGNED_DECL
  4. Using OGRE_ASSERT_HIGH( isAligned( key ) ); is completely acceptable
  5. Using compiler extensions to diagnose alignment is also fine

I tried using OGRE_ASSERT_HIGH( isAligned( key ) ); with:

inline bool isAligned( const uint8_t *x )
{
return (reinterpret_cast<size_t>(x) & 0xFu) == 0u;
}

and it did not trigger; but a simple "works on my machine" (Linux x64) isn't a scientific measurement.

If it's unfeasible to feed aligned ptrs, then we have no other choice but to bite the bullet.

Alternative:

Brainstorming here:

Having 2 versions of the routine and dispatch based on ptr alignment may be an interesting approach; ideally only used on platforms where unaligned reads are actually unsupported (though that's UB)

@jwwalker
Copy link
Contributor Author

To give a specific example, I'm getting odd addresses passed to the hash function by IdString( const std::string &string ).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants