Skip to content

Commit e03b077

Browse files
authored
fix: Make ZstdHelper compatible with UBSan (#9152)
In ZstdHelper::isCompressed call, `src` may not be aligned to 4 bytes, which is violating the alignment requirement of `UndefinedBehaviorSanitizer: misaligned-pointer-use`, thereby resuling in a runtime failure with UBSan enabled. So reconstruct the 32-bit integer as a workaround.
1 parent f5418cb commit e03b077

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

filament/src/ZstdHelper.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,19 @@ bool ZstdHelper::isCompressed(const void* src, size_t src_size) noexcept {
2727
if (src_size < 4) {
2828
return false;
2929
}
30-
const uint32_t magic = *static_cast<const uint32_t*>(src);
30+
31+
// `src` may not be aligned to 4 bytes, which is violating the alignment requirement of
32+
// `UndefinedBehaviorSanitizer: misaligned-pointer-use`. So reconstruct the 32-bit integer from
33+
// bytes in little-endian order as the expected byte sequence is 28 B5 2F FD and
34+
// ZSTD_MAGICNUMBER refers to 0xFD2FB528. This should work correctly on both little-endian and
35+
// big-endian systems.
36+
const auto* p = static_cast<const uint8_t*>(src);
37+
const uint32_t magic =
38+
(uint32_t)p[0] |
39+
(uint32_t)(p[1] << 8) |
40+
(uint32_t)(p[2] << 16) |
41+
(uint32_t)(p[3] << 24);
42+
3143
return magic == ZSTD_MAGICNUMBER;
3244
}
3345

0 commit comments

Comments
 (0)