Skip to content

Commit

Permalink
Fix undefined behavior (#147)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
ekilmer committed Mar 12, 2021
1 parent 6af9a82 commit d9e72af
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions pe-parser-library/src/buffer.cpp
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
}
Expand Down

0 comments on commit d9e72af

Please sign in to comment.