24 changes: 17 additions & 7 deletions libqpdf/BitStream.cc
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#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, int nbytes) :
BitStream::BitStream(unsigned char const* p, size_t nbytes) :
start(p),
nbytes(nbytes)
{
Expand All @@ -16,29 +17,29 @@ BitStream::reset()
{
p = start;
bit_offset = 7;
if (static_cast<unsigned int>(nbytes) > static_cast<unsigned int>(-1) / 8)
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(int nbits)
BitStream::getBits(size_t nbits)
{
return read_bits(this->p, this->bit_offset,
this->bits_available, nbits);
}

long long
BitStream::getBitsSigned(int nbits)
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) > 1 << (nbits - 1))
if (static_cast<long long>(bits) > 1LL << (nbits - 1))
{
result = static_cast<long long>(bits - (1 << nbits));
result = static_cast<long long>(bits -(1ULL << nbits));
}
else
{
Expand All @@ -47,12 +48,21 @@ BitStream::getBitsSigned(int nbits)
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)
{
unsigned int bits_to_skip = bit_offset + 1;
size_t bits_to_skip = bit_offset + 1;
if (bits_available < bits_to_skip)
{
throw std::logic_error(
Expand Down
14 changes: 10 additions & 4 deletions libqpdf/BitWriter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ BitWriter::BitWriter(Pipeline* pl) :
}

void
BitWriter::writeBits(unsigned long long val, unsigned int bits)
BitWriter::writeBits(unsigned long long val, size_t bits)
{
write_bits(this->ch, this->bit_offset, val, bits, this->pl);
}

void
BitWriter::writeBitsSigned(long long val, unsigned int bits)
BitWriter::writeBitsSigned(long long val, size_t bits)
{
unsigned long long uval = 0;
if (val < 0)
{
uval = static_cast<unsigned long long>((1 << bits) + val);
uval = (1ULL << bits) + static_cast<unsigned long long>(val);
}
else
{
Expand All @@ -32,12 +32,18 @@ BitWriter::writeBitsSigned(long long val, unsigned int bits)
writeBits(uval, bits);
}

void
BitWriter::writeBitsInt(int val, size_t bits)
{
writeBits(static_cast<unsigned long long>(val), bits);
}

void
BitWriter::flush()
{
if (bit_offset < 7)
{
int bits_to_write = bit_offset + 1;
size_t bits_to_write = bit_offset + 1;
write_bits(this->ch, this->bit_offset, 0, bits_to_write, this->pl);
}
}
19 changes: 13 additions & 6 deletions libqpdf/BufferInputSource.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <qpdf/BufferInputSource.hh>
#include <qpdf/QIntC.hh>
#include <string.h>
#include <stdexcept>
#include <algorithm>
Expand Down Expand Up @@ -32,14 +33,20 @@ BufferInputSource::~BufferInputSource()
}
}

qpdf_offset_t const
BufferInputSource::bufSizeAsOffset() const
{
return QIntC::to_offset(this->buf->getSize());
}

qpdf_offset_t
BufferInputSource::findAndSkipNextEOL()
{
if (this->cur_offset < 0)
{
throw std::logic_error("INTERNAL ERROR: BufferInputSource offset < 0");
}
qpdf_offset_t end_pos = this->buf->getSize();
qpdf_offset_t end_pos = bufSizeAsOffset();
if (this->cur_offset >= end_pos)
{
this->last_offset = end_pos;
Expand All @@ -48,7 +55,7 @@ BufferInputSource::findAndSkipNextEOL()
}

qpdf_offset_t result = 0;
size_t len = end_pos - this->cur_offset;
size_t len = QIntC::to_size(end_pos - this->cur_offset);
unsigned char const* buffer = this->buf->getBuffer();

void* start = const_cast<unsigned char*>(buffer) + this->cur_offset;
Expand Down Expand Up @@ -97,7 +104,7 @@ BufferInputSource::seek(qpdf_offset_t offset, int whence)
break;

case SEEK_END:
this->cur_offset = this->buf->getSize() + offset;
this->cur_offset = bufSizeAsOffset() + offset;
break;

case SEEK_CUR:
Expand Down Expand Up @@ -130,7 +137,7 @@ BufferInputSource::read(char* buffer, size_t length)
{
throw std::logic_error("INTERNAL ERROR: BufferInputSource offset < 0");
}
qpdf_offset_t end_pos = this->buf->getSize();
qpdf_offset_t end_pos = bufSizeAsOffset();
if (this->cur_offset >= end_pos)
{
this->last_offset = end_pos;
Expand All @@ -139,9 +146,9 @@ BufferInputSource::read(char* buffer, size_t length)

this->last_offset = this->cur_offset;
size_t len = std::min(
static_cast<size_t>(end_pos - this->cur_offset), length);
QIntC::to_size(end_pos - this->cur_offset), length);
memcpy(buffer, buf->getBuffer() + this->cur_offset, len);
this->cur_offset += len;
this->cur_offset += QIntC::to_offset(len);
return len;
}

Expand Down
2 changes: 1 addition & 1 deletion libqpdf/FileInputSource.cc
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ FileInputSource::read(char* buffer, size_t length)
this->filename, "",
this->last_offset,
std::string("read ") +
QUtil::int_to_string(length) + " bytes");
QUtil::uint_to_string(length) + " bytes");
}
else if (length > 0)
{
Expand Down
11 changes: 7 additions & 4 deletions libqpdf/InputSource.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <stdexcept>
#include <qpdf/QTC.hh>
#include <qpdf/PointerHolder.hh>
#include <qpdf/QIntC.hh>


void
Expand Down Expand Up @@ -35,7 +36,7 @@ InputSource::readLine(size_t max_line_length)
this->seek(offset, SEEK_SET);
qpdf_offset_t eol = this->findAndSkipNextEOL();
this->last_offset = offset;
size_t line_length = eol - offset;
size_t line_length = QIntC::to_size(eol - offset);
if (line_length < max_line_length)
{
buf[line_length] = '\0';
Expand Down Expand Up @@ -116,7 +117,8 @@ InputSource::findFirst(char const* start_chars,

// Search for the first character.
if ((p = static_cast<char*>(
memchr(p, start_chars[0], bytes_read - (p - buf)))) != 0)
memchr(p, start_chars[0],
bytes_read - QIntC::to_size(p - buf)))) != 0)
{
if (p == buf)
{
Expand All @@ -126,7 +128,8 @@ InputSource::findFirst(char const* start_chars,
if (len != 0)
{
// Make sure it's in range.
size_t p_relative_offset = (p - buf) + (buf_offset - offset);
size_t p_relative_offset =
QIntC::to_size((p - buf) + (buf_offset - offset));
if (p_relative_offset >= len)
{
// out of range
Expand Down Expand Up @@ -198,7 +201,7 @@ InputSource::findLast(char const* start_chars,
}
after_found_offset = this->tell();
cur_offset = after_found_offset;
cur_len = len - (cur_offset - offset);
cur_len = len - QIntC::to_size((cur_offset - offset));
}
if (found)
{
Expand Down
3 changes: 2 additions & 1 deletion libqpdf/InsecureRandomDataProvider.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ InsecureRandomDataProvider::random()
// Seed the random number generator with something simple, but
// just to be interesting, don't use the unmodified current
// time. It would be better if this were a more secure seed.
QUtil::srandom(QUtil::get_current_time() ^ 0xcccc);
QUtil::srandom(static_cast<unsigned int>(
QUtil::get_current_time() ^ 0xcccc));
this->seeded_random = true;
}

Expand Down
2 changes: 1 addition & 1 deletion libqpdf/JSON.cc
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ JSON::encode_string(std::string const& str)
}
else
{
result.append(1, ch);
result.append(1, static_cast<char>(ch));
}
}
}
Expand Down
38 changes: 22 additions & 16 deletions libqpdf/MD5.cc
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

#include <qpdf/MD5.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>

#include <stdio.h>
#include <memory.h>
Expand Down Expand Up @@ -110,7 +111,7 @@ void MD5::init()
// context.

void MD5::update(unsigned char *input,
unsigned int inputLen)
size_t inputLen)
{
unsigned int i, index, partLen;

Expand Down Expand Up @@ -268,7 +269,7 @@ void MD5::transform(UINT4 state[4], unsigned char block[64])

// Encodes input (UINT4) into output (unsigned char). Assumes len is a
// multiple of 4.
void MD5::encode(unsigned char *output, UINT4 *input, unsigned int len)
void MD5::encode(unsigned char *output, UINT4 *input, size_t len)
{
unsigned int i, j;

Expand All @@ -282,7 +283,7 @@ void MD5::encode(unsigned char *output, UINT4 *input, unsigned int len)

// Decodes input (unsigned char) into output (UINT4). Assumes len is a
// multiple of 4.
void MD5::decode(UINT4 *output, unsigned char *input, unsigned int len)
void MD5::decode(UINT4 *output, unsigned char *input, size_t len)
{
unsigned int i, j;

Expand All @@ -308,7 +309,7 @@ void MD5::reset()

void MD5::encodeString(char const* str)
{
unsigned int len = strlen(str);
size_t len = strlen(str);

update(QUtil::unsigned_char_pointer(str), len);
final();
Expand All @@ -319,22 +320,27 @@ void MD5::appendString(char const* input_string)
update(QUtil::unsigned_char_pointer(input_string), strlen(input_string));
}

void MD5::encodeDataIncrementally(char const* data, int len)
void MD5::encodeDataIncrementally(char const* data, size_t len)
{
update(QUtil::unsigned_char_pointer(data), len);
}

void MD5::encodeFile(char const *filename, int up_to_size)
void MD5::encodeFile(char const *filename, qpdf_offset_t up_to_offset)
{
unsigned char buffer[1024];

FILE *file = QUtil::safe_fopen(filename, "rb");
size_t len;
int so_far = 0;
int to_try = 1024;
size_t so_far = 0;
size_t to_try = 1024;
size_t up_to_size = 0;
if (up_to_offset >= 0)
{
up_to_size = QIntC::to_size(up_to_offset);
}
do
{
if ((up_to_size >= 0) && ((so_far + to_try) > up_to_size))
if ((up_to_offset >= 0) && ((so_far + to_try) > up_to_size))
{
to_try = up_to_size - so_far;
}
Expand All @@ -343,7 +349,7 @@ void MD5::encodeFile(char const *filename, int up_to_size)
{
update(buffer, len);
so_far += len;
if ((up_to_size >= 0) && (so_far >= up_to_size))
if ((up_to_offset >= 0) && (so_far >= up_to_size))
{
break;
}
Expand Down Expand Up @@ -388,37 +394,37 @@ std::string MD5::unparse()
}

std::string
MD5::getDataChecksum(char const* buf, int len)
MD5::getDataChecksum(char const* buf, size_t len)
{
MD5 m;
m.encodeDataIncrementally(buf, len);
return m.unparse();
}

std::string
MD5::getFileChecksum(char const* filename, int up_to_size)
MD5::getFileChecksum(char const* filename, qpdf_offset_t up_to_offset)
{
MD5 m;
m.encodeFile(filename, up_to_size);
m.encodeFile(filename, up_to_offset);
return m.unparse();
}

bool
MD5::checkDataChecksum(char const* const checksum,
char const* buf, int len)
char const* buf, size_t len)
{
std::string actual_checksum = getDataChecksum(buf, len);
return (checksum == actual_checksum);
}

bool
MD5::checkFileChecksum(char const* const checksum,
char const* filename, int up_to_size)
char const* filename, qpdf_offset_t up_to_offset)
{
bool result = false;
try
{
std::string actual_checksum = getFileChecksum(filename, up_to_size);
std::string actual_checksum = getFileChecksum(filename, up_to_offset);
result = (checksum == actual_checksum);
}
catch (std::runtime_error const&)
Expand Down
13 changes: 7 additions & 6 deletions libqpdf/Pl_AES_PDF.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
#include <assert.h>
#include <stdexcept>
#include <qpdf/rijndael.h>
#include <qpdf/QIntC.hh>
#include <string>
#include <stdlib.h>

bool Pl_AES_PDF::use_static_iv = false;

Pl_AES_PDF::Pl_AES_PDF(char const* identifier, Pipeline* next,
bool encrypt, unsigned char const* key,
unsigned int key_bytes) :
size_t key_bytes) :
Pipeline(identifier, next),
encrypt(encrypt),
cbc_mode(true),
Expand All @@ -22,11 +23,11 @@ Pl_AES_PDF::Pl_AES_PDF(char const* identifier, Pipeline* next,
use_specified_iv(false),
disable_padding(false)
{
unsigned int keybits = 8 * key_bytes;
size_t keybits = 8 * key_bytes;
assert(key_bytes == KEYLENGTH(keybits));
this->key = new unsigned char[key_bytes];
this->rk = new uint32_t[RKLENGTH(keybits)];
unsigned int rk_bytes = RKLENGTH(keybits) * sizeof(uint32_t);
size_t rk_bytes = RKLENGTH(keybits) * sizeof(uint32_t);
std::memcpy(this->key, key, key_bytes);
std::memset(this->rk, 0, rk_bytes);
std::memset(this->inbuf, 0, this->buf_size);
Expand Down Expand Up @@ -68,7 +69,7 @@ Pl_AES_PDF::setIV(unsigned char const* iv, size_t bytes)
{
throw std::logic_error(
"Pl_AES_PDF: specified initialization vector"
" size in bytes must be " + QUtil::int_to_string(bytes));
" size in bytes must be " + QUtil::uint_to_string(bytes));
}
this->use_specified_iv = true;
memcpy(this->specified_iv, iv, bytes);
Expand Down Expand Up @@ -123,7 +124,7 @@ Pl_AES_PDF::finish()
// specification, including providing an entire block of padding
// if the input was a multiple of 16 bytes.
unsigned char pad =
static_cast<unsigned char>(this->buf_size - this->offset);
QIntC::to_uchar(this->buf_size - this->offset);
memset(this->inbuf + this->offset, pad, pad);
this->offset = this->buf_size;
flush(false);
Expand Down Expand Up @@ -166,7 +167,7 @@ Pl_AES_PDF::initializeVector()
{
for (unsigned int i = 0; i < this->buf_size; ++i)
{
this->cbc_block[i] = 14 * (1 + i);
this->cbc_block[i] = static_cast<unsigned char>(14U * (1U + i));
}
}
else
Expand Down
2 changes: 1 addition & 1 deletion libqpdf/Pl_ASCII85Decoder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Pl_ASCII85Decoder::flush()
for (int i = 0; i < 5; ++i)
{
lval *= 85;
lval += (this->inbuf[i] - 33);
lval += (this->inbuf[i] - 33U);
}

unsigned char outbuf[4];
Expand Down
2 changes: 1 addition & 1 deletion libqpdf/Pl_ASCIIHexDecoder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len)
}
for (size_t i = 0; i < len; ++i)
{
char ch = toupper(buf[i]);
char ch = static_cast<char>(toupper(buf[i]));
switch (ch)
{
case ' ':
Expand Down
3 changes: 2 additions & 1 deletion libqpdf/Pl_Count.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <qpdf/Pl_Count.hh>
#include <qpdf/QIntC.hh>

Pl_Count::Pl_Count(char const* identifier, Pipeline* next) :
Pipeline(identifier, next),
Expand All @@ -16,7 +17,7 @@ Pl_Count::write(unsigned char* buf, size_t len)
{
if (len)
{
this->count += len;
this->count += QIntC::to_offset(len);
getNext()->write(buf, len);
this->last_char = buf[len - 1];
}
Expand Down
16 changes: 10 additions & 6 deletions libqpdf/Pl_DCT.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <qpdf/QUtil.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QIntC.hh>

#include <setjmp.h>
#include <stdexcept>
Expand Down Expand Up @@ -213,7 +214,7 @@ skip_buffer_input_data(j_decompress_ptr cinfo, long num_bytes)
"reading jpeg: jpeg library requested"
" skipping a negative number of bytes");
}
size_t to_skip = static_cast<size_t>(num_bytes);
size_t to_skip = QIntC::to_size(num_bytes);
if ((to_skip > 0) && (to_skip <= cinfo->src->bytes_in_buffer))
{
cinfo->src->next_input_byte += to_skip;
Expand Down Expand Up @@ -283,15 +284,17 @@ Pl_DCT::compress(void* cinfo_p, Buffer* b)

jpeg_start_compress(cinfo, TRUE);

int width = cinfo->image_width * cinfo->input_components;
unsigned int width = cinfo->image_width *
QIntC::to_uint(cinfo->input_components);
size_t expected_size =
cinfo->image_height * cinfo->image_width * cinfo->input_components;
cinfo->image_height * cinfo->image_width *
QIntC::to_uint(cinfo->input_components);
if (b->getSize() != expected_size)
{
throw std::runtime_error(
"Pl_DCT: image buffer size = " +
QUtil::int_to_string(b->getSize()) + "; expected size = " +
QUtil::int_to_string(expected_size));
QUtil::uint_to_string(b->getSize()) + "; expected size = " +
QUtil::uint_to_string(expected_size));
}
JSAMPROW row_pointer[1];
unsigned char* buffer = b->getBuffer();
Expand Down Expand Up @@ -326,7 +329,8 @@ Pl_DCT::decompress(void* cinfo_p, Buffer* b)
(void) jpeg_read_header(cinfo, TRUE);
(void) jpeg_calc_output_dimensions(cinfo);

int width = cinfo->output_width * cinfo->output_components;
unsigned int width = cinfo->output_width *
QIntC::to_uint(cinfo->output_components);
JSAMPARRAY buffer = (*cinfo->mem->alloc_sarray)
(reinterpret_cast<j_common_ptr>(cinfo), JPOOL_IMAGE, width, 1);

Expand Down
33 changes: 17 additions & 16 deletions libqpdf/Pl_LZWDecoder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>
#include <stdexcept>
#include <string.h>
#include <assert.h>
Expand Down Expand Up @@ -52,22 +53,22 @@ Pl_LZWDecoder::finish()
void
Pl_LZWDecoder::sendNextCode()
{
int high = this->byte_pos;
int med = (this->byte_pos + 1) % 3;
int low = (this->byte_pos + 2) % 3;
unsigned int high = this->byte_pos;
unsigned int med = (this->byte_pos + 1) % 3;
unsigned int low = (this->byte_pos + 2) % 3;

int bits_from_high = 8 - this->bit_pos;
int bits_from_med = this->code_size - bits_from_high;
int bits_from_low = 0;
unsigned int bits_from_high = 8 - this->bit_pos;
unsigned int bits_from_med = this->code_size - bits_from_high;
unsigned int bits_from_low = 0;
if (bits_from_med > 8)
{
bits_from_low = bits_from_med - 8;
bits_from_med = 8;
}
int high_mask = (1 << bits_from_high) - 1;
int med_mask = 0xff - ((1 << (8 - bits_from_med)) - 1);
int low_mask = 0xff - ((1 << (8 - bits_from_low)) - 1);
int code = 0;
unsigned int high_mask = (1U << bits_from_high) - 1U;
unsigned int med_mask = 0xff - ((1U << (8 - bits_from_med)) - 1U);
unsigned int low_mask = 0xff - ((1U << (8 - bits_from_low)) - 1U);
unsigned int code = 0;
code += (this->buf[high] & high_mask) << bits_from_med;
code += ((this->buf[med] & med_mask) >> (8 - bits_from_med));
if (bits_from_low)
Expand All @@ -94,7 +95,7 @@ Pl_LZWDecoder::sendNextCode()
}

unsigned char
Pl_LZWDecoder::getFirstChar(int code)
Pl_LZWDecoder::getFirstChar(unsigned int code)
{
unsigned char result = '\0';
if (code < 256)
Expand Down Expand Up @@ -130,7 +131,7 @@ Pl_LZWDecoder::addToTable(unsigned char next)

if (this->last_code < 256)
{
tmp[0] = this->last_code;
tmp[0] = static_cast<unsigned char>(this->last_code);
last_data = tmp;
last_size = 1;
}
Expand All @@ -144,7 +145,7 @@ Pl_LZWDecoder::addToTable(unsigned char next)
}
Buffer& b = table.at(idx);
last_data = b.getBuffer();
last_size = b.getSize();
last_size = QIntC::to_uint(b.getSize());
}
else
{
Expand All @@ -161,7 +162,7 @@ Pl_LZWDecoder::addToTable(unsigned char next)
}

void
Pl_LZWDecoder::handleCode(int code)
Pl_LZWDecoder::handleCode(unsigned int code)
{
if (this->eod)
{
Expand Down Expand Up @@ -189,11 +190,11 @@ Pl_LZWDecoder::handleCode(int code)
// be what we read last plus the first character of what
// we're reading now.
unsigned char next = '\0';
unsigned int table_size = table.size();
unsigned int table_size = QIntC::to_uint(table.size());
if (code < 256)
{
// just read < 256; last time's next was code
next = code;
next = static_cast<unsigned char>(code);
}
else if (code > 257)
{
Expand Down
13 changes: 8 additions & 5 deletions libqpdf/Pl_PNGFilter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ Pl_PNGFilter::decodeSub()
left = buffer[i - bpp];
}

buffer[i] += left;
buffer[i] = static_cast<unsigned char>(buffer[i] + left);
}
}

Expand All @@ -167,7 +167,7 @@ Pl_PNGFilter::decodeUp()
for (unsigned int i = 0; i < this->bytes_per_row; ++i)
{
unsigned char up = above_buffer[i];
buffer[i] += up;
buffer[i] = static_cast<unsigned char>(buffer[i] + up);
}
}

Expand All @@ -190,7 +190,7 @@ Pl_PNGFilter::decodeAverage()
}

up = above_buffer[i];
buffer[i] += (left+up) / 2;
buffer[i] = static_cast<unsigned char>(buffer[i] + (left+up) / 2);
}
}

Expand All @@ -214,7 +214,9 @@ Pl_PNGFilter::decodePaeth()
upper_left = above_buffer[i - bpp];
}

buffer[i] += this->PaethPredictor(left, up, upper_left);
buffer[i] = static_cast<unsigned char>(
buffer[i] +
this->PaethPredictor(left, up, upper_left));
}
}

Expand Down Expand Up @@ -247,7 +249,8 @@ Pl_PNGFilter::encodeRow()
{
for (unsigned int i = 0; i < this->bytes_per_row; ++i)
{
ch = this->cur_row[i] - this->prev_row[i];
ch = static_cast<unsigned char>(
this->cur_row[i] - this->prev_row[i]);
getNext()->write(&ch, 1);
}
}
Expand Down
4 changes: 2 additions & 2 deletions libqpdf/Pl_RunLength.cc
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,13 @@ Pl_RunLength::decode(unsigned char* data, size_t len)
if (ch < 128)
{
// length represents remaining number of bytes to copy
this->length = 1 + ch;
this->length = 1U + ch;
this->state = st_copying;
}
else if (ch > 128)
{
// length represents number of copies of next byte
this->length = 257 - ch;
this->length = 257U - ch;
this->state = st_run;
}
else // ch == 128
Expand Down
73 changes: 37 additions & 36 deletions libqpdf/QPDF.cc
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ QPDF::reconstruct_xref(QPDFExc& e)
this->m->file->seek(line_start, SEEK_SET);
QPDFTokenizer::Token t1 = readToken(this->m->file, MAX_LEN);
qpdf_offset_t token_start =
this->m->file->tell() - t1.getValue().length();
this->m->file->tell() - toO(t1.getValue().length());
if (token_start >= next_line_start)
{
// don't process yet
Expand Down Expand Up @@ -610,7 +610,7 @@ QPDF::read_xref(qpdf_offset_t xref_offset)
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
"unable to find trailer while reading xref");
}
int size = this->m->trailer.getKey("/Size").getIntValue();
int size = this->m->trailer.getKey("/Size").getIntValueAsInt();
int max_obj = 0;
if (! this->m->xref_table.empty())
{
Expand Down Expand Up @@ -686,7 +686,7 @@ QPDF::parse_xrefFirst(std::string const& line,
{
++p;
}
bytes = p - start;
bytes = toI(p - start);
obj = QUtil::string_to_int(obj_str.c_str());
num = QUtil::string_to_int(num_str.c_str());
return true;
Expand Down Expand Up @@ -837,11 +837,11 @@ QPDF::read_xrefTable(qpdf_offset_t xref_offset)
{
// Save deleted items until after we've checked the
// XRefStm, if any.
deleted_items.push_back(QPDFObjGen(i, f2));
deleted_items.push_back(QPDFObjGen(toI(i), f2));
}
else
{
insertXrefEntry(i, 1, f1, f2);
insertXrefEntry(toI(i), 1, f1, f2);
}
}
qpdf_offset_t pos = this->m->file->tell();
Expand Down Expand Up @@ -1006,15 +1006,15 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
int max_bytes = sizeof(qpdf_offset_t);
for (int i = 0; i < 3; ++i)
{
W[i] = W_obj.getArrayItem(i).getIntValue();
W[i] = W_obj.getArrayItem(i).getIntValueAsInt();
if (W[i] > max_bytes)
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"xref stream", xref_offset,
"Cross-reference stream's /W contains"
" impossibly large values");
}
entry_size += W[i];
entry_size += toS(W[i]);
}
if (entry_size == 0)
{
Expand All @@ -1023,7 +1023,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
"Cross-reference stream's /W indicates"
" entry size of 0");
}
long long max_num_entries =
unsigned long long max_num_entries =
static_cast<unsigned long long>(-1) / entry_size;

std::vector<long long> indx;
Expand Down Expand Up @@ -1063,20 +1063,20 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
indx.push_back(size);
}

long long num_entries = 0;
for (unsigned int i = 1; i < indx.size(); i += 2)
size_t num_entries = 0;
for (size_t i = 1; i < indx.size(); i += 2)
{
if (indx.at(i) > max_num_entries - num_entries)
if (indx.at(i) > QIntC::to_longlong(max_num_entries - num_entries))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"xref stream", xref_offset,
"Cross-reference stream claims to contain"
" too many entries: " +
QUtil::int_to_string(indx.at(i)) + " " +
QUtil::int_to_string(max_num_entries) + " " +
QUtil::int_to_string(num_entries));
QUtil::uint_to_string(max_num_entries) + " " +
QUtil::uint_to_string(num_entries));
}
num_entries += indx.at(i);
num_entries += toS(indx.at(i));
}

// entry_size and num_entries have both been validated to ensure
Expand All @@ -1091,8 +1091,8 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
QPDFExc x(qpdf_e_damaged_pdf, this->m->file->getName(),
"xref stream", xref_offset,
"Cross-reference stream data has the wrong size;"
" expected = " + QUtil::int_to_string(expected_size) +
"; actual = " + QUtil::int_to_string(actual_size));
" expected = " + QUtil::uint_to_string(expected_size) +
"; actual = " + QUtil::uint_to_string(actual_size));
if (expected_size > actual_size)
{
throw x;
Expand All @@ -1103,7 +1103,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
}
}

int cur_chunk = 0;
size_t cur_chunk = 0;
int chunk_count = 0;

bool saw_first_compressed_object = false;
Expand All @@ -1112,7 +1112,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
// not overflow any buffers here. We know that entry_size *
// num_entries is equal to the size of the buffer.
unsigned char const* data = bp->getBuffer();
for (int i = 0; i < num_entries; ++i)
for (size_t i = 0; i < num_entries; ++i)
{
// Read this entry
unsigned char const* entry = data + (entry_size * i);
Expand All @@ -1129,15 +1129,15 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
for (int k = 0; k < W[j]; ++k)
{
fields[j] <<= 8;
fields[j] += static_cast<int>(*p++);
fields[j] += toI(*p++);
}
}

// Get the object and generation number. The object number is
// based on /Index. The generation number is 0 unless this is
// an uncompressed object record, in which case the generation
// number appears as the third field.
int obj = indx.at(cur_chunk) + chunk_count;
int obj = toI(indx.at(cur_chunk)) + chunk_count;
++chunk_count;
if (chunk_count >= indx.at(cur_chunk + 1))
{
Expand All @@ -1161,8 +1161,8 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj)
// This is needed by checkLinearization()
this->m->first_xref_item_offset = xref_offset;
}
insertXrefEntry(obj, static_cast<int>(fields[0]),
fields[1], static_cast<int>(fields[2]));
insertXrefEntry(obj, toI(fields[0]),
fields[1], toI(fields[2]));
}

if (! this->m->trailer.isInitialized())
Expand Down Expand Up @@ -1395,7 +1395,7 @@ QPDF::getObjectCount()
{
og = (*(this->m->obj_cache.rbegin())).first;
}
return og.getObj();
return toS(og.getObj());
}

std::vector<QPDFObjectHandle>
Expand Down Expand Up @@ -1570,8 +1570,8 @@ QPDF::readObject(PointerHolder<InputSource> input,
"an integer");
}

length = length_obj.getIntValue();
input->seek(stream_offset + length, SEEK_SET);
length = toS(length_obj.getUIntValue());
input->seek(stream_offset + toO(length), SEEK_SET);
if (! (readToken(input) ==
QPDFTokenizer::Token(
QPDFTokenizer::tt_word, "endstream")))
Expand Down Expand Up @@ -1641,7 +1641,7 @@ QPDF::recoverStreamLength(PointerHolder<InputSource> input,
size_t length = 0;
if (this->m->file->findFirst("end", stream_offset, 0, ef))
{
length = this->m->file->tell() - stream_offset;
length = toS(this->m->file->tell() - stream_offset);
// Reread endstream but, if it was endobj, don't skip that.
QPDFTokenizer::Token t = readToken(this->m->file);
if (t.getValue() == "endobj")
Expand All @@ -1652,7 +1652,7 @@ QPDF::recoverStreamLength(PointerHolder<InputSource> input,

if (length)
{
int this_obj_offset = 0;
qpdf_offset_t this_obj_offset = 0;
QPDFObjGen this_obj(0, 0);

// Make sure this is inside this object
Expand Down Expand Up @@ -1700,7 +1700,7 @@ QPDF::recoverStreamLength(PointerHolder<InputSource> input,
warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(),
this->m->last_object_description, stream_offset,
"recovered stream length: " +
QUtil::int_to_string(length)));
QUtil::uint_to_string(length)));
}

QTC::TC("qpdf", "QPDF recovered stream length");
Expand Down Expand Up @@ -2027,8 +2027,8 @@ QPDF::resolveObjectsInStream(int obj_stream_number)
" has incorrect keys");
}

int n = dict.getKey("/N").getIntValue();
int first = dict.getKey("/First").getIntValue();
int n = dict.getKey("/N").getIntValueAsInt();
int first = dict.getKey("/First").getIntValueAsInt();

std::map<int, int> offsets;

Expand All @@ -2052,7 +2052,7 @@ QPDF::resolveObjectsInStream(int obj_stream_number)
}

int num = QUtil::string_to_int(tnum.getValue().c_str());
int offset = QUtil::string_to_ll(toffset.getValue().c_str());
int offset = QUtil::string_to_int(toffset.getValue().c_str());
offsets[num] = offset + first;
}

Expand Down Expand Up @@ -2087,7 +2087,7 @@ QPDF::resolveObjectsInStream(int obj_stream_number)
QPDFObjectHandle
QPDF::makeIndirectObject(QPDFObjectHandle oh)
{
int max_objid = getObjectCount();
int max_objid = toI(getObjectCount());
QPDFObjGen next(max_objid + 1, 0);
this->m->obj_cache[next] =
ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1);
Expand Down Expand Up @@ -2509,7 +2509,7 @@ QPDF::getExtensionLevel()
obj = obj.getKey("/ExtensionLevel");
if (obj.isInteger())
{
result = obj.getIntValue();
result = obj.getIntValueAsInt();
}
}
}
Expand Down Expand Up @@ -2733,8 +2733,9 @@ QPDF::pipeStreamData(int objid, int generation,
bool suppress_warnings,
bool will_retry)
{
bool is_attachment_stream = this->m->attachment_streams.count(
QPDFObjGen(objid, generation));
bool is_attachment_stream = (
this->m->attachment_streams.count(
QPDFObjGen(objid, generation)) > 0);
return pipeStreamData(
this->m->encp, this->m->file, *this,
objid, generation, offset, length,
Expand All @@ -2746,7 +2747,7 @@ bool
QPDF::pipeForeignStreamData(
PointerHolder<ForeignStreamData> foreign,
Pipeline* pipeline,
unsigned long encode_flags,
int encode_flags,
qpdf_stream_decode_level_e decode_level)
{
if (foreign->encp->encrypted)
Expand Down
8 changes: 4 additions & 4 deletions libqpdf/QPDFAcroFormDocumentHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ QPDFAcroFormDocumentHelper::analyze()
// bidirectionally to fields.

std::set<QPDFObjGen> visited;
size_t nfields = fields.getArrayNItems();
int nfields = fields.getArrayNItems();
QPDFObjectHandle null(QPDFObjectHandle::newNull());
for (size_t i = 0; i < nfields; ++i)
for (int i = 0; i < nfields; ++i)
{
traverseField(fields.getArrayItem(i), null, 0, visited);
}
Expand Down Expand Up @@ -216,8 +216,8 @@ QPDFAcroFormDocumentHelper::traverseField(
if (kids.isArray())
{
is_field = true;
size_t nkids = kids.getArrayNItems();
for (size_t k = 0; k < nkids; ++k)
int nkids = kids.getArrayNItems();
for (int k = 0; k < nkids; ++k)
{
traverseField(kids.getArrayItem(k), field, 1 + depth, visited);
}
Expand Down
2 changes: 1 addition & 1 deletion libqpdf/QPDFAnnotationObjectHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ int
QPDFAnnotationObjectHelper::getFlags()
{
QPDFObjectHandle flags_obj = this->oh.getKey("/F");
return flags_obj.isInteger() ? flags_obj.getIntValue() : 0;
return flags_obj.isInteger() ? flags_obj.getIntValueAsInt() : 0;
}

QPDFObjectHandle
Expand Down
34 changes: 20 additions & 14 deletions libqpdf/QPDFFormFieldObjectHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <qpdf/QPDFAnnotationObjectHelper.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/Pl_QPDFTokenizer.hh>
#include <qpdf/QIntC.hh>
#include <stdlib.h>

QPDFFormFieldObjectHelper::Members::~Members()
Expand Down Expand Up @@ -189,7 +190,7 @@ QPDFFormFieldObjectHelper::getQuadding()
if (fv.isInteger())
{
QTC::TC("qpdf", "QPDFFormFieldObjectHelper Q present");
result = static_cast<int>(fv.getIntValue());
result = QIntC::to_int(fv.getIntValue());
}
return result;
}
Expand All @@ -198,7 +199,7 @@ int
QPDFFormFieldObjectHelper::getFlags()
{
QPDFObjectHandle f = getInheritableFieldValue("/Ff");
return f.isInteger() ? f.getIntValue() : 0;
return f.isInteger() ? f.getIntValueAsInt() : 0;
}

bool
Expand Down Expand Up @@ -245,8 +246,8 @@ QPDFFormFieldObjectHelper::getChoices()
QPDFObjectHandle opt = getInheritableFieldValue("/Opt");
if (opt.isArray())
{
size_t n = opt.getArrayNItems();
for (size_t i = 0; i < n; ++i)
int n = opt.getArrayNItems();
for (int i = 0; i < n; ++i)
{
QPDFObjectHandle item = opt.getArrayItem(i);
if (item.isString())
Expand Down Expand Up @@ -631,16 +632,16 @@ ValueSetter::writeAppearance()
{
// Try to make the found item the second one, but
// adjust for under/overflow.
int wanted_first = found_idx - 1;
int wanted_last = found_idx + max_rows - 2;
int wanted_first = QIntC::to_int(found_idx) - 1;
int wanted_last = QIntC::to_int(found_idx + max_rows) - 2;
QTC::TC("qpdf", "QPDFFormFieldObjectHelper list found");
while (wanted_first < 0)
{
QTC::TC("qpdf", "QPDFFormFieldObjectHelper list first too low");
++wanted_first;
++wanted_last;
}
while (wanted_last >= static_cast<int>(nopt))
while (wanted_last >= QIntC::to_int(nopt))
{
QTC::TC("qpdf", "QPDFFormFieldObjectHelper list last too high");
if (wanted_first > 0)
Expand All @@ -650,8 +651,9 @@ ValueSetter::writeAppearance()
--wanted_last;
}
highlight = true;
highlight_idx = found_idx - wanted_first;
for (int i = wanted_first; i <= wanted_last; ++i)
highlight_idx = found_idx - QIntC::to_size(wanted_first);
for (size_t i = QIntC::to_size(wanted_first);
i <= QIntC::to_size(wanted_last); ++i)
{
lines.push_back(opt.at(i));
}
Expand All @@ -672,13 +674,15 @@ ValueSetter::writeAppearance()

// Write the lines centered vertically, highlighting if needed
size_t nlines = lines.size();
double dy = bbox.ury - ((bbox.ury - bbox.lly - (nlines * tfh)) / 2.0);
double dy = bbox.ury - ((bbox.ury - bbox.lly -
(static_cast<double>(nlines) * tfh)) / 2.0);
if (highlight)
{
write("q\n0.85 0.85 0.85 rg\n" +
QUtil::double_to_string(bbox.llx) + " " +
QUtil::double_to_string(bbox.lly + dy -
(tfh * (highlight_idx + 1))) + " " +
QUtil::double_to_string(
bbox.lly + dy -
(tfh * (static_cast<double>(highlight_idx + 1)))) + " " +
QUtil::double_to_string(bbox.urx - bbox.llx) + " " +
QUtil::double_to_string(tfh) +
" re f\nQ\n");
Expand All @@ -693,8 +697,10 @@ ValueSetter::writeAppearance()
// which doesn't seem really worth the effort.
if (i == 0)
{
write(QUtil::double_to_string(bbox.llx + dx) + " " +
QUtil::double_to_string(bbox.lly + dy) + " Td\n");
write(QUtil::double_to_string(bbox.llx + static_cast<double>(dx)) +
" " +
QUtil::double_to_string(bbox.lly + static_cast<double>(dy)) +
" Td\n");
}
else
{
Expand Down
8 changes: 4 additions & 4 deletions libqpdf/QPDFNameTreeObjectHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ QPDFNameTreeObjectHelper::updateMap(QPDFObjectHandle oh)
QPDFObjectHandle names = oh.getKey("/Names");
if (names.isArray())
{
size_t nitems = names.getArrayNItems();
size_t i = 0;
int nitems = names.getArrayNItems();
int i = 0;
while (i < nitems - 1)
{
QPDFObjectHandle name = names.getArrayItem(i);
Expand All @@ -47,8 +47,8 @@ QPDFNameTreeObjectHelper::updateMap(QPDFObjectHandle oh)
QPDFObjectHandle kids = oh.getKey("/Kids");
if (kids.isArray())
{
size_t nitems = kids.getArrayNItems();
for (size_t i = 0; i < nitems; ++i)
int nitems = kids.getArrayNItems();
for (int i = 0; i < nitems; ++i)
{
updateMap(kids.getArrayItem(i));
}
Expand Down
8 changes: 4 additions & 4 deletions libqpdf/QPDFNumberTreeObjectHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ QPDFNumberTreeObjectHelper::updateMap(QPDFObjectHandle oh)
QPDFObjectHandle nums = oh.getKey("/Nums");
if (nums.isArray())
{
size_t nitems = nums.getArrayNItems();
size_t i = 0;
int nitems = nums.getArrayNItems();
int i = 0;
while (i < nitems - 1)
{
QPDFObjectHandle num = nums.getArrayItem(i);
Expand All @@ -43,8 +43,8 @@ QPDFNumberTreeObjectHelper::updateMap(QPDFObjectHandle oh)
QPDFObjectHandle kids = oh.getKey("/Kids");
if (kids.isArray())
{
size_t nitems = kids.getArrayNItems();
for (size_t i = 0; i < nitems; ++i)
int nitems = kids.getArrayNItems();
for (int i = 0; i < nitems; ++i)
{
updateMap(kids.getArrayItem(i));
}
Expand Down
17 changes: 9 additions & 8 deletions libqpdf/QPDFObjectHandle.cc
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>

#include <stdexcept>
#include <stdlib.h>
Expand Down Expand Up @@ -643,7 +644,7 @@ QPDFObjectHandle::isRectangle()
{
return false;
}
for (size_t i = 0; i < 4; ++i)
for (int i = 0; i < 4; ++i)
{
if (! getArrayItem(i).isNumber())
{
Expand All @@ -664,7 +665,7 @@ QPDFObjectHandle::isMatrix()
{
return false;
}
for (size_t i = 0; i < 6; ++i)
for (int i = 0; i < 6; ++i)
{
if (! getArrayItem(i).isNumber())
{
Expand Down Expand Up @@ -1013,7 +1014,7 @@ QPDFObjectHandle::getUniqueResourceName(std::string const& prefix,
int& min_suffix)
{
std::set<std::string> names = getResourceNames();
int max_suffix = min_suffix + names.size();
int max_suffix = min_suffix + QIntC::to_int(names.size());
while (min_suffix <= max_suffix)
{
std::string candidate = prefix + QUtil::int_to_string(min_suffix);
Expand Down Expand Up @@ -1374,7 +1375,7 @@ QPDFObjectHandle::rotatePage(int angle, bool relative)
if (cur_obj.getKey("/Rotate").isInteger())
{
found_rotate = true;
old_angle = cur_obj.getKey("/Rotate").getIntValue();
old_angle = cur_obj.getKey("/Rotate").getIntValueAsInt();
}
else if (cur_obj.getKey("/Parent").isDictionary())
{
Expand Down Expand Up @@ -1506,7 +1507,7 @@ QPDFObjectHandle::parse(std::string const& object_str,
bool empty = false;
QPDFObjectHandle result =
parse(input, object_description, tokenizer, empty, 0, 0);
size_t offset = input->tell();
size_t offset = QIntC::to_size(input->tell());
while (offset < object_str.length())
{
if (! isspace(object_str.at(offset)))
Expand Down Expand Up @@ -1618,7 +1619,7 @@ QPDFObjectHandle::parseContentStream_data(
QPDFTokenizer tokenizer;
tokenizer.allowEOF();
bool empty = false;
while (static_cast<size_t>(input->tell()) < length)
while (QIntC::to_size(input->tell()) < length)
{
QPDFObjectHandle obj =
parseInternal(input, "content", tokenizer, empty, 0, 0, true);
Expand Down Expand Up @@ -1863,8 +1864,8 @@ QPDFObjectHandle::parseInternal(PointerHolder<InputSource> input,
// Try to resolve indirect objects
object = newIndirect(
context,
olist.at(olist.size() - 2).getIntValue(),
olist.at(olist.size() - 1).getIntValue());
olist.at(olist.size() - 2).getIntValueAsInt(),
olist.at(olist.size() - 1).getIntValueAsInt());
olist.pop_back();
olist.pop_back();
}
Expand Down
2 changes: 1 addition & 1 deletion libqpdf/QPDFOutlineObjectHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ QPDFOutlineObjectHelper::getCount()
int count = 0;
if (this->oh.hasKey("/Count"))
{
count = this->oh.getKey("/Count").getIntValue();
count = this->oh.getKey("/Count").getIntValueAsInt();
}
return count;
}
Expand Down
2 changes: 1 addition & 1 deletion libqpdf/QPDFPageDocumentHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ QPDFPageDocumentHelper::flattenAnnotationsForPage(
page.getObjectHandle().getKey("/Rotate");
if (rotate_obj.isInteger() && rotate_obj.getIntValue())
{
rotate = rotate_obj.getIntValue();
rotate = rotate_obj.getIntValueAsInt();
}
int next_fx = 1;
for (std::vector<QPDFAnnotationObjectHelper>::iterator iter =
Expand Down
11 changes: 7 additions & 4 deletions libqpdf/QPDFPageObjectHelper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <qpdf/QUtil.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDFMatrix.hh>
#include <qpdf/QIntC.hh>

class ContentProvider: public QPDFObjectHandle::StreamDataProvider
{
Expand Down Expand Up @@ -236,7 +237,9 @@ InlineImageTracker::handleToken(QPDFTokenizer::Token const& token)
b.finish();
QPDFObjectHandle dict =
convertIIDict(QPDFObjectHandle::parse(dict_str));
dict.replaceKey("/Length", QPDFObjectHandle::newInteger(len));
dict.replaceKey(
"/Length",
QPDFObjectHandle::newInteger(QIntC::to_longlong(len)));
std::string name = resources.getUniqueResourceName(
"/IIm", this->min_suffix);
QPDFObjectHandle image = QPDFObjectHandle::newStream(
Expand Down Expand Up @@ -391,8 +394,8 @@ QPDFPageObjectHelper::getAnnotations(std::string const& only_subtype)
QPDFObjectHandle annots = this->oh.getKey("/Annots");
if (annots.isArray())
{
size_t nannots = annots.getArrayNItems();
for (size_t i = 0; i < nannots; ++i)
int nannots = annots.getArrayNItems();
for (int i = 0; i < nannots; ++i)
{
QPDFObjectHandle annot = annots.getArrayItem(i);
if (only_subtype.empty() ||
Expand Down Expand Up @@ -579,7 +582,7 @@ QPDFPageObjectHelper::getMatrixForTransformations(bool invert)
? scale_obj.getNumericValue()
: 1.0);
int rotate = (rotate_obj.isInteger()
? rotate_obj.getIntValue()
? rotate_obj.getIntValueAsInt()
: 0);
if (invert)
{
Expand Down
3 changes: 2 additions & 1 deletion libqpdf/QPDFTokenizer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <qpdf/QPDFExc.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QIntC.hh>

#include <stdexcept>
#include <stdlib.h>
Expand Down Expand Up @@ -715,7 +716,7 @@ QPDFTokenizer::findEI(PointerHolder<InputSource> input)
{
break;
}
this->m->inline_image_bytes = input->tell() - pos - 2;
this->m->inline_image_bytes = QIntC::to_size(input->tell() - pos - 2);

QPDFTokenizer check;
bool found_bad = false;
Expand Down
93 changes: 48 additions & 45 deletions libqpdf/QPDFWriter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDF_Name.hh>
#include <qpdf/QPDF_String.hh>
#include <qpdf/QIntC.hh>

#include <algorithm>
#include <stdlib.h>
Expand Down Expand Up @@ -722,11 +723,11 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf)
this->m->id1 =
trailer.getKey("/ID").getArrayItem(0).getStringValue();
QPDFObjectHandle encrypt = trailer.getKey("/Encrypt");
int V = encrypt.getKey("/V").getIntValue();
int V = encrypt.getKey("/V").getIntValueAsInt();
int key_len = 5;
if (V > 1)
{
key_len = encrypt.getKey("/Length").getIntValue() / 8;
key_len = encrypt.getKey("/Length").getIntValueAsInt() / 8;
}
if (encrypt.hasKey("/EncryptMetadata") &&
encrypt.getKey("/EncryptMetadata").isBool())
Expand Down Expand Up @@ -763,9 +764,9 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf)

setEncryptionParametersInternal(
V,
encrypt.getKey("/R").getIntValue(),
encrypt.getKey("/R").getIntValueAsInt(),
key_len,
encrypt.getKey("/P").getIntValue(),
encrypt.getKey("/P").getIntValueAsInt(),
encrypt.getKey("/O").getStringValue(),
encrypt.getKey("/U").getStringValue(),
OE,
Expand Down Expand Up @@ -884,7 +885,7 @@ QPDFWriter::compareVersions(int major1, int minor1,

void
QPDFWriter::setEncryptionParametersInternal(
int V, int R, int key_len, long P,
int V, int R, int key_len, int P,
std::string const& O, std::string const& U,
std::string const& OE, std::string const& UE, std::string const& Perms,
std::string const& id1, std::string const& user_password,
Expand Down Expand Up @@ -972,10 +973,10 @@ QPDFWriter::setDataKey(int objid)
this->m->encrypt_use_aes, this->m->encryption_V, this->m->encryption_R);
}

int
QPDFWriter::bytesNeeded(unsigned long long n)
unsigned int
QPDFWriter::bytesNeeded(long long n)
{
int bytes = 0;
unsigned int bytes = 0;
while (n)
{
++bytes;
Expand Down Expand Up @@ -1121,7 +1122,7 @@ QPDFWriter::pushEncryptionFilter()
{
p = new Pl_RC4("rc4 stream encryption", this->m->pipeline,
QUtil::unsigned_char_pointer(this->m->cur_data_key),
this->m->cur_data_key.length());
QIntC::to_int(this->m->cur_data_key.length()));
}
pushPipeline(p);
}
Expand Down Expand Up @@ -1356,7 +1357,8 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream,
writeString(" /Prev ");
qpdf_offset_t pos = this->m->pipeline->getCount();
writeString(QUtil::int_to_string(prev));
int nspaces = pos - this->m->pipeline->getCount() + 21;
int nspaces =
QIntC::to_int(pos - this->m->pipeline->getCount() + 21);
if (nspaces < 0)
{
throw std::logic_error(
Expand Down Expand Up @@ -1430,19 +1432,18 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream,
}

void
QPDFWriter::unparseObject(QPDFObjectHandle object, int level,
unsigned int flags)
QPDFWriter::unparseObject(QPDFObjectHandle object, int level, int flags)
{
unparseObject(object, level, flags, 0, false);
}

void
QPDFWriter::unparseObject(QPDFObjectHandle object, int level,
unsigned int flags, size_t stream_length,
int flags, size_t stream_length,
bool compress)
{
QPDFObjGen old_og = object.getObjGen();
unsigned int child_flags = flags & ~f_stream;
int child_flags = flags & ~f_stream;

std::string indent;
for (int i = 0; i < level; ++i)
Expand Down Expand Up @@ -1687,7 +1688,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level,

if (this->m->direct_stream_lengths)
{
writeString(QUtil::int_to_string(stream_length));
writeString(QUtil::uint_to_string(stream_length));
}
else
{
Expand Down Expand Up @@ -1818,7 +1819,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level,
writeString("\nstream\n");
pushEncryptionFilter();
writeBuffer(stream_data);
char last_char = this->m->pipeline->getLastChar();
unsigned char last_char = this->m->pipeline->getLastChar();
popPipelineStack();

if (this->m->newline_before_endstream ||
Expand Down Expand Up @@ -1861,7 +1862,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level,
char* tmp = QUtil::copy_string(val);
size_t vlen = val.length();
RC4 rc4(QUtil::unsigned_char_pointer(this->m->cur_data_key),
this->m->cur_data_key.length());
QIntC::to_int(this->m->cur_data_key.length()));
rc4.process(QUtil::unsigned_char_pointer(tmp), vlen);
val = QPDF_String(std::string(tmp, vlen)).unparse();
delete [] tmp;
Expand All @@ -1883,14 +1884,14 @@ void
QPDFWriter::writeObjectStreamOffsets(std::vector<qpdf_offset_t>& offsets,
int first_obj)
{
for (unsigned int i = 0; i < offsets.size(); ++i)
for (size_t i = 0; i < offsets.size(); ++i)
{
if (i != 0)
{
writeStringQDF("\n");
writeStringNoQDF(" ");
}
writeString(QUtil::int_to_string(i + first_obj));
writeString(QUtil::uint_to_string(i + QIntC::to_size(first_obj)));
writeString(" ");
writeString(QUtil::int_to_string(offsets.at(i)));
}
Expand Down Expand Up @@ -2015,13 +2016,13 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object)
writeStringQDF("\n ");
size_t length = stream_buffer->getSize();
adjustAESStreamLength(length);
writeString(" /Length " + QUtil::int_to_string(length));
writeString(" /Length " + QUtil::uint_to_string(length));
writeStringQDF("\n ");
if (compressed)
{
writeString(" /Filter /FlateDecode");
}
writeString(" /N " + QUtil::int_to_string(offsets.size()));
writeString(" /N " + QUtil::uint_to_string(offsets.size()));
writeStringQDF("\n ");
writeString(" /First " + QUtil::int_to_string(first));
if (! object.isNull())
Expand Down Expand Up @@ -2120,7 +2121,7 @@ QPDFWriter::writeObject(QPDFObjectHandle object, int object_stream_index)
}
}
openObject(new_id + 1);
writeString(QUtil::int_to_string(this->m->cur_stream_length));
writeString(QUtil::uint_to_string(this->m->cur_stream_length));
closeObject(new_id + 1);
}
}
Expand Down Expand Up @@ -2308,12 +2309,12 @@ QPDFWriter::generateObjectStreams()

std::vector<QPDFObjGen> const& eligible =
QPDF::Writer::getCompressibleObjGens(this->m->pdf);
unsigned int n_object_streams = (eligible.size() + 99) / 100;
size_t n_object_streams = (eligible.size() + 99U) / 100U;
if (n_object_streams == 0)
{
return;
}
unsigned int n_per = eligible.size() / n_object_streams;
size_t n_per = eligible.size() / n_object_streams;
if (n_per * n_object_streams < eligible.size())
{
++n_per;
Expand Down Expand Up @@ -2640,7 +2641,7 @@ QPDFWriter::doWriteSetup()
this->m->object_stream_to_objects[stream].insert(obj);
this->m->max_ostream_index =
std::max(this->m->max_ostream_index,
static_cast<int>(
QIntC::to_int(
this->m->object_stream_to_objects[stream].size()) - 1);
}

Expand Down Expand Up @@ -2672,7 +2673,7 @@ QPDFWriter::write()
// files, we write two passes. events_expected is an
// approximation, but it's good enough for progress reporting,
// which is mostly a guess anyway.
this->m->events_expected = (
this->m->events_expected = QIntC::to_int(
this->m->pdf.getObjectCount() * (this->m->linearized ? 3 : 2));

prepareFileForWrite();
Expand Down Expand Up @@ -2785,7 +2786,7 @@ QPDFWriter::writeHintStream(int hint_id)
}
writeString(" /Length ");
adjustAESStreamLength(hlen);
writeString(QUtil::int_to_string(hlen));
writeString(QUtil::uint_to_string(hlen));
writeString(" >>\nstream\n");

if (this->m->encrypted)
Expand All @@ -2794,7 +2795,7 @@ QPDFWriter::writeHintStream(int hint_id)
}
pushEncryptionFilter();
writeBuffer(hint_buffer);
char last_char = this->m->pipeline->getLastChar();
unsigned char last_char = this->m->pipeline->getLastChar();
popPipelineStack();

if (last_char != '\n')
Expand Down Expand Up @@ -2872,11 +2873,11 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset,
qpdf_offset_t space_before_zero = xref_offset - 1;

// field 1 contains offsets and object stream identifiers
int f1_size = std::max(bytesNeeded(max_offset + hint_length),
bytesNeeded(max_id));
unsigned int f1_size = std::max(bytesNeeded(max_offset + hint_length),
bytesNeeded(max_id));

// field 2 contains object stream indices
int f2_size = bytesNeeded(this->m->max_ostream_index);
unsigned int f2_size = bytesNeeded(this->m->max_ostream_index);

unsigned int esize = 1 + f1_size + f2_size;

Expand Down Expand Up @@ -2925,15 +2926,15 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset,
offset += hint_length;
}
writeBinary(1, 1);
writeBinary(offset, f1_size);
writeBinary(QIntC::to_ulonglong(offset), f1_size);
writeBinary(0, f2_size);
}
break;

case 2:
writeBinary(2, 1);
writeBinary(e.getObjStreamNumber(), f1_size);
writeBinary(e.getObjStreamIndex(), f2_size);
writeBinary(QIntC::to_ulonglong(e.getObjStreamNumber()), f1_size);
writeBinary(QIntC::to_ulonglong(e.getObjStreamIndex()), f2_size);
break;

default:
Expand All @@ -2949,7 +2950,7 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset,
writeStringQDF("\n ");
writeString(" /Type /XRef");
writeStringQDF("\n ");
writeString(" /Length " + QUtil::int_to_string(xref_data->getSize()));
writeString(" /Length " + QUtil::uint_to_string(xref_data->getSize()));
if (compressed)
{
writeStringQDF("\n ");
Expand Down Expand Up @@ -2977,7 +2978,7 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset,
}

int
QPDFWriter::calculateXrefStreamPadding(int xref_bytes)
QPDFWriter::calculateXrefStreamPadding(qpdf_offset_t xref_bytes)
{
// This routine is called right after a linearization first pass
// xref stream has been written without compression. Calculate
Expand All @@ -2987,7 +2988,7 @@ QPDFWriter::calculateXrefStreamPadding(int xref_bytes)
// input by 6 bytes plus 5 bytes per 16K, and then we'll add 10
// extra bytes for number length increases.

return 16 + (5 * ((xref_bytes + 16383) / 16384));
return QIntC::to_int(16 + (5 * ((xref_bytes + 16383) / 16384)));
}

void
Expand Down Expand Up @@ -3062,7 +3063,8 @@ QPDFWriter::writeLinearized()
//

// Second half objects
int second_half_uncompressed = part7.size() + part8.size() + part9.size();
int second_half_uncompressed =
QIntC::to_int(part7.size() + part8.size() + part9.size());
int second_half_first_obj = 1;
int after_second_half = 1 + second_half_uncompressed;
this->m->next_objid = after_second_half;
Expand Down Expand Up @@ -3093,15 +3095,15 @@ QPDFWriter::writeLinearized()
first_half_xref = this->m->next_objid++;
}
int part4_first_obj = this->m->next_objid;
this->m->next_objid += part4.size();
this->m->next_objid += QIntC::to_int(part4.size());
int after_part4 = this->m->next_objid;
if (this->m->encrypted)
{
this->m->encryption_dict_objid = this->m->next_objid++;
}
int hint_id = this->m->next_objid++;
int part6_first_obj = this->m->next_objid;
this->m->next_objid += part6.size();
this->m->next_objid += QIntC::to_int(part6.size());
int after_part6 = this->m->next_objid;
// Assign numbers to all compressed objects in the first half
std::vector<QPDFObjectHandle>* vecs1[] = {&part4, &part6};
Expand Down Expand Up @@ -3188,7 +3190,7 @@ QPDFWriter::writeLinearized()
this->m->pdf.getAllPages();
int first_page_object =
this->m->obj_renumber[pages.at(0).getObjGen()];
int npages = pages.size();
int npages = QIntC::to_int(pages.size());

writeString(" /Linearized 1 /L ");
writeString(QUtil::int_to_string(file_size + hint_length));
Expand All @@ -3211,7 +3213,7 @@ QPDFWriter::writeLinearized()
writeString(" >>");
closeObject(lindict_id);
static int const pad = 200;
int spaces = (pos - this->m->pipeline->getCount() + pad);
int spaces = QIntC::to_int(pos - this->m->pipeline->getCount() + pad);
assert(spaces >= 0);
writePad(spaces);
writeString("\n");
Expand Down Expand Up @@ -3263,7 +3265,7 @@ QPDFWriter::writeLinearized()
{
// Pad so that the next object starts at the same
// place as in pass 1.
writePad(first_xref_end - endpos);
writePad(QIntC::to_int(first_xref_end - endpos));

if (this->m->pipeline->getCount() != first_xref_end)
{
Expand Down Expand Up @@ -3346,7 +3348,8 @@ QPDFWriter::writeLinearized()
{
// Make the file size the same.
qpdf_offset_t pos = this->m->pipeline->getCount();
writePad(second_xref_end + hint_length - 1 - pos);
writePad(
QIntC::to_int(second_xref_end + hint_length - 1 - pos));
writeString("\n");

// If this assertion fails, maybe we didn't have
Expand Down Expand Up @@ -3396,7 +3399,7 @@ QPDFWriter::writeLinearized()
activatePipelineStack();
writeHintStream(hint_id);
popPipelineStack(&hint_buffer);
hint_length = hint_buffer->getSize();
hint_length = QIntC::to_offset(hint_buffer->getSize());

// Restore hint offset
this->m->xref[hint_id] = QPDFXRefEntry(1, hint_offset, 0);
Expand Down
3 changes: 2 additions & 1 deletion libqpdf/QPDFXRefEntry.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <qpdf/QPDFXRefEntry.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>

QPDFXRefEntry::QPDFXRefEntry() :
type(0),
Expand Down Expand Up @@ -46,7 +47,7 @@ QPDFXRefEntry::getObjStreamNumber() const
throw std::logic_error(
"getObjStreamNumber called for xref entry of type != 2");
}
return this->field1;
return QIntC::to_int(this->field1);
}

int
Expand Down
13 changes: 8 additions & 5 deletions libqpdf/QPDF_Array.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <qpdf/QPDF_Array.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>
#include <stdexcept>

QPDF_Array::QPDF_Array(std::vector<QPDFObjectHandle> const& items) :
Expand Down Expand Up @@ -68,18 +69,20 @@ QPDF_Array::setDescription(QPDF* qpdf, std::string const& description)
int
QPDF_Array::getNItems() const
{
return this->items.size();
// This should really return a size_t, but changing it would break
// a lot of code.
return QIntC::to_int(this->items.size());
}

QPDFObjectHandle
QPDF_Array::getItem(int n) const
{
if ((n < 0) || (n >= static_cast<int>(this->items.size())))
if ((n < 0) || (n >= QIntC::to_int(this->items.size())))
{
throw std::logic_error(
"INTERNAL ERROR: bounds error accessing QPDF_Array element");
}
return this->items.at(n);
return this->items.at(QIntC::to_size(n));
}

std::vector<QPDFObjectHandle> const&
Expand All @@ -93,7 +96,7 @@ QPDF_Array::setItem(int n, QPDFObjectHandle const& oh)
{
// Call getItem for bounds checking
(void) getItem(n);
this->items.at(n) = oh;
this->items.at(QIntC::to_size(n)) = oh;
}

void
Expand All @@ -106,7 +109,7 @@ void
QPDF_Array::insertItem(int at, QPDFObjectHandle const& item)
{
// As special case, also allow insert beyond the end
if ((at < 0) || (at > static_cast<int>(this->items.size())))
if ((at < 0) || (at > QIntC::to_int(this->items.size())))
{
throw std::logic_error(
"INTERNAL ERROR: bounds error accessing QPDF_Array element");
Expand Down
20 changes: 13 additions & 7 deletions libqpdf/QPDF_Stream.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/Pl_QPDFTokenizer.hh>
#include <qpdf/QIntC.hh>

#include <stdexcept>

Expand Down Expand Up @@ -199,7 +200,7 @@ QPDF_Stream::understandDecodeParams(
QPDFObjectHandle predictor_obj = decode_obj.getKey(key);
if (predictor_obj.isInteger())
{
predictor = predictor_obj.getIntValue();
predictor = predictor_obj.getIntValueAsInt();
if (! ((predictor == 1) || (predictor == 2) ||
((predictor >= 10) && (predictor <= 15))))
{
Expand All @@ -216,7 +217,7 @@ QPDF_Stream::understandDecodeParams(
QPDFObjectHandle earlychange_obj = decode_obj.getKey(key);
if (earlychange_obj.isInteger())
{
int earlychange = earlychange_obj.getIntValue();
int earlychange = earlychange_obj.getIntValueAsInt();
early_code_change = (earlychange == 1);
if (! ((earlychange == 0) || (earlychange == 1)))
{
Expand All @@ -235,7 +236,7 @@ QPDF_Stream::understandDecodeParams(
QPDFObjectHandle param_obj = decode_obj.getKey(key);
if (param_obj.isInteger())
{
int val = param_obj.getIntValue();
int val = param_obj.getIntValueAsInt();
if (key == "/Columns")
{
columns = val;
Expand Down Expand Up @@ -550,15 +551,19 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline,
QTC::TC("qpdf", "QPDF_Stream PNG filter");
pipeline = new Pl_PNGFilter(
"png decode", pipeline, Pl_PNGFilter::a_decode,
columns, colors, bits_per_component);
QIntC::to_uint(columns),
QIntC::to_uint(colors),
QIntC::to_uint(bits_per_component));
to_delete.push_back(pipeline);
}
else if (predictor == 2)
{
QTC::TC("qpdf", "QPDF_Stream TIFF predictor");
pipeline = new Pl_TIFFPredictor(
"tiff decode", pipeline, Pl_TIFFPredictor::a_decode,
columns, colors, bits_per_component);
QIntC::to_uint(columns),
QIntC::to_uint(colors),
QIntC::to_uint(bits_per_component));
to_delete.push_back(pipeline);
}
}
Expand Down Expand Up @@ -744,7 +749,8 @@ QPDF_Stream::replaceFilterData(QPDFObjectHandle const& filter,
else
{
this->stream_dict.replaceKey(
"/Length", QPDFObjectHandle::newInteger(length));
"/Length", QPDFObjectHandle::newInteger(
QIntC::to_longlong(length)));
}
}

Expand All @@ -756,7 +762,7 @@ QPDF_Stream::replaceDict(QPDFObjectHandle new_dict)
QPDFObjectHandle length_obj = new_dict.getKey("/Length");
if (length_obj.isInteger())
{
this->length = length_obj.getIntValue();
this->length = QIntC::to_size(length_obj.getUIntValue());
}
else
{
Expand Down
7 changes: 4 additions & 3 deletions libqpdf/QPDF_String.cc
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@
#include <string.h>

// See above about ctype.
static bool is_ascii_printable(unsigned char ch)
static bool is_ascii_printable(char ch)
{
return ((ch >= 32) && (ch <= 126));
}
static bool is_iso_latin1_printable(unsigned char ch)
static bool is_iso_latin1_printable(char ch)
{
return (((ch >= 32) && (ch <= 126)) || (ch >= 160));
return (((ch >= 32) && (ch <= 126)) ||
(static_cast<unsigned char>(ch) >= 160));
}

QPDF_String::QPDF_String(std::string const& val) :
Expand Down
87 changes: 45 additions & 42 deletions libqpdf/QPDF_encryption.cc
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,9 @@ QPDF::EncryptionData::setV5EncryptionParameters(
static void
pad_or_truncate_password_V4(std::string const& password, char k1[key_bytes])
{
int password_bytes = std::min(static_cast<size_t>(key_bytes),
password.length());
int pad_bytes = key_bytes - password_bytes;
size_t password_bytes = std::min(QIntC::to_size(key_bytes),
password.length());
size_t pad_bytes = key_bytes - password_bytes;
memcpy(k1, password.c_str(), password_bytes);
memcpy(k1 + password_bytes, padding_string, pad_bytes);
}
Expand All @@ -154,9 +154,10 @@ QPDF::trim_user_password(std::string& user_password)
char const* p2 = 0;
while ((p2 = strchr(p1, '\x28')) != 0)
{
if (memcmp(p2, padding_string, len - (p2 - cstr)) == 0)
size_t idx = toS(p2 - cstr);
if (memcmp(p2, padding_string, len - idx) == 0)
{
user_password = user_password.substr(0, p2 - cstr);
user_password = user_password.substr(0, idx);
return;
}
else
Expand All @@ -183,34 +184,35 @@ truncate_password_V5(std::string const& password)
}

static void
iterate_md5_digest(MD5& md5, MD5::Digest& digest, int iterations, int key_len)
iterate_md5_digest(MD5& md5, MD5::Digest& digest,
int iterations, int key_len)
{
md5.digest(digest);

for (int i = 0; i < iterations; ++i)
{
MD5 m;
m.encodeDataIncrementally(reinterpret_cast<char*>(digest),
key_len);
QIntC::to_size(key_len));
m.digest(digest);
}
}


static void
iterate_rc4(unsigned char* data, int data_len,
iterate_rc4(unsigned char* data, size_t data_len,
unsigned char* okey, int key_len,
int iterations, bool reverse)
{
unsigned char* key = new unsigned char[key_len];
unsigned char* key = new unsigned char[QIntC::to_size(key_len)];
for (int i = 0; i < iterations; ++i)
{
int const xor_value = (reverse ? iterations - 1 - i : i);
for (int j = 0; j < key_len; ++j)
{
key[j] = okey[j] ^ xor_value;
key[j] = static_cast<unsigned char>(okey[j] ^ xor_value);
}
RC4 rc4(key, key_len);
RC4 rc4(key, QIntC::to_int(key_len));
rc4.process(data, data_len);
}
delete [] key;
Expand All @@ -228,7 +230,7 @@ process_with_aes(std::string const& key,
Pl_Buffer buffer("buffer");
Pl_AES_PDF aes("aes", &buffer, encrypt,
QUtil::unsigned_char_pointer(key),
key.length());
QIntC::to_uint(key.length()));
if (iv)
{
aes.setIV(iv, iv_length);
Expand Down Expand Up @@ -328,7 +330,7 @@ hash_V5(std::string const& password,
{
unsigned int ch = static_cast<unsigned char>(*(E.rbegin()));

if (ch <= static_cast<unsigned int>(round_number - 32))
if (ch <= QIntC::to_uint(round_number - 32))
{
done = true;
}
Expand All @@ -341,7 +343,7 @@ hash_V5(std::string const& password,
}

static
void pad_short_parameter(std::string& param, unsigned int max_len)
void pad_short_parameter(std::string& param, size_t max_len)
{
if (param.length() < max_len)
{
Expand All @@ -367,11 +369,11 @@ QPDF::compute_data_key(std::string const& encryption_key,
}

// Append low three bytes of object ID and low two bytes of generation
result += static_cast<char>(objid & 0xff);
result += static_cast<char>((objid >> 8) & 0xff);
result += static_cast<char>((objid >> 16) & 0xff);
result += static_cast<char>(generation & 0xff);
result += static_cast<char>((generation >> 8) & 0xff);
result.append(1, static_cast<char>(objid & 0xff));
result.append(1, static_cast<char>((objid >> 8) & 0xff));
result.append(1, static_cast<char>((objid >> 16) & 0xff));
result.append(1, static_cast<char>(generation & 0xff));
result.append(1, static_cast<char>((generation >> 8) & 0xff));
if (use_aes)
{
result += "sAlT";
Expand All @@ -382,7 +384,7 @@ QPDF::compute_data_key(std::string const& encryption_key,
MD5::Digest digest;
md5.digest(digest);
return std::string(reinterpret_cast<char*>(digest),
std::min(result.length(), static_cast<size_t>(16)));
std::min(result.length(), toS(16)));
}

std::string
Expand Down Expand Up @@ -437,10 +439,9 @@ QPDF::compute_encryption_key_from_password(
md5.encodeDataIncrementally(bytes, 4);
}
MD5::Digest digest;
int key_len = std::min(static_cast<int>(sizeof(digest)),
data.getLengthBytes());
int key_len = std::min(QIntC::to_int(sizeof(digest)), data.getLengthBytes());
iterate_md5_digest(md5, digest, ((data.getR() >= 3) ? 50 : 0), key_len);
return std::string(reinterpret_cast<char*>(digest), key_len);
return std::string(reinterpret_cast<char*>(digest), QIntC::to_size(key_len));
}

static void
Expand All @@ -463,7 +464,7 @@ compute_O_rc4_key(std::string const& user_password,
md5.encodeDataIncrementally(
pad_or_truncate_password_V4(password).c_str(), key_bytes);
MD5::Digest digest;
int key_len = std::min(static_cast<int>(sizeof(digest)),
int key_len = std::min(QIntC::to_int(sizeof(digest)),
data.getLengthBytes());
iterate_md5_digest(md5, digest, ((data.getR() >= 3) ? 50 : 0), key_len);
memcpy(key, digest, OU_key_bytes_V4);
Expand All @@ -482,7 +483,7 @@ compute_O_value(std::string const& user_password,
char upass[key_bytes];
pad_or_truncate_password_V4(user_password, upass);
std::string k1(reinterpret_cast<char*>(O_key), OU_key_bytes_V4);
pad_short_parameter(k1, data.getLengthBytes());
pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes()));
iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes,
O_key, data.getLengthBytes(),
(data.getR() >= 3) ? 20 : 1, false);
Expand All @@ -499,7 +500,7 @@ compute_U_value_R2(std::string const& user_password,
std::string k1 = QPDF::compute_encryption_key(user_password, data);
char udata[key_bytes];
pad_or_truncate_password_V4("", udata);
pad_short_parameter(k1, data.getLengthBytes());
pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes()));
iterate_rc4(QUtil::unsigned_char_pointer(udata), key_bytes,
QUtil::unsigned_char_pointer(k1),
data.getLengthBytes(), 1, false);
Expand All @@ -521,7 +522,7 @@ compute_U_value_R3(std::string const& user_password,
data.getId1().length());
MD5::Digest digest;
md5.digest(digest);
pad_short_parameter(k1, data.getLengthBytes());
pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes()));
iterate_rc4(digest, sizeof(MD5::Digest),
QUtil::unsigned_char_pointer(k1),
data.getLengthBytes(), 20, false);
Expand Down Expand Up @@ -555,8 +556,8 @@ check_user_password_V4(std::string const& user_password,
// Algorithm 3.6 from the PDF 1.7 Reference Manual

std::string u_value = compute_U_value(user_password, data);
int to_compare = ((data.getR() >= 3) ? sizeof(MD5::Digest)
: key_bytes);
size_t to_compare = ((data.getR() >= 3) ? sizeof(MD5::Digest)
: key_bytes);
return (memcmp(data.getU().c_str(), u_value.c_str(), to_compare) == 0);
}

Expand Down Expand Up @@ -598,7 +599,7 @@ check_owner_password_V4(std::string& user_password,
unsigned char O_data[key_bytes];
memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);
std::string k1(reinterpret_cast<char*>(key), OU_key_bytes_V4);
pad_short_parameter(k1, data.getLengthBytes());
pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes()));
iterate_rc4(O_data, key_bytes, QUtil::unsigned_char_pointer(k1),
data.getLengthBytes(),
(data.getR() >= 3) ? 20 : 1, true);
Expand Down Expand Up @@ -694,7 +695,8 @@ compute_Perms_value_V5_clear(std::string const& encryption_key,
unsigned char k[16])
{
// From algorithm 3.10 from the PDF 1.7 extension level 3
unsigned long long extended_perms = 0xffffffff00000000LL | data.getP();
unsigned long long extended_perms =
0xffffffff00000000LL | static_cast<unsigned long long>(data.getP());
for (int i = 0; i < 8; ++i)
{
k[i] = static_cast<unsigned char>(extended_perms & 0xff);
Expand Down Expand Up @@ -868,11 +870,11 @@ QPDF::initializeEncryption()
"or the wrong type");
}

int V = encryption_dict.getKey("/V").getIntValue();
int R = encryption_dict.getKey("/R").getIntValue();
int V = encryption_dict.getKey("/V").getIntValueAsInt();
int R = encryption_dict.getKey("/R").getIntValueAsInt();
std::string O = encryption_dict.getKey("/O").getStringValue();
std::string U = encryption_dict.getKey("/U").getStringValue();
unsigned int P = encryption_dict.getKey("/P").getIntValue();
int P = encryption_dict.getKey("/P").getIntValueAsInt();

// If supporting new encryption R/V values, remember to update
// error message inside this if statement.
Expand Down Expand Up @@ -935,7 +937,7 @@ QPDF::initializeEncryption()
int Length = 40;
if (encryption_dict.getKey("/Length").isInteger())
{
Length = encryption_dict.getKey("/Length").getIntValue();
Length = encryption_dict.getKey("/Length").getIntValueAsInt();
if (R < 3)
{
// Force Length to 40 regardless of what the file says.
Expand Down Expand Up @@ -1013,7 +1015,8 @@ QPDF::initializeEncryption()
}
}

EncryptionData data(V, R, Length / 8, P, O, U, OE, UE, Perms,
EncryptionData data(V, R, Length / 8,
P, O, U, OE, UE, Perms,
id1, this->m->encp->encrypt_metadata);
if (this->m->provided_password_is_hex_key)
{
Expand Down Expand Up @@ -1154,11 +1157,11 @@ QPDF::decryptString(std::string& str, int objid, int generation)
else
{
QTC::TC("qpdf", "QPDF_encryption rc4 decode string");
unsigned int vlen = str.length();
size_t vlen = str.length();
// Using PointerHolder guarantees that tmp will
// be freed even if rc4.process throws an exception.
PointerHolder<char> tmp(true, QUtil::copy_string(str));
RC4 rc4(QUtil::unsigned_char_pointer(key), key.length());
RC4 rc4(QUtil::unsigned_char_pointer(key), toI(key.length()));
rc4.process(QUtil::unsigned_char_pointer(tmp.getPointer()), vlen);
str = std::string(tmp.getPointer(), vlen);
}
Expand Down Expand Up @@ -1313,7 +1316,7 @@ QPDF::decryptStream(PointerHolder<EncryptionParameters> encp,
QTC::TC("qpdf", "QPDF_encryption rc4 decode stream");
pipeline = new Pl_RC4("RC4 stream decryption", pipeline,
QUtil::unsigned_char_pointer(key),
key.length());
toI(key.length()));
}
heap.push_back(pipeline);
}
Expand Down Expand Up @@ -1404,9 +1407,9 @@ QPDF::isEncrypted(int& R, int& P, int& V,
QPDFObjectHandle Pkey = encrypt.getKey("/P");
QPDFObjectHandle Rkey = encrypt.getKey("/R");
QPDFObjectHandle Vkey = encrypt.getKey("/V");
P = Pkey.getIntValue();
R = Rkey.getIntValue();
V = Vkey.getIntValue();
P = Pkey.getIntValueAsInt();
R = Rkey.getIntValueAsInt();
V = Vkey.getIntValueAsInt();
stream_method = this->m->encp->cf_stream;
string_method = this->m->encp->cf_string;
file_method = this->m->encp->cf_file;
Expand Down
279 changes: 144 additions & 135 deletions libqpdf/QPDF_linearization.cc

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions libqpdf/QPDF_optimization.cc
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ QPDF::optimize(std::map<int, int> const& object_stream_data,
pushInheritedAttributesToPage(allow_changes, false);

// Traverse pages
int n = this->m->all_pages.size();
int n = toI(this->m->all_pages.size());
for (int pageno = 0; pageno < n; ++pageno)
{
updateObjectMaps(ObjUser(ObjUser::ou_page, pageno),
this->m->all_pages.at(pageno));
this->m->all_pages.at(toS(pageno)));
}

// Traverse document-level items
Expand Down
33 changes: 16 additions & 17 deletions libqpdf/QPDF_pages.cc
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,17 @@ QPDF::flattenPagesTree()

QPDFObjectHandle pages = getRoot().getKey("/Pages");

int const len = this->m->all_pages.size();
for (int pos = 0; pos < len; ++pos)
size_t const len = this->m->all_pages.size();
for (size_t pos = 0; pos < len; ++pos)
{
// populate pageobj_to_pages_pos and fix parent pointer
insertPageobjToPage(this->m->all_pages.at(pos), pos, true);
insertPageobjToPage(this->m->all_pages.at(pos), toI(pos), true);
this->m->all_pages.at(pos).replaceKey("/Parent", pages);
}

pages.replaceKey("/Kids", QPDFObjectHandle::newArray(this->m->all_pages));
// /Count has not changed
if (pages.getKey("/Count").getIntValue() != len)
if (pages.getKey("/Count").getUIntValue() != len)
{
throw std::logic_error("/Count is wrong after flattening pages tree");
}
Expand Down Expand Up @@ -222,26 +222,25 @@ QPDF::insertPage(QPDFObjectHandle newpage, int pos)

QTC::TC("qpdf", "QPDF insert page",
(pos == 0) ? 0 : // insert at beginning
(pos == static_cast<int>(this->m->all_pages.size())) ? 1 : // at end
(pos == QIntC::to_int(this->m->all_pages.size())) ? 1 : // at end
2); // insert in middle

QPDFObjectHandle pages = getRoot().getKey("/Pages");
QPDFObjectHandle kids = pages.getKey("/Kids");
assert ((pos >= 0) &&
(static_cast<size_t>(pos) <= this->m->all_pages.size()));
assert ((pos >= 0) && (QIntC::to_size(pos) <= this->m->all_pages.size()));

newpage.replaceKey("/Parent", pages);
kids.insertItem(pos, newpage);
int npages = kids.getArrayNItems();
pages.replaceKey("/Count", QPDFObjectHandle::newInteger(npages));
this->m->all_pages.insert(this->m->all_pages.begin() + pos, newpage);
assert(this->m->all_pages.size() == static_cast<size_t>(npages));
assert(this->m->all_pages.size() == QIntC::to_size(npages));
for (int i = pos + 1; i < npages; ++i)
{
insertPageobjToPage(this->m->all_pages.at(i), i, false);
insertPageobjToPage(this->m->all_pages.at(toS(i)), i, false);
}
insertPageobjToPage(newpage, pos, true);
assert(this->m->pageobj_to_pages_pos.size() == static_cast<size_t>(npages));
assert(this->m->pageobj_to_pages_pos.size() == QIntC::to_size(npages));
}

void
Expand All @@ -250,8 +249,7 @@ QPDF::removePage(QPDFObjectHandle page)
int pos = findPage(page); // also ensures flat /Pages
QTC::TC("qpdf", "QPDF remove page",
(pos == 0) ? 0 : // remove at beginning
(pos == static_cast<int>(
this->m->all_pages.size() - 1)) ? 1 : // end
(pos == QIntC::to_int(this->m->all_pages.size() - 1)) ? 1 : // end
2); // remove in middle

QPDFObjectHandle pages = getRoot().getKey("/Pages");
Expand All @@ -261,12 +259,12 @@ QPDF::removePage(QPDFObjectHandle page)
int npages = kids.getArrayNItems();
pages.replaceKey("/Count", QPDFObjectHandle::newInteger(npages));
this->m->all_pages.erase(this->m->all_pages.begin() + pos);
assert(this->m->all_pages.size() == static_cast<size_t>(npages));
assert(this->m->all_pages.size() == QIntC::to_size(npages));
this->m->pageobj_to_pages_pos.erase(page.getObjGen());
assert(this->m->pageobj_to_pages_pos.size() == static_cast<size_t>(npages));
assert(this->m->pageobj_to_pages_pos.size() == QIntC::to_size(npages));
for (int i = pos; i < npages; ++i)
{
insertPageobjToPage(this->m->all_pages.at(i), i, false);
insertPageobjToPage(this->m->all_pages.at(toS(i)), i, false);
}
}

Expand All @@ -291,8 +289,9 @@ QPDF::addPage(QPDFObjectHandle newpage, bool first)
}
else
{
insertPage(newpage,
getRoot().getKey("/Pages").getKey("/Count").getIntValue());
insertPage(
newpage,
getRoot().getKey("/Pages").getKey("/Count").getIntValueAsInt());
}
}

Expand Down
78 changes: 39 additions & 39 deletions libqpdf/QUtil.cc
Original file line number Diff line number Diff line change
Expand Up @@ -251,15 +251,15 @@ int_to_string_base_internal(T num, int base, int length)
std::ostringstream buf;
buf << std::setbase(base) << std::nouppercase << num;
std::string result;
if ((length > 0) &&
(buf.str().length() < QIntC::to_size(length)))
int str_length = QIntC::to_int(buf.str().length());
if ((length > 0) && (str_length < length))
{
result.append(length - buf.str().length(), '0');
result.append(QIntC::to_size(length - str_length), '0');
}
result += buf.str();
if ((length < 0) && (buf.str().length() < QIntC::to_size(-length)))
if ((length < 0) && (str_length < -length))
{
result.append(-length - buf.str().length(), ' ');
result.append(QIntC::to_size(-length - str_length), ' ');
}
return result;
}
Expand All @@ -273,7 +273,7 @@ QUtil::int_to_string(long long num, int length)
std::string
QUtil::uint_to_string(unsigned long long num, int length)
{
return int_to_string_base(num, 10, length);
return uint_to_string_base(num, 10, length);
}

std::string
Expand Down Expand Up @@ -420,7 +420,7 @@ QUtil::safe_fopen(char const* filename, char const* mode)
wmode[strlen(mode)] = 0;
for (size_t i = 0; i < strlen(mode); ++i)
{
wmode[i] = mode[i];
wmode[i] = static_cast<wchar_t>(mode[i]);
}

#ifdef _MSC_VER
Expand Down Expand Up @@ -465,9 +465,7 @@ QUtil::seek(FILE* stream, qpdf_offset_t offset, int whence)
# if defined _MSC_VER || defined __BORLANDC__
return _fseeki64(stream, offset, whence);
# else
return fseek(stream,
QIntC::IntConverter<qpdf_offset_t, long>(offset),
whence);
return fseek(stream, QIntC::to_long(offset), whence);
# endif
#endif
}
Expand Down Expand Up @@ -572,17 +570,15 @@ QUtil::hex_decode(std::string const& input)
bool skip = false;
if ((*p >= 'A') && (*p <= 'F'))
{
ch -= 'A';
ch += 10;
ch = QIntC::to_char(ch - 'A' + 10);
}
else if ((*p >= 'a') && (*p <= 'f'))
{
ch -= 'a';
ch += 10;
ch = QIntC::to_char(ch - 'a' + 10);
}
else if ((*p >= '0') && (*p <= '9'))
{
ch -= '0';
ch = QIntC::to_char(ch - '0');
}
else
{
Expand All @@ -592,12 +588,12 @@ QUtil::hex_decode(std::string const& input)
{
if (pos == 0)
{
result.push_back(ch << 4);
result.push_back(static_cast<char>(ch << 4));
pos = 1;
}
else
{
result[result.length()-1] += ch;
result[result.length()-1] |= ch;
pos = 0;
}
}
Expand Down Expand Up @@ -717,7 +713,7 @@ QUtil::get_current_time()
uinow.LowPart = filenow.dwLowDateTime;
uinow.HighPart = filenow.dwHighDateTime;
ULONGLONG now = uinow.QuadPart;
return ((now / 10000000LL) - 11644473600LL);
return static_cast<time_t>((now / 10000000ULL) - 11644473600ULL);
#else
return time(0);
#endif
Expand Down Expand Up @@ -762,7 +758,7 @@ QUtil::toUTF8(unsigned long uval)
*cur_byte = static_cast<unsigned char>(0x80 + (uval & 0x3f));
uval >>= 6;
// Maximum that will fit in high byte now shrinks by one bit
maxval >>= 1;
maxval = static_cast<unsigned char>(maxval >> 1);
// Slide to the left one byte
if (cur_byte <= bytes)
{
Expand All @@ -773,7 +769,7 @@ QUtil::toUTF8(unsigned long uval)
// If maxval is k bits long, the high (7 - k) bits of the
// resulting byte must be high.
*cur_byte = static_cast<unsigned char>(
(0xff - (1 + (maxval << 1))) + uval);
QIntC::to_ulong(0xff - (1 + (maxval << 1))) + uval);

result += reinterpret_cast<char*>(cur_byte);
}
Expand All @@ -792,20 +788,22 @@ QUtil::toUTF16(unsigned long uval)
else if (uval <= 0xffff)
{
char out[2];
out[0] = (uval & 0xff00) >> 8;
out[1] = (uval & 0xff);
out[0] = static_cast<char>((uval & 0xff00) >> 8);
out[1] = static_cast<char>(uval & 0xff);
result = std::string(out, 2);
}
else if (uval <= 0x10ffff)
{
char out[4];
uval -= 0x10000;
unsigned short high = ((uval & 0xffc00) >> 10) + 0xd800;
unsigned short low = (uval & 0x3ff) + 0xdc00;
out[0] = (high & 0xff00) >> 8;
out[1] = (high & 0xff);
out[2] = (low & 0xff00) >> 8;
out[3] = (low & 0xff);
unsigned short high =
static_cast<unsigned short>(((uval & 0xffc00) >> 10) + 0xd800);
unsigned short low =
static_cast<unsigned short>((uval & 0x3ff) + 0xdc00);
out[0] = static_cast<char>((high & 0xff00) >> 8);
out[1] = static_cast<char>(high & 0xff);
out[2] = static_cast<char>((low & 0xff00) >> 8);
out[3] = static_cast<char>(low & 0xff);
result = std::string(out, 4);
}
else
Expand Down Expand Up @@ -1172,7 +1170,8 @@ QUtil::parse_numrange(char const* range, int max)
if (p)
{
message = "error at * in numeric range " +
std::string(range, p - range) + "*" + p + ": " + e.what();
std::string(range, QIntC::to_size(p - range)) +
"*" + p + ": " + e.what();
}
else
{
Expand Down Expand Up @@ -1764,7 +1763,7 @@ unsigned long get_next_utf8_codepoint(
while (ch & bit_check)
{
++bytes_needed;
to_clear |= bit_check;
to_clear = static_cast<unsigned char>(to_clear | bit_check);
bit_check >>= 1;
}
if (((bytes_needed > 5) || (bytes_needed < 1)) ||
Expand All @@ -1774,11 +1773,11 @@ unsigned long get_next_utf8_codepoint(
return 0xfffd;
}

unsigned long codepoint = (ch & ~to_clear);
unsigned long codepoint = static_cast<unsigned long>(ch & ~to_clear);
while (bytes_needed > 0)
{
--bytes_needed;
ch = utf8_val.at(++pos);
ch = static_cast<unsigned char>(utf8_val.at(++pos));
if ((ch & 0xc0) != 0x80)
{
--pos;
Expand Down Expand Up @@ -1823,7 +1822,7 @@ transcode_utf8(std::string const& utf8_val, std::string& result,
char ch = static_cast<char>(codepoint);
if (encoding == e_utf16)
{
result += QUtil::toUTF16(ch);
result += QUtil::toUTF16(QIntC::to_ulong(ch));
}
else
{
Expand All @@ -1837,7 +1836,7 @@ transcode_utf8(std::string const& utf8_val, std::string& result,
else if ((codepoint > 160) && (codepoint < 256) &&
((encoding == e_winansi) || (encoding == e_pdfdoc)))
{
result.append(1, static_cast<unsigned char>(codepoint & 0xff));
result.append(1, static_cast<char>(codepoint & 0xff));
}
else
{
Expand All @@ -1859,7 +1858,7 @@ transcode_utf8(std::string const& utf8_val, std::string& result,
okay = false;
ch = static_cast<unsigned char>(unknown);
}
result.append(1, ch);
result.append(1, static_cast<char>(ch));
}
}
return okay;
Expand Down Expand Up @@ -1956,7 +1955,7 @@ QUtil::utf16_to_utf8(std::string const& val)
}
// If the string has an odd number of bytes, the last byte is
// ignored.
for (unsigned int i = start; i < len; i += 2)
for (size_t i = start; i < len; i += 2)
{
// Convert from UTF16-BE. If we get a malformed
// codepoint, this code will generate incorrect output
Expand All @@ -1965,11 +1964,12 @@ QUtil::utf16_to_utf8(std::string const& val)
// discarded, and a low codepoint not preceded by a high
// codepoint will just get its low 10 bits output.
unsigned short bits =
(static_cast<unsigned char>(val.at(i)) << 8) +
static_cast<unsigned char>(val.at(i+1));
QIntC::to_ushort(
(static_cast<unsigned char>(val.at(i)) << 8) +
static_cast<unsigned char>(val.at(i+1)));
if ((bits & 0xFC00) == 0xD800)
{
codepoint = 0x10000 + ((bits & 0x3FF) << 10);
codepoint = 0x10000U + ((bits & 0x3FFU) << 10U);
continue;
}
else if ((bits & 0xFC00) == 0xDC00)
Expand Down
14 changes: 8 additions & 6 deletions libqpdf/RC4.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <qpdf/RC4.hh>
#include <qpdf/QIntC.hh>

#include <string.h>

Expand All @@ -15,12 +16,13 @@ RC4::RC4(unsigned char const* key_data, int key_len)
{
if (key_len == -1)
{
key_len = strlen(reinterpret_cast<char const*>(key_data));
key_len = QIntC::to_int(
strlen(reinterpret_cast<char const*>(key_data)));
}

for (int i = 0; i < 256; ++i)
{
key.state[i] = i;
key.state[i] = static_cast<unsigned char>(i);
}
key.x = 0;
key.y = 0;
Expand All @@ -36,18 +38,18 @@ RC4::RC4(unsigned char const* key_data, int key_len)
}

void
RC4::process(unsigned char *in_data, int len, unsigned char* out_data)
RC4::process(unsigned char *in_data, size_t len, unsigned char* out_data)
{
if (out_data == 0)
{
// Convert in place
out_data = in_data;
}

for (int i = 0; i < len; ++i)
for (size_t i = 0; i < len; ++i)
{
key.x = (key.x + 1) % 256;
key.y = (key.state[key.x] + key.y) % 256;
key.x = static_cast<unsigned char>((key.x + 1) % 256);
key.y = static_cast<unsigned char>((key.state[key.x] + key.y) % 256);
swap_byte(key.state[key.x], key.state[key.y]);
int xor_index = (key.state[key.x] + key.state[key.y]) % 256;
out_data[i] = in_data[i] ^ key.state[xor_index];
Expand Down
6 changes: 4 additions & 2 deletions libqpdf/SecureRandomDataProvider.cc
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ class WindowsCryptProvider
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsign-compare"
# pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
if (GetLastError() == NTE_BAD_KEYSET)
#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \
Expand Down Expand Up @@ -94,7 +95,8 @@ SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len)
// Optimization: make the WindowsCryptProvider static as long as
// it can be done in a thread-safe fashion.
WindowsCryptProvider c;
if (! CryptGenRandom(c.crypt_prov, len, reinterpret_cast<BYTE*>(data)))
if (! CryptGenRandom(c.crypt_prov, static_cast<DWORD>(len),
reinterpret_cast<BYTE*>(data)))
{
throw std::runtime_error("unable to generate secure random data");
}
Expand All @@ -112,7 +114,7 @@ SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len)
{
throw std::runtime_error(
"unable to read " +
QUtil::int_to_string(len) +
QUtil::uint_to_string(len) +
" bytes from " + std::string(RANDOM_DEVICE));
}

Expand Down
27 changes: 14 additions & 13 deletions libqpdf/bits.icc
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

#ifdef BITS_READ
static unsigned long long
read_bits(unsigned char const*& p, unsigned int& bit_offset,
unsigned int& bits_available, unsigned int bits_wanted)
read_bits(unsigned char const*& p, size_t& bit_offset,
size_t& bits_available, size_t bits_wanted)
{
// View p as a stream of bits:

Expand Down Expand Up @@ -46,11 +46,12 @@ read_bits(unsigned char const*& p, unsigned int& bit_offset,
{
// Grab bits from the first byte clearing anything before
// bit_offset.
unsigned char byte = *p & ((1 << (bit_offset + 1)) - 1);
unsigned char byte = static_cast<unsigned char>(
*p & ((1U << (bit_offset + 1U)) - 1U));

// There are bit_offset + 1 bits available in the first byte.
unsigned int to_copy = std::min(bits_wanted, bit_offset + 1);
unsigned int leftover = (bit_offset + 1) - to_copy;
size_t to_copy = std::min(bits_wanted, bit_offset + 1);
size_t leftover = (bit_offset + 1) - to_copy;

#ifdef BITS_TESTING
QTC::TC("libtests", "bits bit_offset",
Expand All @@ -61,7 +62,7 @@ read_bits(unsigned char const*& p, unsigned int& bit_offset,
#endif

// Right shift so that all the bits we want are right justified.
byte >>= leftover;
byte = static_cast<unsigned char>(byte >> leftover);

// Copy the bits into result
result <<= to_copy;
Expand Down Expand Up @@ -94,8 +95,8 @@ read_bits(unsigned char const*& p, unsigned int& bit_offset,

#ifdef BITS_WRITE
static void
write_bits(unsigned char& ch, unsigned int& bit_offset,
unsigned long long val, unsigned int bits, Pipeline* pipeline)
write_bits(unsigned char& ch, size_t& bit_offset,
unsigned long long val, size_t bits, Pipeline* pipeline)
{
if (bits > 32)
{
Expand All @@ -111,11 +112,11 @@ write_bits(unsigned char& ch, unsigned int& bit_offset,
#endif
while (bits > 0)
{
int bits_to_write = std::min(bits, bit_offset + 1);
unsigned char newval =
(val >> (bits - bits_to_write)) & ((1 << bits_to_write) - 1);
int bits_left_in_ch = bit_offset + 1 - bits_to_write;
newval <<= bits_left_in_ch;
size_t bits_to_write = std::min(bits, bit_offset + 1);
unsigned char newval = static_cast<unsigned char>(
(val >> (bits - bits_to_write)) & ((1U << bits_to_write) - 1));
size_t bits_left_in_ch = bit_offset + 1 - bits_to_write;
newval = static_cast<unsigned char>(newval << bits_left_in_ch);
ch |= newval;
if (bits_left_in_ch == 0)
{
Expand Down
5 changes: 3 additions & 2 deletions libqpdf/qpdf-c.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <qpdf/QTC.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/Pl_Discard.hh>
#include <qpdf/QIntC.hh>

#include <list>
#include <string>
Expand Down Expand Up @@ -63,7 +64,7 @@ static void call_read(qpdf_data qpdf)
static void call_read_memory(qpdf_data qpdf)
{
qpdf->qpdf->processMemoryFile(qpdf->filename, qpdf->buffer,
qpdf->size, qpdf->password);
QIntC::to_size(qpdf->size), qpdf->password);
}

// must set qpdf->filename
Expand Down Expand Up @@ -234,7 +235,7 @@ unsigned long long qpdf_get_error_file_position(qpdf_data qpdf, qpdf_error e)
{
return 0;
}
return e->exc->getFilePosition();
return QIntC::to_ulonglong(e->exc->getFilePosition());
}

char const* qpdf_get_error_message_detail(qpdf_data qpdf, qpdf_error e)
Expand Down
17 changes: 11 additions & 6 deletions libqpdf/qpdf/BitStream.hh
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,33 @@
#define BITSTREAM_HH

#include <qpdf/DLL.h>
#include <stddef.h>

class BitStream
{
public:
QPDF_DLL
BitStream(unsigned char const* p, int nbytes);
BitStream(unsigned char const* p, size_t nbytes);
QPDF_DLL
void reset();
QPDF_DLL
unsigned long long getBits(int nbits);
unsigned long long getBits(size_t nbits);
QPDF_DLL
long long getBitsSigned(int nbits);
long long getBitsSigned(size_t nbits);
// Only call getBitsInt when requesting a number of bits that will
// definitely fit in an int.
QPDF_DLL
int getBitsInt(size_t nbits);
QPDF_DLL
void skipToNextByte();

private:
unsigned char const* start;
int nbytes;
size_t nbytes;

unsigned char const* p;
unsigned int bit_offset;
unsigned int bits_available;
size_t bit_offset;
size_t bits_available;
};

#endif // BITSTREAM_HH
9 changes: 6 additions & 3 deletions libqpdf/qpdf/BitWriter.hh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#define BITWRITER_HH

#include <qpdf/DLL.h>
#include <stddef.h>

class Pipeline;

Expand All @@ -15,17 +16,19 @@ class BitWriter
QPDF_DLL
BitWriter(Pipeline* pl);
QPDF_DLL
void writeBits(unsigned long long val, unsigned int bits);
void writeBits(unsigned long long val, size_t bits);
QPDF_DLL
void writeBitsSigned(long long val, unsigned int bits);
void writeBitsSigned(long long val, size_t bits);
QPDF_DLL
void writeBitsInt(int val, size_t bits);
// Force any partial byte to be written to the pipeline.
QPDF_DLL
void flush();

private:
Pipeline* pl;
unsigned char ch;
unsigned int bit_offset;
size_t bit_offset;
};

#endif // BITWRITER_HH
22 changes: 12 additions & 10 deletions libqpdf/qpdf/MD5.hh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <qpdf/DLL.h>
#include <qpdf/qpdf-config.h>
#include <qpdf/Types.h>
#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif
Expand All @@ -25,17 +26,17 @@ class MD5
QPDF_DLL
void encodeString(char const* input_string);

// encodes file and finalizes
// encodes file and finalizes; offset < 0 reads whole file
QPDF_DLL
void encodeFile(char const* filename, int up_to_size = -1);
void encodeFile(char const* filename, qpdf_offset_t up_to_offset = -1);

// appends string to current md5 object
QPDF_DLL
void appendString(char const* input_string);

// appends arbitrary data to current md5 object
QPDF_DLL
void encodeDataIncrementally(char const* input_data, int len);
void encodeDataIncrementally(char const* input_data, size_t len);

// computes a raw digest
QPDF_DLL
Expand All @@ -52,16 +53,17 @@ class MD5

// Convenience functions
QPDF_DLL
static std::string getDataChecksum(char const* buf, int len);
static std::string getDataChecksum(char const* buf, size_t len);
QPDF_DLL
static std::string getFileChecksum(char const* filename,
int up_to_size = -1);
qpdf_offset_t up_to_offset = -1);
QPDF_DLL
static bool checkDataChecksum(char const* const checksum,
char const* buf, int len);
char const* buf, size_t len);
QPDF_DLL
static bool checkFileChecksum(char const* const checksum,
char const* filename, int up_to_size = -1);
char const* filename,
qpdf_offset_t up_to_offset = -1);

private:
// POINTER defines a generic pointer type
Expand All @@ -74,12 +76,12 @@ class MD5
typedef uint32_t UINT4;

void init();
void update(unsigned char *, unsigned int);
void update(unsigned char *, size_t);
void final();

static void transform(UINT4 [4], unsigned char [64]);
static void encode(unsigned char *, UINT4 *, unsigned int);
static void decode(UINT4 *, unsigned char *, unsigned int);
static void encode(unsigned char *, UINT4 *, size_t);
static void decode(UINT4 *, unsigned char *, size_t);

UINT4 state[4]; // state (ABCD)
UINT4 count[2]; // number of bits, modulo 2^64 (lsb first)
Expand Down
3 changes: 2 additions & 1 deletion libqpdf/qpdf/Pl_AES_PDF.hh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ class Pl_AES_PDF: public Pipeline
QPDF_DLL
// key should be a pointer to key_bytes bytes of data
Pl_AES_PDF(char const* identifier, Pipeline* next,
bool encrypt, unsigned char const* key, unsigned int key_bytes);
bool encrypt, unsigned char const* key,
size_t key_bytes);
QPDF_DLL
virtual ~Pl_AES_PDF();

Expand Down
2 changes: 1 addition & 1 deletion libqpdf/qpdf/Pl_ASCII85Decoder.hh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Pl_ASCII85Decoder: public Pipeline
private:
void flush();

char inbuf[5];
unsigned char inbuf[5];
size_t pos;
size_t eod;
};
Expand Down
16 changes: 8 additions & 8 deletions libqpdf/qpdf/Pl_LZWDecoder.hh
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,23 @@ class Pl_LZWDecoder: public Pipeline

private:
void sendNextCode();
void handleCode(int code);
unsigned char getFirstChar(int code);
void handleCode(unsigned int code);
unsigned char getFirstChar(unsigned int code);
void addToTable(unsigned char next);

// members used for converting bits to codes
unsigned char buf[3];
int code_size;
int next;
int byte_pos;
int bit_pos; // left to right: 01234567
int bits_available;
unsigned int code_size;
unsigned int next;
unsigned int byte_pos;
unsigned int bit_pos; // left to right: 01234567
unsigned int bits_available;

// members used for handle LZW decompression
bool code_change_delta;
bool eod;
std::vector<Buffer> table;
int last_code;
unsigned int last_code;
};

#endif // PL_LZWDECODER_HH
2 changes: 1 addition & 1 deletion libqpdf/qpdf/Pl_RC4.hh
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
class Pl_RC4: public Pipeline
{
public:
static int const def_bufsize = 65536;
static size_t const def_bufsize = 65536;

// key_len of -1 means treat key_data as a null-terminated string
QPDF_DLL
Expand Down
5 changes: 4 additions & 1 deletion libqpdf/qpdf/RC4.hh
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
#ifndef RC4_HH
#define RC4_HH

#include <stddef.h>

class RC4
{
public:
// key_len of -1 means treat key_data as a null-terminated string
RC4(unsigned char const* key_data, int key_len = -1);

// out_data = 0 means to encrypt/decrypt in place
void process(unsigned char* in_data, int len, unsigned char* out_data = 0);
void process(unsigned char* in_data, size_t len,
unsigned char* out_data = 0);

private:
class RC4Key
Expand Down
13 changes: 7 additions & 6 deletions libqpdf/qpdf/rijndael.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#include <stddef.h>

int rijndaelSetupEncrypt(uint32_t *rk, const unsigned char *key,
int keybits);
int rijndaelSetupDecrypt(uint32_t *rk, const unsigned char *key,
int keybits);
void rijndaelEncrypt(const uint32_t *rk, int nrounds,
unsigned int rijndaelSetupEncrypt(uint32_t *rk, const unsigned char *key,
size_t keybits);
unsigned int rijndaelSetupDecrypt(uint32_t *rk, const unsigned char *key,
size_t keybits);
void rijndaelEncrypt(const uint32_t *rk, unsigned int nrounds,
const unsigned char plaintext[16], unsigned char ciphertext[16]);
void rijndaelDecrypt(const uint32_t *rk, int nrounds,
void rijndaelDecrypt(const uint32_t *rk, unsigned int nrounds,
const unsigned char ciphertext[16], unsigned char plaintext[16]);

#define KEYLENGTH(keybits) ((keybits)/8)
Expand Down
12 changes: 7 additions & 5 deletions libqpdf/rijndael.cc
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ static const u32 rcon[] =
*
* @return the number of rounds for the given cipher key size.
*/
int rijndaelSetupEncrypt(u32 *rk, const u8 *key, int keybits)
unsigned int rijndaelSetupEncrypt(u32 *rk, const u8 *key, size_t keybits)
{
int i = 0;
u32 temp;
Expand Down Expand Up @@ -799,9 +799,9 @@ int rijndaelSetupEncrypt(u32 *rk, const u8 *key, int keybits)
*
* @return the number of rounds for the given cipher key size.
*/
int rijndaelSetupDecrypt(u32 *rk, const u8 *key, int keybits)
unsigned int rijndaelSetupDecrypt(u32 *rk, const u8 *key, size_t keybits)
{
int nrounds, i, j;
unsigned int nrounds, i, j;
u32 temp;

/* expand the cipher key: */
Expand Down Expand Up @@ -842,7 +842,8 @@ int rijndaelSetupDecrypt(u32 *rk, const u8 *key, int keybits)
return nrounds;
}

void rijndaelEncrypt(const u32 *rk, int nrounds, const u8 plaintext[16],
void rijndaelEncrypt(const u32 *rk, unsigned int nrounds,
const u8 plaintext[16],
u8 ciphertext[16])
{
u32 s0, s1, s2, s3, t0, t1, t2, t3;
Expand Down Expand Up @@ -1024,7 +1025,8 @@ void rijndaelEncrypt(const u32 *rk, int nrounds, const u8 plaintext[16],
PUTU32(ciphertext + 12, s3);
}

void rijndaelDecrypt(const u32 *rk, int nrounds, const u8 ciphertext[16],
void rijndaelDecrypt(const u32 *rk, unsigned int nrounds,
const u8 ciphertext[16],
u8 plaintext[16])
{
u32 s0, s1, s2, s3, t0, t1, t2, t3;
Expand Down
4 changes: 2 additions & 2 deletions libqpdf/sph/md_helper.c
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ SPH_XCAT(sph_, HASH)(void *cc, const void *data, size_t len)

clen = SPH_BLEN - current;
if (clen > len)
clen = len;
clen = (unsigned)len;
memcpy(sc->buf + current, data, clen);
data = (const unsigned char *)data + clen;
current += clen;
Expand Down Expand Up @@ -257,7 +257,7 @@ SPH_XCAT(HASH, _addbits_and_close)(void *cc,
{
unsigned z;

z = 0x80 >> n;
z = 0x80U >> n;
sc->buf[current ++] = ((ub & -z) | z) & 0xFF;
}
#endif
Expand Down
8 changes: 4 additions & 4 deletions libqpdf/sph/sph_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -1337,8 +1337,8 @@ sph_bswap64(sph_u64 x)
static SPH_INLINE void
sph_enc16be(void *dst, unsigned val)
{
((unsigned char *)dst)[0] = (val >> 8);
((unsigned char *)dst)[1] = val;
((unsigned char *)dst)[0] = (unsigned char)(val >> 8);
((unsigned char *)dst)[1] = (unsigned char)val;
}

static SPH_INLINE unsigned
Expand All @@ -1351,8 +1351,8 @@ sph_dec16be(const void *src)
static SPH_INLINE void
sph_enc16le(void *dst, unsigned val)
{
((unsigned char *)dst)[0] = val;
((unsigned char *)dst)[1] = val >> 8;
((unsigned char *)dst)[0] = (unsigned char)val;
((unsigned char *)dst)[1] = (unsigned char)(val >> 8);
}

static SPH_INLINE unsigned
Expand Down
Loading