From: Xinliang David Li Date: Tue, 17 Nov 2015 03:47:21 +0000 (+0000) Subject: Fix unaligned memory read issue exposed by ubsan X-Git-Url: http://plrg.eecs.uci.edu/git/?p=oota-llvm.git;a=commitdiff_plain;h=4d60f67763b08c19335b29e96a61ad4cbce034d9;hp=15d19608b087c452ba9d28bafa268426e7f6fab9 Fix unaligned memory read issue exposed by ubsan Indexed profile data as designed today does not guarantee counter data to be well aligned, so reading needs to use the slower form (with memcpy). This is less than ideal and should be improved in the future (i.e., with fixed length function key instead of variable length name key). git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@253309 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/ProfileData/InstrProf.cpp b/lib/ProfileData/InstrProf.cpp index 762f00b48b6..ef7b19b2882 100644 --- a/lib/ProfileData/InstrProf.cpp +++ b/lib/ProfileData/InstrProf.cpp @@ -184,11 +184,13 @@ void ValueProfRecord::serializeFrom(const InstrProfRecord &Record, } } -template static T swapToHostOrder(T v, support::endianness Orig) { - if (Orig == getHostEndianness()) - return v; - sys::swapByteOrder(v); - return v; +template +static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) { + using namespace support; + if (Orig == little) + return endian::readNext(D); + else + return endian::readNext(D); } // For writing/serializing, Old is the host endianness, and New is @@ -278,10 +280,9 @@ ValueProfData::getValueProfData(const unsigned char *D, if (D + sizeof(ValueProfData) > BufferEnd) return instrprof_error::truncated; - uint32_t TotalSize = swapToHostOrder( - reinterpret_cast(D)[0], Endianness); - uint32_t NumValueKinds = swapToHostOrder( - reinterpret_cast(D)[1], Endianness); + const unsigned char *Header = D; + uint32_t TotalSize = swapToHostOrder(Header, Endianness); + uint32_t NumValueKinds = swapToHostOrder(Header, Endianness); if (D + TotalSize > BufferEnd) return instrprof_error::too_large; @@ -307,7 +308,6 @@ ValueProfData::getValueProfData(const unsigned char *D, return instrprof_error::malformed; } - D += TotalSize; return std::move(VPD); }