Index: llvm/include/llvm/Bitstream/BitstreamReader.h =================================================================== --- llvm/include/llvm/Bitstream/BitstreamReader.h +++ llvm/include/llvm/Bitstream/BitstreamReader.h @@ -229,21 +229,33 @@ return R; } - Expected ReadVBR(unsigned NumBits) { + Expected ReadVBR(const unsigned NumBits) { Expected MaybeRead = Read(NumBits); if (!MaybeRead) return MaybeRead; uint32_t Piece = MaybeRead.get(); - if ((Piece & (1U << (NumBits-1))) == 0) + if (NumBits >= 33 || NumBits == 0) + return make_error("Invalid NumBits value", + llvm::inconvertibleErrorCode()); + 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; + if (Mask > 1) { + if (MaskBitOrder - 1 + NextBit >= 32) { + return make_error("Invalid NumBits or NextBit value", + llvm::inconvertibleErrorCode()); + } + } + Result |= (Piece & (Mask - 1)) << NextBit; - if ((Piece & (1U << (NumBits-1))) == 0) + if ((Piece & Mask) == 0) return Result; NextBit += NumBits-1; Index: llvm/test/Bitcode/invalid-no-ubsan.test =================================================================== --- llvm/test/Bitcode/invalid-no-ubsan.test +++ llvm/test/Bitcode/invalid-no-ubsan.test @@ -6,14 +6,12 @@ # TODO: This code should be fixed to not exhibit UB, and these tests should be # incorporated back into invalid.test and run under UBSan again. -UNSUPPORTED: ubsan - RUN: not llvm-dis -disable-output %p/Inputs/size-not-plausible.bc 2>&1 | \ RUN: FileCheck --check-prefix=SIZE-NOT-PLAUSIBLE %s -SIZE-NOT-PLAUSIBLE: Size is not plausible +SIZE-NOT-PLAUSIBLE: Invalid NumBits or NextBit value RUN: not llvm-dis -disable-output %p/Inputs/invalid-value-symbol-table-2.bc 2>&1 | \ RUN: FileCheck --check-prefix=INVALID-VALUE-SYMBOL-TABLE-2 %s -INVALID-VALUE-SYMBOL-TABLE-2: Expected value symbol table subbloc +INVALID-VALUE-SYMBOL-TABLE-2: Invalid NumBits or NextBit value