Skip to content

Change reinterpret_cast use to memcpy #2295

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

Merged
merged 1 commit into from
Feb 13, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/coreclr/src/vm/diagnosticsprotocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ bool TryParse(uint8_t *&bufferCursor, uint32_t &bufferLen, T &result)

if (bufferLen < sizeof(T))
return false;
result = *(reinterpret_cast<T *>(bufferCursor));
memcpy(&result, bufferCursor, sizeof(T));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might consider something like:

template <typename T>
static inline T unaligned_reinterpret_cast(const void* ptr)
{
   T tmp; 
   memcpy(&tmp, ptr, sizeof(T));
   return tmp;
}

Then just use it like:

result = unaligned_reinterpret_cast<T>(bufferCursor);

At least, for fundamental types such as int and float, this generates pretty good code that does not involve copies.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I see how refactoring that code removes the need for a copy. memcpy happens either way. Are you suggesting replacing the entirety of TryParse with the above code?

Copy link
Contributor

@lpereira lpereira Jan 28, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I mean, it still calls memcpy() (which might not even copy, just load it in a register), but there's no additional copy because it's returning tmp instead of a reference or pointer.

This just wraps memcpy() in a function in such a way that it's clear from the call site that it's a reinterpret_cast that works with unaligned pointers. It's otherwise identical to the direct memcpy() call in your patch.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing with this single line change, it just worked in my case.

bufferCursor += sizeof(T);
bufferLen -= sizeof(T);
return true;
Expand Down