4
0
mirror of https://github.com/QuasarApp/pe-parse.git synced 2025-05-11 10:49:33 +00:00

Fix undefined behavior ()

* Fix undefined behavior unaligned accesses in buffer reads

Uses memcpy instead of reinterpret_cast to fix undefined behavior

See https://blog.quarkslab.com/unaligned-accesses-in-cc-what-why-and-solutions-to-do-it-properly.html

* Replace reinterpret_cast with memcpy in readChar16
This commit is contained in:
Eric Kilmer 2021-03-12 15:51:53 -05:00 committed by GitHub
parent 6af9a82335
commit d9e72af81e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -112,11 +112,12 @@ bool readWord(bounded_buffer *b, std::uint32_t offset, std::uint16_t &out) {
return false;
}
std::uint16_t *tmp = reinterpret_cast<std::uint16_t *>(b->buf + offset);
std::uint16_t tmp;
memcpy(&tmp, (b->buf + offset), sizeof(std::uint16_t));
if (b->swapBytes) {
out = byteSwapUint16(*tmp);
out = byteSwapUint16(tmp);
} else {
out = *tmp;
out = tmp;
}
return true;
@ -133,11 +134,12 @@ bool readDword(bounded_buffer *b, std::uint32_t offset, std::uint32_t &out) {
return false;
}
std::uint32_t *tmp = reinterpret_cast<std::uint32_t *>(b->buf + offset);
std::uint32_t tmp;
memcpy(&tmp, (b->buf + offset), sizeof(std::uint32_t));
if (b->swapBytes) {
out = byteSwapUint32(*tmp);
out = byteSwapUint32(tmp);
} else {
out = *tmp;
out = tmp;
}
return true;
@ -154,11 +156,12 @@ bool readQword(bounded_buffer *b, std::uint32_t offset, std::uint64_t &out) {
return false;
}
std::uint64_t *tmp = reinterpret_cast<std::uint64_t *>(b->buf + offset);
std::uint64_t tmp;
memcpy(&tmp, (b->buf + offset), sizeof(std::uint64_t));
if (b->swapBytes) {
out = byteSwapUint64(*tmp);
out = byteSwapUint64(tmp);
} else {
out = *tmp;
out = tmp;
}
return true;
@ -175,16 +178,16 @@ bool readChar16(bounded_buffer *b, std::uint32_t offset, char16_t &out) {
return false;
}
char16_t *tmp = nullptr;
char16_t tmp;
if (b->swapBytes) {
std::uint8_t tmpBuf[2];
tmpBuf[0] = *(b->buf + offset + 1);
tmpBuf[1] = *(b->buf + offset);
tmp = reinterpret_cast<char16_t *>(tmpBuf);
memcpy(&tmp, tmpBuf, sizeof(std::uint16_t));
} else {
tmp = reinterpret_cast<char16_t *>(b->buf + offset);
memcpy(&tmp, (b->buf + offset), sizeof(std::uint16_t));
}
out = *tmp;
out = tmp;
return true;
}