[PATCH] D119307: [Bitstream] Fix UB in left-shift in ReadVBR
Jan Korous via Phabricator via llvm-commits
llvm-commits at lists.llvm.org
Tue Feb 15 17:12:57 PST 2022
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6280c29a8701: [Bitstream] Add assert to ReadVBR and ReadVBR64 (authored by jkorous).
Changed prior to commit:
https://reviews.llvm.org/D119307?vs=408681&id=409102#toc
Repository:
rG LLVM Github Monorepo
CHANGES SINCE LAST ACTION
https://reviews.llvm.org/D119307/new/
https://reviews.llvm.org/D119307
Files:
llvm/include/llvm/Bitstream/BitstreamReader.h
Index: llvm/include/llvm/Bitstream/BitstreamReader.h
===================================================================
--- llvm/include/llvm/Bitstream/BitstreamReader.h
+++ llvm/include/llvm/Bitstream/BitstreamReader.h
@@ -227,21 +227,25 @@
return R;
}
- Expected<uint32_t> ReadVBR(unsigned NumBits) {
+ Expected<uint32_t> ReadVBR(const unsigned NumBits) {
Expected<unsigned> MaybeRead = Read(NumBits);
if (!MaybeRead)
return MaybeRead;
uint32_t Piece = MaybeRead.get();
- if ((Piece & (1U << (NumBits-1))) == 0)
+ assert(NumBits <= 32 && NumBits >= 1 && "Invalid NumBits value");
+ const uint32_t MaskBitOrder = (NumBits - 1);
+ const uint32_t Mask = 1UL << MaskBitOrder;
+
+ if ((Piece & Mask) == 0)
return Piece;
uint32_t Result = 0;
unsigned NextBit = 0;
while (true) {
- Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
+ Result |= (Piece & (Mask - 1)) << NextBit;
- if ((Piece & (1U << (NumBits-1))) == 0)
+ if ((Piece & Mask) == 0)
return Result;
NextBit += NumBits-1;
@@ -258,21 +262,24 @@
// Read a VBR that may have a value up to 64-bits in size. The chunk size of
// the VBR must still be <= 32 bits though.
- Expected<uint64_t> ReadVBR64(unsigned NumBits) {
+ Expected<uint64_t> ReadVBR64(const unsigned NumBits) {
Expected<uint64_t> MaybeRead = Read(NumBits);
if (!MaybeRead)
return MaybeRead;
uint32_t Piece = MaybeRead.get();
+ assert(NumBits <= 32 && NumBits >= 1 && "Invalid NumBits value");
+ const uint32_t MaskBitOrder = (NumBits - 1);
+ const uint32_t Mask = 1UL << MaskBitOrder;
- if ((Piece & (1U << (NumBits-1))) == 0)
+ if ((Piece & Mask) == 0)
return uint64_t(Piece);
uint64_t Result = 0;
unsigned NextBit = 0;
while (true) {
- Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
+ Result |= uint64_t(Piece & (Mask - 1)) << NextBit;
- if ((Piece & (1U << (NumBits-1))) == 0)
+ if ((Piece & Mask) == 0)
return Result;
NextBit += NumBits-1;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D119307.409102.patch
Type: text/x-patch
Size: 2114 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220216/be2f677f/attachment.bin>
More information about the llvm-commits
mailing list