Skip to content

Commit 6280c29

Browse files
committed
[Bitstream] Add assert to ReadVBR and ReadVBR64
We want to prevent UB potentially caused by left-shifting by type bit-width. Differential Revision: https://reviews.llvm.org/D119307
1 parent 132553b commit 6280c29

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

llvm/include/llvm/Bitstream/BitstreamReader.h

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -227,21 +227,25 @@ class SimpleBitstreamCursor {
227227
return R;
228228
}
229229

230-
Expected<uint32_t> ReadVBR(unsigned NumBits) {
230+
Expected<uint32_t> ReadVBR(const unsigned NumBits) {
231231
Expected<unsigned> MaybeRead = Read(NumBits);
232232
if (!MaybeRead)
233233
return MaybeRead;
234234
uint32_t Piece = MaybeRead.get();
235235

236-
if ((Piece & (1U << (NumBits-1))) == 0)
236+
assert(NumBits <= 32 && NumBits >= 1 && "Invalid NumBits value");
237+
const uint32_t MaskBitOrder = (NumBits - 1);
238+
const uint32_t Mask = 1UL << MaskBitOrder;
239+
240+
if ((Piece & Mask) == 0)
237241
return Piece;
238242

239243
uint32_t Result = 0;
240244
unsigned NextBit = 0;
241245
while (true) {
242-
Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
246+
Result |= (Piece & (Mask - 1)) << NextBit;
243247

244-
if ((Piece & (1U << (NumBits-1))) == 0)
248+
if ((Piece & Mask) == 0)
245249
return Result;
246250

247251
NextBit += NumBits-1;
@@ -258,21 +262,24 @@ class SimpleBitstreamCursor {
258262

259263
// Read a VBR that may have a value up to 64-bits in size. The chunk size of
260264
// the VBR must still be <= 32 bits though.
261-
Expected<uint64_t> ReadVBR64(unsigned NumBits) {
265+
Expected<uint64_t> ReadVBR64(const unsigned NumBits) {
262266
Expected<uint64_t> MaybeRead = Read(NumBits);
263267
if (!MaybeRead)
264268
return MaybeRead;
265269
uint32_t Piece = MaybeRead.get();
270+
assert(NumBits <= 32 && NumBits >= 1 && "Invalid NumBits value");
271+
const uint32_t MaskBitOrder = (NumBits - 1);
272+
const uint32_t Mask = 1UL << MaskBitOrder;
266273

267-
if ((Piece & (1U << (NumBits-1))) == 0)
274+
if ((Piece & Mask) == 0)
268275
return uint64_t(Piece);
269276

270277
uint64_t Result = 0;
271278
unsigned NextBit = 0;
272279
while (true) {
273-
Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
280+
Result |= uint64_t(Piece & (Mask - 1)) << NextBit;
274281

275-
if ((Piece & (1U << (NumBits-1))) == 0)
282+
if ((Piece & Mask) == 0)
276283
return Result;
277284

278285
NextBit += NumBits-1;

0 commit comments

Comments
 (0)