mirror of
https://github.com/qpdf/qpdf.git
synced 2024-12-22 19:08:59 +00:00
d71f05ca07
This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.
76 lines
1.5 KiB
C++
76 lines
1.5 KiB
C++
#include <qpdf/BitStream.hh>
|
|
#include <qpdf/QIntC.hh>
|
|
|
|
// See comments in bits.cc
|
|
#define BITS_READ 1
|
|
#include "bits.icc"
|
|
|
|
BitStream::BitStream(unsigned char const* p, size_t nbytes) :
|
|
start(p),
|
|
nbytes(nbytes)
|
|
{
|
|
reset();
|
|
}
|
|
|
|
void
|
|
BitStream::reset()
|
|
{
|
|
p = start;
|
|
bit_offset = 7;
|
|
if (QIntC::to_uint(nbytes) > static_cast<unsigned int>(-1) / 8)
|
|
{
|
|
throw std::runtime_error("array too large for bitstream");
|
|
}
|
|
bits_available = 8 * nbytes;
|
|
}
|
|
|
|
unsigned long long
|
|
BitStream::getBits(size_t nbits)
|
|
{
|
|
return read_bits(this->p, this->bit_offset,
|
|
this->bits_available, nbits);
|
|
}
|
|
|
|
long long
|
|
BitStream::getBitsSigned(size_t nbits)
|
|
{
|
|
unsigned long long bits = read_bits(this->p, this->bit_offset,
|
|
this->bits_available, nbits);
|
|
long long result = 0;
|
|
if (static_cast<long long>(bits) > 1LL << (nbits - 1))
|
|
{
|
|
result = static_cast<long long>(bits -(1ULL << nbits));
|
|
}
|
|
else
|
|
{
|
|
result = static_cast<long long>(bits);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
int
|
|
BitStream::getBitsInt(size_t nbits)
|
|
{
|
|
return static_cast<int>(
|
|
QIntC::to_uint(
|
|
read_bits(this->p, this->bit_offset,
|
|
this->bits_available, nbits)));
|
|
}
|
|
|
|
void
|
|
BitStream::skipToNextByte()
|
|
{
|
|
if (bit_offset != 7)
|
|
{
|
|
size_t bits_to_skip = bit_offset + 1;
|
|
if (bits_available < bits_to_skip)
|
|
{
|
|
throw std::logic_error(
|
|
"INTERNAL ERROR: overflow skipping to next byte in bitstream");
|
|
}
|
|
bit_offset = 7;
|
|
++p;
|
|
bits_available -= bits_to_skip;
|
|
}
|
|
}
|