From 132fc181cd3e6ee6c06172308a5ae3b0e58b3848 Mon Sep 17 00:00:00 2001 From: WerWolv Date: Sun, 12 Sep 2021 14:28:13 +0200 Subject: [PATCH] patterns: Fix bitfields with unaligned sizes Correction for #292 --- .../libimhex/include/hex/helpers/utils.hpp | 18 +++++++++++++ .../hex/pattern_language/pattern_data.hpp | 27 +------------------ 2 files changed, 19 insertions(+), 26 deletions(-) diff --git a/plugins/libimhex/include/hex/helpers/utils.hpp b/plugins/libimhex/include/hex/helpers/utils.hpp index aa8383055..ba2ca8974 100644 --- a/plugins/libimhex/include/hex/helpers/utils.hpp +++ b/plugins/libimhex/include/hex/helpers/utils.hpp @@ -38,6 +38,24 @@ namespace hex { return (value & mask) >> to; } + [[nodiscard]] inline u64 extract(u32 from, u32 to, const std::vector &bytes) { + u8 index = 0; + while(from > 32 && to > 32) { + if (from - 8 < 0 || to - 8 < 0) + return 0; + + from -= 8; + to -= 8; + index++; + } + + u64 value = 0; + std::memcpy(&value, &bytes[index], std::min(sizeof(value), bytes.size() - index)); + u64 mask = (std::numeric_limits::max() >> (64 - (from + 1))); + + return (value & mask) >> to; + } + template struct overloaded : Ts... { using Ts::operator()...; }; template overloaded(Ts...) -> overloaded; diff --git a/plugins/libimhex/include/hex/pattern_language/pattern_data.hpp b/plugins/libimhex/include/hex/pattern_language/pattern_data.hpp index f21629f0d..d1102b750 100644 --- a/plugins/libimhex/include/hex/pattern_language/pattern_data.hpp +++ b/plugins/libimhex/include/hex/pattern_language/pattern_data.hpp @@ -1244,14 +1244,6 @@ namespace hex::pl { return new PatternDataBitfieldField(*this); } - template - T extractValue(const std::vector &value) { - T fieldValue = 0; - std::memcpy(&fieldValue, value.data(), value.size()); - - return hex::extract(this->m_bitOffset + (this->m_bitSize - 1), this->m_bitOffset, fieldValue); - } - void createEntry(prv::Provider* &provider) override { std::vector value(this->getParent()->getSize(), 0); provider->read(this->getParent()->getOffset(), &value[0], value.size()); @@ -1281,24 +1273,7 @@ namespace hex::pl { { u8 numBytes = (this->m_bitSize / 8) + 1; - u64 extractedValue; - switch (this->getSize()) { - case 1: - extractedValue = extractValue(value); - break; - case 2: - extractedValue = extractValue(value); - break; - case 4: - extractedValue = extractValue(value); - break; - case 8: - extractedValue = extractValue(value); - break; - default: - extractedValue = 0; - } - + u64 extractedValue = hex::extract(this->m_bitOffset + (this->m_bitSize - 1), this->m_bitOffset, value); ImGui::Text("%llu (0x%llX)", extractedValue, extractedValue); }