diff --git a/ChangeLog b/ChangeLog index a91961590..713b954a0 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,9 +1,19 @@ 2019-06-20 Jay Berkenbilt + * Fix all integer sign and conversion warnings. This makes all + integer type conversions that have potential data loss explicit + with calls that do range checks and raise an exception. + * Change out_bufsize argument to Pl_Flate's constructor for int to unsigned int for compatibility with underlying zlib implementation. + * Change QPDFObjectHandle::pipeStreamData's encode_flags argument + from unsigned long to int since int is the underlying type of the + enumerated type values that are passed to it. This change should + be invisible to virtually all code unless you are compiling with + strict warning flags and explicitly casting to unsigned long. + * Add methods to QPDFObjectHandle to return the value of Integer objects as int and unsigned int with range checking and fallback behavior to avoid silent underflow/overflow conditions. diff --git a/NOTICE.md b/NOTICE.md index b430a830d..56eb455c9 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -10,8 +10,6 @@ Versions of qpdf prior to version 7 were released under the terms of version 2.0 The qpdf distribution includes a copy of [qtest](http://qtest.qbilt.org), which is released under the terms of the [version 2.0 of the Artistic license](https://opensource.org/licenses/Artistic-2.0), which can be found at https://opensource.org/licenses/Artistic-2.0. -The standalone fuzz target runner (fuzz/standalone_fuzz_target_runner.cc) is copyright 2017 by Google and is also released under the Apache license, Version 2.0. - The Rijndael encryption implementation used as the basis for AES encryption and decryption support comes from Philip J. Erdelsky's public domain implementation. The files `libqpdf/rijndael.cc` and `libqpdf/qpdf/rijndael.h` remain in the public domain. They were obtained from * http://www.efgh.com/software/rijndael.htm * http://www.efgh.com/software/rijndael.txt diff --git a/examples/pdf-create.cc b/examples/pdf-create.cc index 1c787e2eb..b27d4e17d 100644 --- a/examples/pdf-create.cc +++ b/examples/pdf-create.cc @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -30,15 +31,15 @@ class ImageProvider: public QPDFObjectHandle::StreamDataProvider virtual ~ImageProvider(); virtual void provideStreamData(int objid, int generation, Pipeline* pipeline); - int getWidth() const; - int getHeight() const; + size_t getWidth() const; + size_t getHeight() const; private: - int width; - int stripe_height; + size_t width; + size_t stripe_height; std::string color_space; std::string filter; - int n_stripes; + size_t n_stripes; std::vector stripes; J_COLOR_SPACE j_color_space; }; @@ -88,13 +89,13 @@ ImageProvider::~ImageProvider() { } -int +size_t ImageProvider::getWidth() const { return width; } -int +size_t ImageProvider::getHeight() const { return stripe_height * n_stripes; @@ -111,7 +112,8 @@ ImageProvider::provideStreamData(int objid, int generation, { p = new Pl_DCT( "image encoder", pipeline, - width, getHeight(), stripes[0].length(), j_color_space); + QIntC::to_uint(width), QIntC::to_uint(getHeight()), + QIntC::to_int(stripes[0].length()), j_color_space); to_delete.push_back(p); } else if (filter == "/RunLengthDecode") @@ -121,9 +123,9 @@ ImageProvider::provideStreamData(int objid, int generation, to_delete.push_back(p); } - for (int i = 0; i < n_stripes; ++i) + for (size_t i = 0; i < n_stripes; ++i) { - for (int j = 0; j < width * stripe_height; ++j) + for (size_t j = 0; j < width * stripe_height; ++j) { p->write( QUtil::unsigned_char_pointer(stripes[i].c_str()), @@ -155,9 +157,9 @@ QPDFObjectHandle newName(std::string const& name) return QPDFObjectHandle::newName(name); } -QPDFObjectHandle newInteger(int val) +QPDFObjectHandle newInteger(size_t val) { - return QPDFObjectHandle::newInteger(val); + return QPDFObjectHandle::newInteger(QIntC::to_int(val)); } void add_page(QPDFPageDocumentHelper& dh, QPDFObjectHandle font, @@ -173,8 +175,8 @@ void add_page(QPDFPageDocumentHelper& dh, QPDFObjectHandle font, // compression. ImageProvider* p = new ImageProvider(color_space, filter); PointerHolder provider(p); - int width = p->getWidth(); - int height = p->getHeight(); + size_t width = p->getWidth(); + size_t height = p->getHeight(); QPDFObjectHandle image = QPDFObjectHandle::newStream(&pdf); image.replaceDict(QPDFObjectHandle::parse( "<<" @@ -335,8 +337,8 @@ static void check(char const* filename, unsigned int mismatches = 0; int tolerance = ( desired_filter == "/DCTDecode" ? 10 : 0); - unsigned int threshold = ( - desired_filter == "/DCTDecode" ? len / 40 : 0); + size_t threshold = ( + desired_filter == "/DCTDecode" ? len / 40U : 0); for (size_t i = 0; i < len; ++i) { int delta = actual_bytes[i] - desired_bytes[i]; diff --git a/examples/pdf-double-page-size.cc b/examples/pdf-double-page-size.cc index 06c989217..6c5e59137 100644 --- a/examples/pdf-double-page-size.cc +++ b/examples/pdf-double-page-size.cc @@ -34,7 +34,7 @@ static void doubleBoxSize(QPDFObjectHandle& page, char const* box_name) " is not an array of four elements"); } std::vector doubled; - for (unsigned int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { doubled.push_back( QPDFObjectHandle::newReal( diff --git a/examples/pdf-invert-images.cc b/examples/pdf-invert-images.cc index 1469d9cc0..a149c495e 100644 --- a/examples/pdf-invert-images.cc +++ b/examples/pdf-invert-images.cc @@ -7,6 +7,7 @@ #include #include #include +#include static char const* whoami = 0; @@ -56,7 +57,7 @@ ImageInverter::provideStreamData(int objid, int generation, unsigned char ch; for (size_t i = 0; i < size; ++i) { - ch = static_cast(0xff) - buf[i]; + ch = QIntC::to_uchar(0xff - buf[i]); pipeline->write(&ch, 1); } pipeline->finish(); diff --git a/examples/pdf-parse-content.cc b/examples/pdf-parse-content.cc index 8659fbe34..254fcdfe2 100644 --- a/examples/pdf-parse-content.cc +++ b/examples/pdf-parse-content.cc @@ -6,6 +6,7 @@ #include #include #include +#include static char const* whoami = 0; @@ -72,12 +73,12 @@ int main(int argc, char* argv[]) pdf.processFile(filename); std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); - if ((pageno < 1) || (static_cast(pageno) > pages.size())) + if ((pageno < 1) || (QIntC::to_size(pageno) > pages.size())) { usage(); } - QPDFPageObjectHelper& page = pages.at(pageno-1); + QPDFPageObjectHelper& page = pages.at(QIntC::to_size(pageno-1)); ParserCallbacks cb; page.parsePageContents(&cb); } diff --git a/examples/pdf-split-pages.cc b/examples/pdf-split-pages.cc index b6dd701ba..7857d6497 100644 --- a/examples/pdf-split-pages.cc +++ b/examples/pdf-split-pages.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -24,7 +25,8 @@ static void process(char const* whoami, inpdf.processFile(infile); std::vector pages = QPDFPageDocumentHelper(inpdf).getAllPages(); - int pageno_len = QUtil::int_to_string(pages.size()).length(); + int pageno_len = + QIntC::to_int(QUtil::uint_to_string(pages.size()).length()); int pageno = 0; for (std::vector::iterator iter = pages.begin(); iter != pages.end(); ++iter) diff --git a/fuzz/standalone_fuzz_target_runner.cc b/fuzz/standalone_fuzz_target_runner.cc index 9881d0fb4..59fb0438a 100644 --- a/fuzz/standalone_fuzz_target_runner.cc +++ b/fuzz/standalone_fuzz_target_runner.cc @@ -1,34 +1,46 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// Licensed under the Apache License, Version 2.0 (the "License"); - -// Except for formatting, comments, and portability, this was copied -// from projects/example/my-api-repo/standalone_fuzz_target_runner.cpp -// in https://github.com/oss-fuzz - -#include +#include +#include +#include #include -#include -#include +#include extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size); +static void read_file_into_memory( + char const* filename, + PointerHolder& file_buf, size_t& size) +{ + FILE* f = QUtil::safe_fopen(filename, "rb"); + fseek(f, 0, SEEK_END); + size = QIntC::to_size(QUtil::tell(f)); + fseek(f, 0, SEEK_SET); + file_buf = PointerHolder(true, new unsigned char[size]); + unsigned char* buf_p = file_buf.getPointer(); + size_t bytes_read = 0; + size_t len = 0; + while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0) + { + bytes_read += len; + } + if (bytes_read != size) + { + throw std::runtime_error( + std::string("failure reading file ") + filename + + " into memory: read " + + QUtil::uint_to_string(bytes_read) + "; wanted " + + QUtil::uint_to_string(size)); + } + fclose(f); +} + int main(int argc, char **argv) { for (int i = 1; i < argc; i++) { - std::ifstream in(argv[i]); - in.seekg(0, in.end); - size_t length = in.tellg(); - in.seekg (0, in.beg); - std::cout << "checking " << argv[i] << std::endl; - // Allocate exactly length bytes so that we reliably catch - // buffer overflows. - std::vector bytes(length); - in.read(bytes.data(), bytes.size()); - assert(in); - LLVMFuzzerTestOneInput( - reinterpret_cast(bytes.data()), - bytes.size()); + PointerHolder file_buf; + size_t size = 0; + read_file_into_memory(argv[i], file_buf, size); + LLVMFuzzerTestOneInput(file_buf.getPointer(), size); std::cout << argv[i] << " successful" << std::endl; } return 0; diff --git a/include/qpdf/BufferInputSource.hh b/include/qpdf/BufferInputSource.hh index 3fb0625bf..51bb98f9c 100644 --- a/include/qpdf/BufferInputSource.hh +++ b/include/qpdf/BufferInputSource.hh @@ -54,6 +54,8 @@ class BufferInputSource: public InputSource virtual void unreadCh(char ch); private: + qpdf_offset_t const bufSizeAsOffset() const; + bool own_memory; std::string description; Buffer* buf; diff --git a/include/qpdf/Pl_Count.hh b/include/qpdf/Pl_Count.hh index c3f7b3e12..0b021d9ac 100644 --- a/include/qpdf/Pl_Count.hh +++ b/include/qpdf/Pl_Count.hh @@ -48,6 +48,8 @@ class Pl_Count: public Pipeline unsigned char getLastChar() const; private: + // Must be qpdf_offset_t, not size_t, to handle writing more than + // size_t can handle. qpdf_offset_t count; unsigned char last_char; }; diff --git a/include/qpdf/QPDF.hh b/include/qpdf/QPDF.hh index 6de51ef37..c3fa0873c 100644 --- a/include/qpdf/QPDF.hh +++ b/include/qpdf/QPDF.hh @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -859,7 +860,7 @@ class QPDF bool pipeForeignStreamData( PointerHolder, Pipeline*, - unsigned long encode_flags, + int encode_flags, qpdf_stream_decode_level_e decode_level); static bool pipeStreamData(PointerHolder encp, PointerHolder file, @@ -1253,7 +1254,7 @@ class QPDF void dumpHPageOffset(); void dumpHSharedObject(); void dumpHGeneric(HGeneric&); - int adjusted_offset(int offset); + qpdf_offset_t adjusted_offset(qpdf_offset_t offset); QPDFObjectHandle objGenToIndirect(QPDFObjGen const&); void calculateLinearizationData( std::map const& object_stream_data); @@ -1297,6 +1298,20 @@ class QPDF std::set& visited, bool top); void filterCompressedObjects(std::map const& object_stream_data); + // Type conversion helper methods + template static qpdf_offset_t toO(T const& i) + { + return QIntC::to_offset(i); + } + template static size_t toS(T const& i) + { + return QIntC::to_size(i); + } + template static int toI(T const& i) + { + return QIntC::to_int(i); + } + class Members { friend class QPDF; diff --git a/include/qpdf/QPDFWriter.hh b/include/qpdf/QPDFWriter.hh index 0b8bf0289..2ac00582f 100644 --- a/include/qpdf/QPDFWriter.hh +++ b/include/qpdf/QPDFWriter.hh @@ -467,7 +467,7 @@ class QPDFWriter enum trailer_e { t_normal, t_lin_first, t_lin_second }; - int bytesNeeded(unsigned long long n); + unsigned int bytesNeeded(long long n); void writeBinary(unsigned long long val, unsigned int bytes); void writeString(std::string const& str); void writeBuffer(PointerHolder&); @@ -483,10 +483,8 @@ class QPDFWriter void writeTrailer(trailer_e which, int size, bool xref_stream, qpdf_offset_t prev, int linearization_pass); - void unparseObject(QPDFObjectHandle object, int level, - unsigned int flags); - void unparseObject(QPDFObjectHandle object, int level, - unsigned int flags, + void unparseObject(QPDFObjectHandle object, int level, int flags); + void unparseObject(QPDFObjectHandle object, int level, int flags, // for stream dictionaries size_t stream_length, bool compress); void unparseChild(QPDFObjectHandle child, int level, int flags); @@ -510,7 +508,7 @@ class QPDFWriter char const* user_password, char const* owner_password, int V, int R, int key_len, std::set& bits_to_clear); void 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, @@ -554,7 +552,7 @@ class QPDFWriter qpdf_offset_t hint_length, bool skip_compression, int linearization_pass); - int calculateXrefStreamPadding(int xref_bytes); + int calculateXrefStreamPadding(qpdf_offset_t xref_bytes); // When filtering subsections, push additional pipelines to the // stack. When ready to switch, activate the pipeline stack. diff --git a/libqpdf/BitStream.cc b/libqpdf/BitStream.cc index bb52af31a..95ca47c57 100644 --- a/libqpdf/BitStream.cc +++ b/libqpdf/BitStream.cc @@ -1,10 +1,11 @@ #include +#include // 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) { @@ -16,7 +17,7 @@ BitStream::reset() { p = start; bit_offset = 7; - if (static_cast(nbytes) > static_cast(-1) / 8) + if (QIntC::to_uint(nbytes) > static_cast(-1) / 8) { throw std::runtime_error("array too large for bitstream"); } @@ -24,21 +25,21 @@ BitStream::reset() } 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(bits) > 1 << (nbits - 1)) + if (static_cast(bits) > 1LL << (nbits - 1)) { - result = static_cast(bits - (1 << nbits)); + result = static_cast(bits -(1ULL << nbits)); } else { @@ -47,12 +48,21 @@ BitStream::getBitsSigned(int nbits) return result; } +int +BitStream::getBitsInt(size_t nbits) +{ + return static_cast( + 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( diff --git a/libqpdf/BitWriter.cc b/libqpdf/BitWriter.cc index 7513ac762..efe19dedf 100644 --- a/libqpdf/BitWriter.cc +++ b/libqpdf/BitWriter.cc @@ -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((1 << bits) + val); + uval = (1ULL << bits) + static_cast(val); } else { @@ -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(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); } } diff --git a/libqpdf/BufferInputSource.cc b/libqpdf/BufferInputSource.cc index 4346fcd01..1bf61bbd1 100644 --- a/libqpdf/BufferInputSource.cc +++ b/libqpdf/BufferInputSource.cc @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -32,6 +33,12 @@ BufferInputSource::~BufferInputSource() } } +qpdf_offset_t const +BufferInputSource::bufSizeAsOffset() const +{ + return QIntC::to_offset(this->buf->getSize()); +} + qpdf_offset_t BufferInputSource::findAndSkipNextEOL() { @@ -39,7 +46,7 @@ BufferInputSource::findAndSkipNextEOL() { 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; @@ -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(buffer) + this->cur_offset; @@ -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: @@ -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; @@ -139,9 +146,9 @@ BufferInputSource::read(char* buffer, size_t length) this->last_offset = this->cur_offset; size_t len = std::min( - static_cast(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; } diff --git a/libqpdf/FileInputSource.cc b/libqpdf/FileInputSource.cc index 4e4a34bff..d0f3c8ef8 100644 --- a/libqpdf/FileInputSource.cc +++ b/libqpdf/FileInputSource.cc @@ -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) { diff --git a/libqpdf/InputSource.cc b/libqpdf/InputSource.cc index 69cafeb80..ca363566e 100644 --- a/libqpdf/InputSource.cc +++ b/libqpdf/InputSource.cc @@ -3,6 +3,7 @@ #include #include #include +#include void @@ -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'; @@ -116,7 +117,8 @@ InputSource::findFirst(char const* start_chars, // Search for the first character. if ((p = static_cast( - 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) { @@ -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 @@ -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) { diff --git a/libqpdf/InsecureRandomDataProvider.cc b/libqpdf/InsecureRandomDataProvider.cc index 5f637746c..18b21baaf 100644 --- a/libqpdf/InsecureRandomDataProvider.cc +++ b/libqpdf/InsecureRandomDataProvider.cc @@ -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( + QUtil::get_current_time() ^ 0xcccc)); this->seeded_random = true; } diff --git a/libqpdf/JSON.cc b/libqpdf/JSON.cc index df753b692..8565a831f 100644 --- a/libqpdf/JSON.cc +++ b/libqpdf/JSON.cc @@ -197,7 +197,7 @@ JSON::encode_string(std::string const& str) } else { - result.append(1, ch); + result.append(1, static_cast(ch)); } } } diff --git a/libqpdf/MD5.cc b/libqpdf/MD5.cc index 275567dae..6e166a7c3 100644 --- a/libqpdf/MD5.cc +++ b/libqpdf/MD5.cc @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -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; @@ -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; @@ -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; @@ -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(); @@ -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; } @@ -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; } @@ -388,7 +394,7 @@ 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); @@ -396,16 +402,16 @@ MD5::getDataChecksum(char const* buf, int len) } 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); @@ -413,12 +419,12 @@ MD5::checkDataChecksum(char const* const 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&) diff --git a/libqpdf/Pl_AES_PDF.cc b/libqpdf/Pl_AES_PDF.cc index 5c493cb45..c2c921e6a 100644 --- a/libqpdf/Pl_AES_PDF.cc +++ b/libqpdf/Pl_AES_PDF.cc @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -11,7 +12,7 @@ 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), @@ -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); @@ -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); @@ -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(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); @@ -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(14U * (1U + i)); } } else diff --git a/libqpdf/Pl_ASCII85Decoder.cc b/libqpdf/Pl_ASCII85Decoder.cc index 3a3b57b10..b8df3e879 100644 --- a/libqpdf/Pl_ASCII85Decoder.cc +++ b/libqpdf/Pl_ASCII85Decoder.cc @@ -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]; diff --git a/libqpdf/Pl_ASCIIHexDecoder.cc b/libqpdf/Pl_ASCIIHexDecoder.cc index d6acab24f..f20a97697 100644 --- a/libqpdf/Pl_ASCIIHexDecoder.cc +++ b/libqpdf/Pl_ASCIIHexDecoder.cc @@ -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(toupper(buf[i])); switch (ch) { case ' ': diff --git a/libqpdf/Pl_Count.cc b/libqpdf/Pl_Count.cc index c76a5e239..b4b136406 100644 --- a/libqpdf/Pl_Count.cc +++ b/libqpdf/Pl_Count.cc @@ -1,4 +1,5 @@ #include +#include Pl_Count::Pl_Count(char const* identifier, Pipeline* next) : Pipeline(identifier, next), @@ -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]; } diff --git a/libqpdf/Pl_DCT.cc b/libqpdf/Pl_DCT.cc index ceecc5186..4da068cb5 100644 --- a/libqpdf/Pl_DCT.cc +++ b/libqpdf/Pl_DCT.cc @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -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(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; @@ -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(); @@ -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(cinfo), JPOOL_IMAGE, width, 1); diff --git a/libqpdf/Pl_LZWDecoder.cc b/libqpdf/Pl_LZWDecoder.cc index 2cc2077b7..6cc870483 100644 --- a/libqpdf/Pl_LZWDecoder.cc +++ b/libqpdf/Pl_LZWDecoder.cc @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -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) @@ -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) @@ -130,7 +131,7 @@ Pl_LZWDecoder::addToTable(unsigned char next) if (this->last_code < 256) { - tmp[0] = this->last_code; + tmp[0] = static_cast(this->last_code); last_data = tmp; last_size = 1; } @@ -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 { @@ -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) { @@ -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(code); } else if (code > 257) { diff --git a/libqpdf/Pl_PNGFilter.cc b/libqpdf/Pl_PNGFilter.cc index 217a14fa0..a39c17f98 100644 --- a/libqpdf/Pl_PNGFilter.cc +++ b/libqpdf/Pl_PNGFilter.cc @@ -153,7 +153,7 @@ Pl_PNGFilter::decodeSub() left = buffer[i - bpp]; } - buffer[i] += left; + buffer[i] = static_cast(buffer[i] + left); } } @@ -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(buffer[i] + up); } } @@ -190,7 +190,7 @@ Pl_PNGFilter::decodeAverage() } up = above_buffer[i]; - buffer[i] += (left+up) / 2; + buffer[i] = static_cast(buffer[i] + (left+up) / 2); } } @@ -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( + buffer[i] + + this->PaethPredictor(left, up, upper_left)); } } @@ -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( + this->cur_row[i] - this->prev_row[i]); getNext()->write(&ch, 1); } } diff --git a/libqpdf/Pl_RunLength.cc b/libqpdf/Pl_RunLength.cc index 1e8c56ca3..3e3abd981 100644 --- a/libqpdf/Pl_RunLength.cc +++ b/libqpdf/Pl_RunLength.cc @@ -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 diff --git a/libqpdf/QPDF.cc b/libqpdf/QPDF.cc index 48015d4ba..55f220d8f 100644 --- a/libqpdf/QPDF.cc +++ b/libqpdf/QPDF.cc @@ -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 @@ -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()) { @@ -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; @@ -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(); @@ -1006,7 +1006,7 @@ 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(), @@ -1014,7 +1014,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) "Cross-reference stream's /W contains" " impossibly large values"); } - entry_size += W[i]; + entry_size += toS(W[i]); } if (entry_size == 0) { @@ -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(-1) / entry_size; std::vector indx; @@ -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 @@ -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; @@ -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; @@ -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); @@ -1129,7 +1129,7 @@ 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(*p++); + fields[j] += toI(*p++); } } @@ -1137,7 +1137,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) // 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)) { @@ -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(fields[0]), - fields[1], static_cast(fields[2])); + insertXrefEntry(obj, toI(fields[0]), + fields[1], toI(fields[2])); } if (! this->m->trailer.isInitialized()) @@ -1395,7 +1395,7 @@ QPDF::getObjectCount() { og = (*(this->m->obj_cache.rbegin())).first; } - return og.getObj(); + return toS(og.getObj()); } std::vector @@ -1570,8 +1570,8 @@ QPDF::readObject(PointerHolder 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"))) @@ -1641,7 +1641,7 @@ QPDF::recoverStreamLength(PointerHolder 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") @@ -1652,7 +1652,7 @@ QPDF::recoverStreamLength(PointerHolder 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 @@ -1700,7 +1700,7 @@ QPDF::recoverStreamLength(PointerHolder 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"); @@ -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 offsets; @@ -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; } @@ -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); @@ -2509,7 +2509,7 @@ QPDF::getExtensionLevel() obj = obj.getKey("/ExtensionLevel"); if (obj.isInteger()) { - result = obj.getIntValue(); + result = obj.getIntValueAsInt(); } } } @@ -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, @@ -2746,7 +2747,7 @@ bool QPDF::pipeForeignStreamData( PointerHolder foreign, Pipeline* pipeline, - unsigned long encode_flags, + int encode_flags, qpdf_stream_decode_level_e decode_level) { if (foreign->encp->encrypted) diff --git a/libqpdf/QPDFAcroFormDocumentHelper.cc b/libqpdf/QPDFAcroFormDocumentHelper.cc index a55f71603..ea12f6564 100644 --- a/libqpdf/QPDFAcroFormDocumentHelper.cc +++ b/libqpdf/QPDFAcroFormDocumentHelper.cc @@ -114,9 +114,9 @@ QPDFAcroFormDocumentHelper::analyze() // bidirectionally to fields. std::set 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); } @@ -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); } diff --git a/libqpdf/QPDFAnnotationObjectHelper.cc b/libqpdf/QPDFAnnotationObjectHelper.cc index 698f80e1e..a51471392 100644 --- a/libqpdf/QPDFAnnotationObjectHelper.cc +++ b/libqpdf/QPDFAnnotationObjectHelper.cc @@ -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 diff --git a/libqpdf/QPDFFormFieldObjectHelper.cc b/libqpdf/QPDFFormFieldObjectHelper.cc index 08042df20..b3c61ce5d 100644 --- a/libqpdf/QPDFFormFieldObjectHelper.cc +++ b/libqpdf/QPDFFormFieldObjectHelper.cc @@ -4,6 +4,7 @@ #include #include #include +#include #include QPDFFormFieldObjectHelper::Members::~Members() @@ -189,7 +190,7 @@ QPDFFormFieldObjectHelper::getQuadding() if (fv.isInteger()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper Q present"); - result = static_cast(fv.getIntValue()); + result = QIntC::to_int(fv.getIntValue()); } return result; } @@ -198,7 +199,7 @@ int QPDFFormFieldObjectHelper::getFlags() { QPDFObjectHandle f = getInheritableFieldValue("/Ff"); - return f.isInteger() ? f.getIntValue() : 0; + return f.isInteger() ? f.getIntValueAsInt() : 0; } bool @@ -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()) @@ -631,8 +632,8 @@ 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) { @@ -640,7 +641,7 @@ ValueSetter::writeAppearance() ++wanted_first; ++wanted_last; } - while (wanted_last >= static_cast(nopt)) + while (wanted_last >= QIntC::to_int(nopt)) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper list last too high"); if (wanted_first > 0) @@ -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)); } @@ -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(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(highlight_idx + 1)))) + " " + QUtil::double_to_string(bbox.urx - bbox.llx) + " " + QUtil::double_to_string(tfh) + " re f\nQ\n"); @@ -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(dx)) + + " " + + QUtil::double_to_string(bbox.lly + static_cast(dy)) + + " Td\n"); } else { diff --git a/libqpdf/QPDFNameTreeObjectHelper.cc b/libqpdf/QPDFNameTreeObjectHelper.cc index 4eb0fb152..a7f0a00d9 100644 --- a/libqpdf/QPDFNameTreeObjectHelper.cc +++ b/libqpdf/QPDFNameTreeObjectHelper.cc @@ -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); @@ -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)); } diff --git a/libqpdf/QPDFNumberTreeObjectHelper.cc b/libqpdf/QPDFNumberTreeObjectHelper.cc index 40b1c6f9d..15930fcd6 100644 --- a/libqpdf/QPDFNumberTreeObjectHelper.cc +++ b/libqpdf/QPDFNumberTreeObjectHelper.cc @@ -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); @@ -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)); } diff --git a/libqpdf/QPDFObjectHandle.cc b/libqpdf/QPDFObjectHandle.cc index d182f9bfa..9ccfa37a8 100644 --- a/libqpdf/QPDFObjectHandle.cc +++ b/libqpdf/QPDFObjectHandle.cc @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -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()) { @@ -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()) { @@ -1013,7 +1014,7 @@ QPDFObjectHandle::getUniqueResourceName(std::string const& prefix, int& min_suffix) { std::set 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); @@ -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()) { @@ -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))) @@ -1618,7 +1619,7 @@ QPDFObjectHandle::parseContentStream_data( QPDFTokenizer tokenizer; tokenizer.allowEOF(); bool empty = false; - while (static_cast(input->tell()) < length) + while (QIntC::to_size(input->tell()) < length) { QPDFObjectHandle obj = parseInternal(input, "content", tokenizer, empty, 0, 0, true); @@ -1863,8 +1864,8 @@ QPDFObjectHandle::parseInternal(PointerHolder 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(); } diff --git a/libqpdf/QPDFOutlineObjectHelper.cc b/libqpdf/QPDFOutlineObjectHelper.cc index e8eb11d0a..6cdd182ee 100644 --- a/libqpdf/QPDFOutlineObjectHelper.cc +++ b/libqpdf/QPDFOutlineObjectHelper.cc @@ -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; } diff --git a/libqpdf/QPDFPageDocumentHelper.cc b/libqpdf/QPDFPageDocumentHelper.cc index 58d6ed228..048319f59 100644 --- a/libqpdf/QPDFPageDocumentHelper.cc +++ b/libqpdf/QPDFPageDocumentHelper.cc @@ -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::iterator iter = diff --git a/libqpdf/QPDFPageObjectHelper.cc b/libqpdf/QPDFPageObjectHelper.cc index 9543d294d..8ecd01445 100644 --- a/libqpdf/QPDFPageObjectHelper.cc +++ b/libqpdf/QPDFPageObjectHelper.cc @@ -6,6 +6,7 @@ #include #include #include +#include class ContentProvider: public QPDFObjectHandle::StreamDataProvider { @@ -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( @@ -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() || @@ -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) { diff --git a/libqpdf/QPDFTokenizer.cc b/libqpdf/QPDFTokenizer.cc index ff5ebe152..3c40ed00c 100644 --- a/libqpdf/QPDFTokenizer.cc +++ b/libqpdf/QPDFTokenizer.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -715,7 +716,7 @@ QPDFTokenizer::findEI(PointerHolder 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; diff --git a/libqpdf/QPDFWriter.cc b/libqpdf/QPDFWriter.cc index 22928372d..23a67d7c0 100644 --- a/libqpdf/QPDFWriter.cc +++ b/libqpdf/QPDFWriter.cc @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -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()) @@ -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, @@ -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, @@ -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; @@ -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); } @@ -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( @@ -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) @@ -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 { @@ -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 || @@ -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; @@ -1883,14 +1884,14 @@ void QPDFWriter::writeObjectStreamOffsets(std::vector& 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))); } @@ -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()) @@ -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); } } @@ -2308,12 +2309,12 @@ QPDFWriter::generateObjectStreams() std::vector 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; @@ -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( + QIntC::to_int( this->m->object_stream_to_objects[stream].size()) - 1); } @@ -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(); @@ -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) @@ -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') @@ -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; @@ -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: @@ -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 "); @@ -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 @@ -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 @@ -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; @@ -3093,7 +3095,7 @@ 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) { @@ -3101,7 +3103,7 @@ QPDFWriter::writeLinearized() } 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* vecs1[] = {&part4, &part6}; @@ -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)); @@ -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"); @@ -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) { @@ -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 @@ -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); diff --git a/libqpdf/QPDFXRefEntry.cc b/libqpdf/QPDFXRefEntry.cc index 2e458ada7..a0cad43eb 100644 --- a/libqpdf/QPDFXRefEntry.cc +++ b/libqpdf/QPDFXRefEntry.cc @@ -1,6 +1,7 @@ #include #include #include +#include QPDFXRefEntry::QPDFXRefEntry() : type(0), @@ -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 diff --git a/libqpdf/QPDF_Array.cc b/libqpdf/QPDF_Array.cc index 15c2e93e1..c22143a15 100644 --- a/libqpdf/QPDF_Array.cc +++ b/libqpdf/QPDF_Array.cc @@ -1,5 +1,6 @@ #include #include +#include #include QPDF_Array::QPDF_Array(std::vector const& items) : @@ -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(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 const& @@ -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 @@ -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(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"); diff --git a/libqpdf/QPDF_Stream.cc b/libqpdf/QPDF_Stream.cc index 8b904e1f9..4f20c6042 100644 --- a/libqpdf/QPDF_Stream.cc +++ b/libqpdf/QPDF_Stream.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include @@ -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)))) { @@ -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))) { @@ -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; @@ -550,7 +551,9 @@ 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) @@ -558,7 +561,9 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, 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); } } @@ -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))); } } @@ -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 { diff --git a/libqpdf/QPDF_String.cc b/libqpdf/QPDF_String.cc index bf1141d15..5558979cb 100644 --- a/libqpdf/QPDF_String.cc +++ b/libqpdf/QPDF_String.cc @@ -9,13 +9,14 @@ #include // 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(ch) >= 160)); } QPDF_String::QPDF_String(std::string const& val) : diff --git a/libqpdf/QPDF_encryption.cc b/libqpdf/QPDF_encryption.cc index c0778b6ac..c02f1aac4 100644 --- a/libqpdf/QPDF_encryption.cc +++ b/libqpdf/QPDF_encryption.cc @@ -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(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); } @@ -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 @@ -183,7 +184,8 @@ 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); @@ -191,26 +193,26 @@ iterate_md5_digest(MD5& md5, MD5::Digest& digest, int iterations, int key_len) { MD5 m; m.encodeDataIncrementally(reinterpret_cast(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(okey[j] ^ xor_value); } - RC4 rc4(key, key_len); + RC4 rc4(key, QIntC::to_int(key_len)); rc4.process(data, data_len); } delete [] key; @@ -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); @@ -328,7 +330,7 @@ hash_V5(std::string const& password, { unsigned int ch = static_cast(*(E.rbegin())); - if (ch <= static_cast(round_number - 32)) + if (ch <= QIntC::to_uint(round_number - 32)) { done = true; } @@ -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) { @@ -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(objid & 0xff); - result += static_cast((objid >> 8) & 0xff); - result += static_cast((objid >> 16) & 0xff); - result += static_cast(generation & 0xff); - result += static_cast((generation >> 8) & 0xff); + result.append(1, static_cast(objid & 0xff)); + result.append(1, static_cast((objid >> 8) & 0xff)); + result.append(1, static_cast((objid >> 16) & 0xff)); + result.append(1, static_cast(generation & 0xff)); + result.append(1, static_cast((generation >> 8) & 0xff)); if (use_aes) { result += "sAlT"; @@ -382,7 +384,7 @@ QPDF::compute_data_key(std::string const& encryption_key, MD5::Digest digest; md5.digest(digest); return std::string(reinterpret_cast(digest), - std::min(result.length(), static_cast(16))); + std::min(result.length(), toS(16))); } std::string @@ -437,10 +439,9 @@ QPDF::compute_encryption_key_from_password( md5.encodeDataIncrementally(bytes, 4); } MD5::Digest digest; - int key_len = std::min(static_cast(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(digest), key_len); + return std::string(reinterpret_cast(digest), QIntC::to_size(key_len)); } static void @@ -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(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); @@ -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(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); @@ -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); @@ -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); @@ -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); } @@ -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(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); @@ -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(data.getP()); for (int i = 0; i < 8; ++i) { k[i] = static_cast(extended_perms & 0xff); @@ -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. @@ -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. @@ -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) { @@ -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 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); } @@ -1313,7 +1316,7 @@ QPDF::decryptStream(PointerHolder 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); } @@ -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; diff --git a/libqpdf/QPDF_linearization.cc b/libqpdf/QPDF_linearization.cc index 5de1e8f6d..04b646d36 100644 --- a/libqpdf/QPDF_linearization.cc +++ b/libqpdf/QPDF_linearization.cc @@ -26,15 +26,15 @@ load_vector_int(BitStream& bit_stream, int nitems, std::vector& vec, // nitems times, read bits_wanted from the given bit stream, // storing results in the ith vector entry. - for (int i = 0; i < nitems; ++i) + for (size_t i = 0; i < QIntC::to_size(nitems); ++i) { if (append) { vec.push_back(T()); } - vec.at(i).*field = bit_stream.getBits(bits_wanted); + vec.at(i).*field = bit_stream.getBitsInt(QIntC::to_size(bits_wanted)); } - if (static_cast(vec.size()) != nitems) + if (QIntC::to_int(vec.size()) != nitems) { throw std::logic_error("vector has wrong size in load_vector_int"); } @@ -51,11 +51,12 @@ load_vector_vector(BitStream& bit_stream, { // nitems1 times, read nitems2 (from the ith element of vec1) items // into the vec2 vector field of the ith item of vec1. - for (int i1 = 0; i1 < nitems1; ++i1) + for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) { for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) { - (vec1.at(i1).*vec2).push_back(bit_stream.getBits(bits_wanted)); + (vec1.at(i1).*vec2).push_back( + bit_stream.getBitsInt(QIntC::to_size(bits_wanted))); } } bit_stream.skipToNextByte(); @@ -131,7 +132,7 @@ QPDF::isLinearized() (t4.getType() == QPDFTokenizer::tt_dict_open)) { lindict_obj = - static_cast(QUtil::string_to_ll(t1.getValue().c_str())); + QIntC::to_int(QUtil::string_to_ll(t1.getValue().c_str())); } } @@ -149,7 +150,7 @@ QPDF::isLinearized() QPDFObjectHandle linkey = candidate.getKey("/Linearized"); if (! (linkey.isNumber() && - (static_cast(floor(linkey.getNumericValue())) == 1))) + (QIntC::to_int(floor(linkey.getNumericValue())) == 1))) { return false; } @@ -213,7 +214,7 @@ QPDF::readLinearizationData() } // Hint table array: offset length [ offset length ] - unsigned int n_H_items = H.getArrayNItems(); + size_t n_H_items = toS(H.getArrayNItems()); if (! ((n_H_items == 2) || (n_H_items == 4))) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), @@ -223,12 +224,12 @@ QPDF::readLinearizationData() } std::vector H_items; - for (unsigned int i = 0; i < n_H_items; ++i) + for (size_t i = 0; i < n_H_items; ++i) { - QPDFObjectHandle oh(H.getArrayItem(i)); + QPDFObjectHandle oh(H.getArrayItem(toI(i))); if (oh.isInteger()) { - H_items.push_back(oh.getIntValue()); + H_items.push_back(oh.getIntValueAsInt()); } else { @@ -258,7 +259,7 @@ QPDF::readLinearizationData() if (P.isInteger()) { QTC::TC("qpdf", "QPDF P present in lindict"); - first_page = P.getIntValue(); + first_page = P.getIntValueAsInt(); } else { @@ -279,9 +280,9 @@ QPDF::readLinearizationData() } // file_size initialized by isLinearized() - this->m->linp.first_page_object = O.getIntValue(); + this->m->linp.first_page_object = O.getIntValueAsInt(); this->m->linp.first_page_end = E.getIntValue(); - this->m->linp.npages = N.getIntValue(); + this->m->linp.npages = N.getIntValueAsInt(); this->m->linp.xref_zero_offset = T.getIntValue(); this->m->linp.first_page = first_page; this->m->linp.H_offset = H0_offset; @@ -290,10 +291,10 @@ QPDF::readLinearizationData() // Read hint streams Pl_Buffer pb("hint buffer"); - QPDFObjectHandle H0 = readHintStream(pb, H0_offset, H0_length); + QPDFObjectHandle H0 = readHintStream(pb, H0_offset, toS(H0_length)); if (H1_offset) { - (void) readHintStream(pb, H1_offset, H1_length); + (void) readHintStream(pb, H1_offset, toS(H1_length)); } // PDF 1.4 hint tables that we ignore: @@ -313,31 +314,31 @@ QPDF::readLinearizationData() PointerHolder hbp = pb.getBuffer(); Buffer* hb = hbp.getPointer(); unsigned char const* h_buf = hb->getBuffer(); - int h_size = hb->getSize(); + size_t h_size = hb->getSize(); readHPageOffset(BitStream(h_buf, h_size)); - int HSi = HS.getIntValue(); - if ((HSi < 0) || (HSi >= h_size)) + int HSi = HS.getIntValueAsInt(); + if ((HSi < 0) || (toS(HSi) >= h_size)) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "linearization hint table", this->m->file->getLastOffset(), "/S (shared object) offset is out of bounds"); } - readHSharedObject(BitStream(h_buf + HSi, h_size - HSi)); + readHSharedObject(BitStream(h_buf + HSi, h_size - toS(HSi))); if (HO.isInteger()) { - int HOi = HO.getIntValue(); - if ((HOi < 0) || (HOi >= h_size)) + int HOi = HO.getIntValueAsInt(); + if ((HOi < 0) || (toS(HOi) >= h_size)) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "linearization hint table", this->m->file->getLastOffset(), "/O (outline) offset is out of bounds"); } - readHGeneric(BitStream(h_buf + HOi, h_size - HOi), + readHGeneric(BitStream(h_buf + HOi, h_size - toS(HOi)), this->m->outline_hints); } } @@ -381,7 +382,7 @@ QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length) { QTC::TC("qpdf", "QPDF hint table length direct"); } - qpdf_offset_t computed_end = offset + length; + qpdf_offset_t computed_end = offset + toO(length); if ((computed_end < min_end_offset) || (computed_end > max_end_offset)) { @@ -405,23 +406,23 @@ QPDF::readHPageOffset(BitStream h) HPageOffset& t = this->m->page_offset_hints; - t.min_nobjects = h.getBits(32); // 1 - t.first_page_offset = h.getBits(32); // 2 - t.nbits_delta_nobjects = h.getBits(16); // 3 - t.min_page_length = h.getBits(32); // 4 - t.nbits_delta_page_length = h.getBits(16); // 5 - t.min_content_offset = h.getBits(32); // 6 - t.nbits_delta_content_offset = h.getBits(16); // 7 - t.min_content_length = h.getBits(32); // 8 - t.nbits_delta_content_length = h.getBits(16); // 9 - t.nbits_nshared_objects = h.getBits(16); // 10 - t.nbits_shared_identifier = h.getBits(16); // 11 - t.nbits_shared_numerator = h.getBits(16); // 12 - t.shared_denominator = h.getBits(16); // 13 + t.min_nobjects = h.getBitsInt(32); // 1 + t.first_page_offset = h.getBitsInt(32); // 2 + t.nbits_delta_nobjects = h.getBitsInt(16); // 3 + t.min_page_length = h.getBitsInt(32); // 4 + t.nbits_delta_page_length = h.getBitsInt(16); // 5 + t.min_content_offset = h.getBitsInt(32); // 6 + t.nbits_delta_content_offset = h.getBitsInt(16); // 7 + t.min_content_length = h.getBitsInt(32); // 8 + t.nbits_delta_content_length = h.getBitsInt(16); // 9 + t.nbits_nshared_objects = h.getBitsInt(16); // 10 + t.nbits_shared_identifier = h.getBitsInt(16); // 11 + t.nbits_shared_numerator = h.getBitsInt(16); // 12 + t.shared_denominator = h.getBitsInt(16); // 13 std::vector& entries = t.entries; entries.clear(); - unsigned int nitems = this->m->linp.npages; + int nitems = this->m->linp.npages; load_vector_int(h, nitems, entries, t.nbits_delta_nobjects, &HPageOffsetEntry::delta_nobjects); @@ -452,13 +453,13 @@ QPDF::readHSharedObject(BitStream h) { HSharedObject& t = this->m->shared_object_hints; - t.first_shared_obj = h.getBits(32); // 1 - t.first_shared_offset = h.getBits(32); // 2 - t.nshared_first_page = h.getBits(32); // 3 - t.nshared_total = h.getBits(32); // 4 - t.nbits_nobjects = h.getBits(16); // 5 - t.min_group_length = h.getBits(32); // 6 - t.nbits_delta_group_length = h.getBits(16); // 7 + t.first_shared_obj = h.getBitsInt(32); // 1 + t.first_shared_offset = h.getBitsInt(32); // 2 + t.nshared_first_page = h.getBitsInt(32); // 3 + t.nshared_total = h.getBitsInt(32); // 4 + t.nbits_nobjects = h.getBitsInt(16); // 5 + t.min_group_length = h.getBitsInt(32); // 6 + t.nbits_delta_group_length = h.getBitsInt(16); // 7 QTC::TC("qpdf", "QPDF lin nshared_total > nshared_first_page", (t.nshared_total > t.nshared_first_page) ? 1 : 0); @@ -471,7 +472,7 @@ QPDF::readHSharedObject(BitStream h) &HSharedObjectEntry::delta_group_length); load_vector_int(h, nitems, entries, 1, &HSharedObjectEntry::signature_present); - for (int i = 0; i < nitems; ++i) + for (size_t i = 0; i < toS(nitems); ++i) { if (entries.at(i).signature_present) { @@ -492,10 +493,10 @@ QPDF::readHSharedObject(BitStream h) void QPDF::readHGeneric(BitStream h, HGeneric& t) { - t.first_object = h.getBits(32); // 1 - t.first_object_offset = h.getBits(32); // 2 - t.nobjects = h.getBits(32); // 3 - t.group_length = h.getBits(32); // 4 + t.first_object = h.getBitsInt(32); // 1 + t.first_object_offset = h.getBitsInt(32); // 2 + t.nobjects = h.getBitsInt(32); // 3 + t.group_length = h.getBitsInt(32); // 4 } bool @@ -522,21 +523,21 @@ QPDF::checkLinearizationInternal() } // N: number of pages - int npages = pages.size(); + int npages = toI(pages.size()); if (p.npages != npages) { // Not tested in the test suite errors.push_back("page count (/N) mismatch"); } - for (int i = 0; i < npages; ++i) + for (size_t i = 0; i < toS(npages); ++i) { QPDFObjectHandle const& page = pages.at(i); QPDFObjGen og(page.getObjGen()); if (this->m->xref_table[og].getType() == 2) { errors.push_back("page dictionary for page " + - QUtil::int_to_string(i) + " is compressed"); + QUtil::uint_to_string(i) + " is compressed"); } } @@ -756,8 +757,8 @@ QPDF::lengthNextN(int first_object, int n, stopOnError("found unknown object while" " calculating length for linearization data"); } - length += this->m->obj_cache[og].end_after_space - - getLinearizationOffset(og); + length += toI(this->m->obj_cache[og].end_after_space - + getLinearizationOffset(og)); } } return length; @@ -786,8 +787,8 @@ QPDF::checkHPageOffset(std::list& errors, // under a page's /Resources dictionary in with shared objects // even when they are private. - unsigned int npages = pages.size(); - int table_offset = adjusted_offset( + int npages = toI(pages.size()); + qpdf_offset_t table_offset = adjusted_offset( this->m->page_offset_hints.first_page_offset); QPDFObjGen first_page_og(pages.at(0).getObjGen()); if (this->m->xref_table.count(first_page_og) == 0) @@ -800,9 +801,9 @@ QPDF::checkHPageOffset(std::list& errors, warnings.push_back("first page object offset mismatch"); } - for (unsigned int pageno = 0; pageno < npages; ++pageno) + for (int pageno = 0; pageno < npages; ++pageno) { - QPDFObjGen page_og(pages.at(pageno).getObjGen()); + QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen()); int first_object = page_og.getObj(); if (this->m->xref_table.count(page_og) == 0) { @@ -810,8 +811,10 @@ QPDF::checkHPageOffset(std::list& errors, } offset = getLinearizationOffset(page_og); - HPageOffsetEntry& he = this->m->page_offset_hints.entries.at(pageno); - CHPageOffsetEntry& ce = this->m->c_page_offset_data.entries.at(pageno); + HPageOffsetEntry& he = + this->m->page_offset_hints.entries.at(toS(pageno)); + CHPageOffsetEntry& ce = + this->m->c_page_offset_data.entries.at(toS(pageno)); int h_nobjects = he.delta_nobjects + this->m->page_offset_hints.min_nobjects; if (h_nobjects != ce.nobjects) @@ -827,8 +830,8 @@ QPDF::checkHPageOffset(std::list& errors, // Use value for number of objects in hint table rather than // computed value if there is a discrepancy. int length = lengthNextN(first_object, h_nobjects, errors); - int h_length = he.delta_page_length + - this->m->page_offset_hints.min_page_length; + int h_length = toI(he.delta_page_length + + this->m->page_offset_hints.min_page_length); if (length != h_length) { // This condition almost certainly indicates a bad hint @@ -854,7 +857,7 @@ QPDF::checkHPageOffset(std::list& errors, warnings.push_back("page 0 has shared identifier entries"); } - for (int i = 0; i < he.nshared_objects; ++i) + for (size_t i = 0; i < toS(he.nshared_objects); ++i) { int idx = he.shared_identifiers.at(i); if (shared_idx_to_obj.count(idx) == 0) @@ -866,7 +869,7 @@ QPDF::checkHPageOffset(std::list& errors, hint_shared.insert(shared_idx_to_obj[idx]); } - for (int i = 0; i < ce.nshared_objects; ++i) + for (size_t i = 0; i < toS(ce.nshared_objects); ++i) { int idx = ce.shared_identifiers.at(i); if (idx >= this->m->c_shared_object_data.nshared_total) @@ -874,7 +877,7 @@ QPDF::checkHPageOffset(std::list& errors, throw std::logic_error( "index out of bounds for shared object hint table"); } - int obj = this->m->c_shared_object_data.entries.at(idx).object; + int obj = this->m->c_shared_object_data.entries.at(toS(idx)).object; computed_shared.insert(obj); } @@ -975,8 +978,9 @@ QPDF::checkHSharedObject(std::list& errors, { stopOnError("unknown object in shared object hint table"); } - int offset = getLinearizationOffset(og); - int h_offset = adjusted_offset(so.first_shared_offset); + qpdf_offset_t offset = getLinearizationOffset(og); + qpdf_offset_t h_offset = + adjusted_offset(so.first_shared_offset); if (offset != h_offset) { errors.push_back( @@ -987,7 +991,7 @@ QPDF::checkHSharedObject(std::list& errors, } idx_to_obj[i] = cur_object; - HSharedObjectEntry& se = so.entries.at(i); + HSharedObjectEntry& se = so.entries.at(toS(i)); int nobjects = se.nobjects_minus_one + 1; int length = lengthNextN(cur_object, nobjects, errors); int h_length = so.min_group_length + se.delta_group_length; @@ -1041,10 +1045,10 @@ QPDF::checkHOutlines(std::list& warnings) { stopOnError("unknown object in outlines hint table"); } - int offset = getLinearizationOffset(og); + qpdf_offset_t offset = getLinearizationOffset(og); ObjUser ou(ObjUser::ou_root_key, "/Outlines"); - int length = maxEnd(ou) - offset; - int table_offset = + int length = toI(maxEnd(ou) - offset); + qpdf_offset_t table_offset = adjusted_offset(this->m->outline_hints.first_object_offset); if (offset != table_offset) { @@ -1124,8 +1128,8 @@ QPDF::dumpLinearizationDataInternal() } } -int -QPDF::adjusted_offset(int offset) +qpdf_offset_t +QPDF::adjusted_offset(qpdf_offset_t offset) { // All offsets >= H_offset have to be increased by H_length // since all hint table location values disregard the hint table @@ -1170,7 +1174,7 @@ QPDF::dumpHPageOffset() << "shared_denominator: " << t.shared_denominator << std::endl; - for (int i1 = 0; i1 < this->m->linp.npages; ++i1) + for (size_t i1 = 0; i1 < toS(this->m->linp.npages); ++i1) { HPageOffsetEntry& pe = t.entries.at(i1); *this->m->out_stream @@ -1185,7 +1189,7 @@ QPDF::dumpHPageOffset() << " content_length: " << pe.delta_content_length + t.min_content_length << std::endl << " nshared_objects: " << pe.nshared_objects << std::endl; - for (int i2 = 0; i2 < pe.nshared_objects; ++i2) + for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2) { *this->m->out_stream << " identifier " << i2 << ": " << pe.shared_identifiers.at(i2) << std::endl; @@ -1215,7 +1219,7 @@ QPDF::dumpHSharedObject() << "nbits_delta_group_length: " << t.nbits_delta_group_length << std::endl; - for (int i = 0; i < t.nshared_total; ++i) + for (size_t i = 0; i < toS(t.nshared_total); ++i) { HSharedObjectEntry& se = t.entries.at(i); *this->m->out_stream @@ -1516,7 +1520,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) pages.push_back(getUncompressedObject(*iter, object_stream_data)); } } - unsigned int npages = pages.size(); + int npages = toI(pages.size()); // We will be initializing some values of the computed hint // tables. Specifically, we can initialize any items that deal @@ -1531,7 +1535,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // reasonable size. this->m->c_linp.npages = npages; this->m->c_page_offset_data.entries = - std::vector(npages); + std::vector(toS(npages)); // Part 4: open document objects. We don't care about the order. @@ -1594,12 +1598,13 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // in garbage values for all the shared object identifiers on the // first page. - this->m->c_page_offset_data.entries.at(0).nobjects = this->m->part6.size(); + this->m->c_page_offset_data.entries.at(0).nobjects = + toI(this->m->part6.size()); // Part 7: other pages' private objects // For each page in order: - for (unsigned int i = 1; i < npages; ++i) + for (size_t i = 1; i < toS(npages); ++i) { // Place this page's page object @@ -1609,7 +1614,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) throw std::logic_error( "INTERNAL ERROR: " "QPDF::calculateLinearizationData: page object for page " + - QUtil::int_to_string(i) + " not in lc_other_page_private"); + QUtil::uint_to_string(i) + " not in lc_other_page_private"); } lc_other_page_private.erase(page_og); this->m->part7.push_back(pages.at(i)); @@ -1619,7 +1624,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) this->m->c_page_offset_data.entries.at(i).nobjects = 1; - ObjUser ou(ObjUser::ou_page, i); + ObjUser ou(ObjUser::ou_page, toI(i)); if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" @@ -1687,7 +1692,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Place private thumbnail images in page order. Slightly more // information would be required if we were going to bother with // thumbnail hint tables. - for (unsigned int i = 0; i < npages; ++i) + for (size_t i = 0; i < toS(npages); ++i) { QPDFObjectHandle thumb = pages.at(i).getKey("/Thumb"); thumb = getUncompressedObject(thumb, object_stream_data); @@ -1710,7 +1715,8 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // lc_thumbnail_private. } std::set& ogs = - this->m->obj_user_to_objects[ObjUser(ObjUser::ou_thumb, i)]; + this->m->obj_user_to_objects[ + ObjUser(ObjUser::ou_thumb, toI(i))]; for (std::set::iterator iter = ogs.begin(); iter != ogs.end(); ++iter) { @@ -1753,18 +1759,18 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Make sure we got everything exactly once. - unsigned int num_placed = + size_t num_placed = this->m->part4.size() + this->m->part6.size() + this->m->part7.size() + this->m->part8.size() + this->m->part9.size(); - unsigned int num_wanted = this->m->object_to_obj_users.size(); + size_t num_wanted = this->m->object_to_obj_users.size(); if (num_placed != num_wanted) { throw std::logic_error( "INTERNAL ERROR: QPDF::calculateLinearizationData: wrong " "number of objects placed (num_placed = " + - QUtil::int_to_string(num_placed) + + QUtil::uint_to_string(num_placed) + "; number of objects: " + - QUtil::int_to_string(num_wanted)); + QUtil::uint_to_string(num_wanted)); } // Calculate shared object hint table information including @@ -1780,10 +1786,11 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // can map from object number only without regards to generation. std::map obj_to_index; - this->m->c_shared_object_data.nshared_first_page = this->m->part6.size(); + this->m->c_shared_object_data.nshared_first_page = + toI(this->m->part6.size()); this->m->c_shared_object_data.nshared_total = this->m->c_shared_object_data.nshared_first_page + - this->m->part8.size(); + toI(this->m->part8.size()); std::vector& shared = this->m->c_shared_object_data.entries; @@ -1792,7 +1799,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) { QPDFObjectHandle& oh = *iter; int obj = oh.getObjectID(); - obj_to_index[obj] = shared.size(); + obj_to_index[obj] = toI(shared.size()); shared.push_back(CHSharedObjectEntry(obj)); } QTC::TC("qpdf", "QPDF lin part 8 empty", this->m->part8.empty() ? 1 : 0); @@ -1806,7 +1813,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) { QPDFObjectHandle& oh = *iter; int obj = oh.getObjectID(); - obj_to_index[obj] = shared.size(); + obj_to_index[obj] = toI(shared.size()); shared.push_back(CHSharedObjectEntry(obj)); } } @@ -1820,10 +1827,10 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Now compute the list of shared objects for each page after the // first page. - for (unsigned int i = 1; i < npages; ++i) + for (size_t i = 1; i < toS(npages); ++i) { CHPageOffsetEntry& pe = this->m->c_page_offset_data.entries.at(i); - ObjUser ou(ObjUser::ou_page, i); + ObjUser ou(ObjUser::ou_page, toI(i)); if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" @@ -1921,7 +1928,7 @@ QPDF::outputLengthNextN( stopOnError("found item with unknown length" " while writing linearization data"); } - length += (*(lengths.find(first + i))).second; + length += toI((*(lengths.find(first + toI(i)))).second); } return length; } @@ -1938,7 +1945,7 @@ QPDF::calculateHPageOffset( // values. std::vector const& pages = getAllPages(); - unsigned int npages = pages.size(); + size_t npages = pages.size(); CHPageOffset& cph = this->m->c_page_offset_data; std::vector& cphe = cph.entries; @@ -2001,7 +2008,7 @@ QPDF::calculateHPageOffset( ph.nbits_delta_content_length = ph.nbits_delta_page_length; ph.min_content_length = ph.min_page_length; - for (unsigned int i = 0; i < npages; ++i) + for (size_t i = 0; i < npages; ++i) { // Adjust delta entries if ((phe.at(i).delta_nobjects < min_nobjects) || @@ -2014,7 +2021,7 @@ QPDF::calculateHPageOffset( phe.at(i).delta_page_length -= min_length; phe.at(i).delta_content_length = phe.at(i).delta_page_length; - for (int j = 0; j < cphe.at(i).nshared_objects; ++j) + for (size_t j = 0; j < toS(cphe.at(i).nshared_objects); ++j) { phe.at(i).shared_identifiers.push_back( cphe.at(i).shared_identifiers.at(j)); @@ -2039,7 +2046,7 @@ QPDF::calculateHSharedObject( csoe.at(0).object, 1, lengths, obj_renumber); int max_length = min_length; - for (int i = 0; i < cso.nshared_total; ++i) + for (size_t i = 0; i < toS(cso.nshared_total); ++i) { // Assign absolute numbers to deltas; adjust later int length = outputLengthNextN( @@ -2066,7 +2073,7 @@ QPDF::calculateHSharedObject( so.min_group_length = min_length; so.nbits_delta_group_length = nbits(max_length - min_length); - for (int i = 0; i < cso.nshared_total; ++i) + for (size_t i = 0; i < toS(cso.nshared_total); ++i) { // Adjust deltas if (soe.at(i).delta_group_length < min_length) @@ -2110,9 +2117,10 @@ write_vector_int(BitWriter& w, int nitems, std::vector& vec, // nitems times, write bits bits from the given field of the ith // vector to the given bit writer. - for (int i = 0; i < nitems; ++i) + for (size_t i = 0; i < QIntC::to_size(nitems); ++i) { - w.writeBits(vec.at(i).*field, bits); + w.writeBits(QIntC::to_ulonglong(vec.at(i).*field), + QIntC::to_size(bits)); } // The PDF spec says that each hint table starts at a byte // boundary. Each "row" actually must start on a byte boundary. @@ -2127,11 +2135,12 @@ write_vector_vector(BitWriter& w, { // nitems1 times, write nitems2 (from the ith element of vec1) items // from the vec2 vector field of the ith item of vec1. - for (int i1 = 0; i1 < nitems1; ++i1) + for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) { - for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) + for (size_t i2 = 0; i2 < QIntC::to_size(vec1.at(i1).*nitems2); ++i2) { - w.writeBits((vec1.at(i1).*vec2).at(i2), bits); + w.writeBits(QIntC::to_ulonglong((vec1.at(i1).*vec2).at(i2)), + QIntC::to_size(bits)); } } w.flush(); @@ -2143,21 +2152,21 @@ QPDF::writeHPageOffset(BitWriter& w) { HPageOffset& t = this->m->page_offset_hints; - w.writeBits(t.min_nobjects, 32); // 1 - w.writeBits(t.first_page_offset, 32); // 2 - w.writeBits(t.nbits_delta_nobjects, 16); // 3 - w.writeBits(t.min_page_length, 32); // 4 - w.writeBits(t.nbits_delta_page_length, 16); // 5 - w.writeBits(t.min_content_offset, 32); // 6 - w.writeBits(t.nbits_delta_content_offset, 16); // 7 - w.writeBits(t.min_content_length, 32); // 8 - w.writeBits(t.nbits_delta_content_length, 16); // 9 - w.writeBits(t.nbits_nshared_objects, 16); // 10 - w.writeBits(t.nbits_shared_identifier, 16); // 11 - w.writeBits(t.nbits_shared_numerator, 16); // 12 - w.writeBits(t.shared_denominator, 16); // 13 - - unsigned int nitems = getAllPages().size(); + w.writeBitsInt(t.min_nobjects, 32); // 1 + w.writeBitsInt(toI(t.first_page_offset), 32); // 2 + w.writeBitsInt(t.nbits_delta_nobjects, 16); // 3 + w.writeBitsInt(t.min_page_length, 32); // 4 + w.writeBitsInt(t.nbits_delta_page_length, 16); // 5 + w.writeBitsInt(t.min_content_offset, 32); // 6 + w.writeBitsInt(t.nbits_delta_content_offset, 16); // 7 + w.writeBitsInt(t.min_content_length, 32); // 8 + w.writeBitsInt(t.nbits_delta_content_length, 16); // 9 + w.writeBitsInt(t.nbits_nshared_objects, 16); // 10 + w.writeBitsInt(t.nbits_shared_identifier, 16); // 11 + w.writeBitsInt(t.nbits_shared_numerator, 16); // 12 + w.writeBitsInt(t.shared_denominator, 16); // 13 + + int nitems = toI(getAllPages().size()); std::vector& entries = t.entries; write_vector_int(w, nitems, entries, @@ -2190,13 +2199,13 @@ QPDF::writeHSharedObject(BitWriter& w) { HSharedObject& t = this->m->shared_object_hints; - w.writeBits(t.first_shared_obj, 32); // 1 - w.writeBits(t.first_shared_offset, 32); // 2 - w.writeBits(t.nshared_first_page, 32); // 3 - w.writeBits(t.nshared_total, 32); // 4 - w.writeBits(t.nbits_nobjects, 16); // 5 - w.writeBits(t.min_group_length, 32); // 6 - w.writeBits(t.nbits_delta_group_length, 16); // 7 + w.writeBitsInt(t.first_shared_obj, 32); // 1 + w.writeBitsInt(toI(t.first_shared_offset), 32); // 2 + w.writeBitsInt(t.nshared_first_page, 32); // 3 + w.writeBitsInt(t.nshared_total, 32); // 4 + w.writeBitsInt(t.nbits_nobjects, 16); // 5 + w.writeBitsInt(t.min_group_length, 32); // 6 + w.writeBitsInt(t.nbits_delta_group_length, 16); // 7 QTC::TC("qpdf", "QPDF lin write nshared_total > nshared_first_page", (t.nshared_total > t.nshared_first_page) ? 1 : 0); @@ -2209,7 +2218,7 @@ QPDF::writeHSharedObject(BitWriter& w) &HSharedObjectEntry::delta_group_length); write_vector_int(w, nitems, entries, 1, &HSharedObjectEntry::signature_present); - for (int i = 0; i < nitems; ++i) + for (size_t i = 0; i < toS(nitems); ++i) { // If signature were present, we'd have to write a 128-bit hash. if (entries.at(i).signature_present != 0) @@ -2226,10 +2235,10 @@ QPDF::writeHSharedObject(BitWriter& w) void QPDF::writeHGeneric(BitWriter& w, HGeneric& t) { - w.writeBits(t.first_object, 32); // 1 - w.writeBits(t.first_object_offset, 32); // 2 - w.writeBits(t.nobjects, 32); // 3 - w.writeBits(t.group_length, 32); // 4 + w.writeBitsInt(t.first_object, 32); // 1 + w.writeBitsInt(toI(t.first_object_offset), 32); // 2 + w.writeBitsInt(t.nobjects, 32); // 3 + w.writeBitsInt(t.group_length, 32); // 4 } void @@ -2252,12 +2261,12 @@ QPDF::generateHintStream(std::map const& xref, BitWriter w(&c); writeHPageOffset(w); - S = c.getCount(); + S = toI(c.getCount()); writeHSharedObject(w); O = 0; if (this->m->outline_hints.nobjects > 0) { - O = c.getCount(); + O = toI(c.getCount()); writeHGeneric(w, this->m->outline_hints); } c.finish(); diff --git a/libqpdf/QPDF_optimization.cc b/libqpdf/QPDF_optimization.cc index 5d959f105..3394836c1 100644 --- a/libqpdf/QPDF_optimization.cc +++ b/libqpdf/QPDF_optimization.cc @@ -87,11 +87,11 @@ QPDF::optimize(std::map 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 diff --git a/libqpdf/QPDF_pages.cc b/libqpdf/QPDF_pages.cc index f4156d034..fe23e8507 100644 --- a/libqpdf/QPDF_pages.cc +++ b/libqpdf/QPDF_pages.cc @@ -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"); } @@ -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(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(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(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(npages)); + assert(this->m->pageobj_to_pages_pos.size() == QIntC::to_size(npages)); } void @@ -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( - 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"); @@ -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(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(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); } } @@ -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()); } } diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index dee3a636f..c8c23f6ab 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -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; } @@ -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 @@ -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(mode[i]); } #ifdef _MSC_VER @@ -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(offset), - whence); + return fseek(stream, QIntC::to_long(offset), whence); # endif #endif } @@ -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 { @@ -592,12 +588,12 @@ QUtil::hex_decode(std::string const& input) { if (pos == 0) { - result.push_back(ch << 4); + result.push_back(static_cast(ch << 4)); pos = 1; } else { - result[result.length()-1] += ch; + result[result.length()-1] |= ch; pos = 0; } } @@ -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((now / 10000000ULL) - 11644473600ULL); #else return time(0); #endif @@ -762,7 +758,7 @@ QUtil::toUTF8(unsigned long uval) *cur_byte = static_cast(0x80 + (uval & 0x3f)); uval >>= 6; // Maximum that will fit in high byte now shrinks by one bit - maxval >>= 1; + maxval = static_cast(maxval >> 1); // Slide to the left one byte if (cur_byte <= bytes) { @@ -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( - (0xff - (1 + (maxval << 1))) + uval); + QIntC::to_ulong(0xff - (1 + (maxval << 1))) + uval); result += reinterpret_cast(cur_byte); } @@ -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((uval & 0xff00) >> 8); + out[1] = static_cast(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(((uval & 0xffc00) >> 10) + 0xd800); + unsigned short low = + static_cast((uval & 0x3ff) + 0xdc00); + out[0] = static_cast((high & 0xff00) >> 8); + out[1] = static_cast(high & 0xff); + out[2] = static_cast((low & 0xff00) >> 8); + out[3] = static_cast(low & 0xff); result = std::string(out, 4); } else @@ -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 { @@ -1764,7 +1763,7 @@ unsigned long get_next_utf8_codepoint( while (ch & bit_check) { ++bytes_needed; - to_clear |= bit_check; + to_clear = static_cast(to_clear | bit_check); bit_check >>= 1; } if (((bytes_needed > 5) || (bytes_needed < 1)) || @@ -1774,11 +1773,11 @@ unsigned long get_next_utf8_codepoint( return 0xfffd; } - unsigned long codepoint = (ch & ~to_clear); + unsigned long codepoint = static_cast(ch & ~to_clear); while (bytes_needed > 0) { --bytes_needed; - ch = utf8_val.at(++pos); + ch = static_cast(utf8_val.at(++pos)); if ((ch & 0xc0) != 0x80) { --pos; @@ -1823,7 +1822,7 @@ transcode_utf8(std::string const& utf8_val, std::string& result, char ch = static_cast(codepoint); if (encoding == e_utf16) { - result += QUtil::toUTF16(ch); + result += QUtil::toUTF16(QIntC::to_ulong(ch)); } else { @@ -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(codepoint & 0xff)); + result.append(1, static_cast(codepoint & 0xff)); } else { @@ -1859,7 +1858,7 @@ transcode_utf8(std::string const& utf8_val, std::string& result, okay = false; ch = static_cast(unknown); } - result.append(1, ch); + result.append(1, static_cast(ch)); } } return okay; @@ -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 @@ -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(val.at(i)) << 8) + - static_cast(val.at(i+1)); + QIntC::to_ushort( + (static_cast(val.at(i)) << 8) + + static_cast(val.at(i+1))); if ((bits & 0xFC00) == 0xD800) { - codepoint = 0x10000 + ((bits & 0x3FF) << 10); + codepoint = 0x10000U + ((bits & 0x3FFU) << 10U); continue; } else if ((bits & 0xFC00) == 0xDC00) diff --git a/libqpdf/RC4.cc b/libqpdf/RC4.cc index 7639a3641..8ab242a00 100644 --- a/libqpdf/RC4.cc +++ b/libqpdf/RC4.cc @@ -1,4 +1,5 @@ #include +#include #include @@ -15,12 +16,13 @@ RC4::RC4(unsigned char const* key_data, int key_len) { if (key_len == -1) { - key_len = strlen(reinterpret_cast(key_data)); + key_len = QIntC::to_int( + strlen(reinterpret_cast(key_data))); } for (int i = 0; i < 256; ++i) { - key.state[i] = i; + key.state[i] = static_cast(i); } key.x = 0; key.y = 0; @@ -36,7 +38,7 @@ 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) { @@ -44,10 +46,10 @@ RC4::process(unsigned char *in_data, int len, unsigned char* out_data) 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((key.x + 1) % 256); + key.y = static_cast((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]; diff --git a/libqpdf/SecureRandomDataProvider.cc b/libqpdf/SecureRandomDataProvider.cc index fe9f1d4b5..6d40852a0 100644 --- a/libqpdf/SecureRandomDataProvider.cc +++ b/libqpdf/SecureRandomDataProvider.cc @@ -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) || \ @@ -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(data))) + if (! CryptGenRandom(c.crypt_prov, static_cast(len), + reinterpret_cast(data))) { throw std::runtime_error("unable to generate secure random data"); } @@ -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)); } diff --git a/libqpdf/bits.icc b/libqpdf/bits.icc index bcd7dd85e..1cbbebccf 100644 --- a/libqpdf/bits.icc +++ b/libqpdf/bits.icc @@ -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: @@ -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( + *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", @@ -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(byte >> leftover); // Copy the bits into result result <<= to_copy; @@ -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) { @@ -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( + (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(newval << bits_left_in_ch); ch |= newval; if (bits_left_in_ch == 0) { diff --git a/libqpdf/qpdf-c.cc b/libqpdf/qpdf-c.cc index 310bb7d09..00712a930 100644 --- a/libqpdf/qpdf-c.cc +++ b/libqpdf/qpdf-c.cc @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -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 @@ -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) diff --git a/libqpdf/qpdf/BitStream.hh b/libqpdf/qpdf/BitStream.hh index bdbf2645b..8be7c64de 100644 --- a/libqpdf/qpdf/BitStream.hh +++ b/libqpdf/qpdf/BitStream.hh @@ -4,28 +4,33 @@ #define BITSTREAM_HH #include +#include 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 diff --git a/libqpdf/qpdf/BitWriter.hh b/libqpdf/qpdf/BitWriter.hh index 76e28b8ee..3ca919776 100644 --- a/libqpdf/qpdf/BitWriter.hh +++ b/libqpdf/qpdf/BitWriter.hh @@ -4,6 +4,7 @@ #define BITWRITER_HH #include +#include class Pipeline; @@ -15,9 +16,11 @@ 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(); @@ -25,7 +28,7 @@ class BitWriter private: Pipeline* pl; unsigned char ch; - unsigned int bit_offset; + size_t bit_offset; }; #endif // BITWRITER_HH diff --git a/libqpdf/qpdf/MD5.hh b/libqpdf/qpdf/MD5.hh index 5cefe08c3..02cdb3cfb 100644 --- a/libqpdf/qpdf/MD5.hh +++ b/libqpdf/qpdf/MD5.hh @@ -3,6 +3,7 @@ #include #include +#include #ifdef HAVE_INTTYPES_H # include #endif @@ -25,9 +26,9 @@ 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 @@ -35,7 +36,7 @@ class MD5 // 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 @@ -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 @@ -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) diff --git a/libqpdf/qpdf/Pl_AES_PDF.hh b/libqpdf/qpdf/Pl_AES_PDF.hh index ac56e59ae..4aaf68bb7 100644 --- a/libqpdf/qpdf/Pl_AES_PDF.hh +++ b/libqpdf/qpdf/Pl_AES_PDF.hh @@ -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(); diff --git a/libqpdf/qpdf/Pl_ASCII85Decoder.hh b/libqpdf/qpdf/Pl_ASCII85Decoder.hh index 4778f61af..cef094250 100644 --- a/libqpdf/qpdf/Pl_ASCII85Decoder.hh +++ b/libqpdf/qpdf/Pl_ASCII85Decoder.hh @@ -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; }; diff --git a/libqpdf/qpdf/Pl_LZWDecoder.hh b/libqpdf/qpdf/Pl_LZWDecoder.hh index b4f517ffd..0456310f8 100644 --- a/libqpdf/qpdf/Pl_LZWDecoder.hh +++ b/libqpdf/qpdf/Pl_LZWDecoder.hh @@ -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 table; - int last_code; + unsigned int last_code; }; #endif // PL_LZWDECODER_HH diff --git a/libqpdf/qpdf/Pl_RC4.hh b/libqpdf/qpdf/Pl_RC4.hh index 27eab5d04..9885f0ade 100644 --- a/libqpdf/qpdf/Pl_RC4.hh +++ b/libqpdf/qpdf/Pl_RC4.hh @@ -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 diff --git a/libqpdf/qpdf/RC4.hh b/libqpdf/qpdf/RC4.hh index efd91069c..a2aa5dce8 100644 --- a/libqpdf/qpdf/RC4.hh +++ b/libqpdf/qpdf/RC4.hh @@ -1,6 +1,8 @@ #ifndef RC4_HH #define RC4_HH +#include + class RC4 { public: @@ -8,7 +10,8 @@ class RC4 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 diff --git a/libqpdf/qpdf/rijndael.h b/libqpdf/qpdf/rijndael.h index 8b4c88f6b..fa838fd95 100644 --- a/libqpdf/qpdf/rijndael.h +++ b/libqpdf/qpdf/rijndael.h @@ -8,14 +8,15 @@ #ifdef HAVE_STDINT_H # include #endif +#include -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) diff --git a/libqpdf/rijndael.cc b/libqpdf/rijndael.cc index 7f711df7d..c60c22880 100644 --- a/libqpdf/rijndael.cc +++ b/libqpdf/rijndael.cc @@ -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; @@ -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: */ @@ -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; @@ -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; diff --git a/libqpdf/sph/md_helper.c b/libqpdf/sph/md_helper.c index 5384f03f7..829391a7e 100644 --- a/libqpdf/sph/md_helper.c +++ b/libqpdf/sph/md_helper.c @@ -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; @@ -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 diff --git a/libqpdf/sph/sph_types.h b/libqpdf/sph/sph_types.h index f434d8bb8..e3b648c1b 100644 --- a/libqpdf/sph/sph_types.h +++ b/libqpdf/sph/sph_types.h @@ -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 @@ -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 diff --git a/libtests/aes.cc b/libtests/aes.cc index b5a63d9a2..26906d468 100644 --- a/libtests/aes.cc +++ b/libtests/aes.cc @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -87,7 +88,7 @@ int main(int argc, char* argv[]) usage(); } - unsigned int hexkeylen = strlen(hexkey); + unsigned int hexkeylen = QIntC::to_uint(strlen(hexkey)); unsigned int keylen = hexkeylen / 2; FILE* infile = QUtil::safe_fopen(infilename, "rb"); diff --git a/libtests/bits.cc b/libtests/bits.cc index 3b274f935..1dfd42ed7 100644 --- a/libtests/bits.cc +++ b/libtests/bits.cc @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include #include #include @@ -12,8 +14,8 @@ #include "../libqpdf/bits.icc" static void -print_values(int byte_offset, unsigned int bit_offset, - unsigned int bits_available) +print_values(long long byte_offset, size_t bit_offset, + size_t bits_available) { std::cout << "byte offset = " << byte_offset << ", " << "bit offset = " << bit_offset << ", " @@ -22,11 +24,11 @@ print_values(int byte_offset, unsigned int bit_offset, static void test_read_bits(unsigned char const* buf, - unsigned char const*& p, unsigned int& bit_offset, - unsigned int& bits_available, int bits_wanted) + unsigned char const*& p, size_t& bit_offset, + size_t& bits_available, size_t bits_wanted) { unsigned long result = - read_bits(p, bit_offset, bits_available, bits_wanted); + QIntC::to_ulong(read_bits(p, bit_offset, bits_available, bits_wanted)); std::cout << "bits read: " << bits_wanted << ", result = " << result << std::endl; @@ -34,12 +36,12 @@ test_read_bits(unsigned char const* buf, } static void -test_write_bits(unsigned char& ch, unsigned int& bit_offset, unsigned long val, - int bits, Pl_Buffer* bp) +test_write_bits(unsigned char& ch, size_t& bit_offset, unsigned long val, + size_t bits, Pl_Buffer* bp) { write_bits(ch, bit_offset, val, bits, bp); - printf("ch = %02x, bit_offset = %d\n", - static_cast(ch), bit_offset); + std::cout << "ch = " << QUtil::uint_to_string_base(ch, 16, 2) + << ", bit_offset = " << bit_offset << std::endl; } static void @@ -51,10 +53,10 @@ print_buffer(Pl_Buffer* bp) size_t l = b->getSize(); for (unsigned long i = 0; i < l; ++i) { - printf("%02x%s", static_cast(p[i]), - (i == l - 1) ? "\n" : " "); + std::cout << QUtil::uint_to_string_base(p[i], 16, 2) + << ((i == l - 1) ? "\n" : " "); } - printf("\n"); + std::cout << std::endl; delete b; } @@ -71,8 +73,8 @@ test() }; unsigned char const* p = buf; - unsigned int bit_offset = 7; - unsigned int bits_available = 64; + size_t bit_offset = 7; + size_t bits_available = 64; // 11110:101 0:001010:1 01100101: 01111001 // 0:00:1:0010 10001001 01110101 01001:011 @@ -163,7 +165,7 @@ test() bw.writeBits(30UL, 5); bw.flush(); bw.flush(); - bw.writeBits(0xABUL, 8); + bw.writeBitsInt(0xAB, 8); bw.flush(); print_buffer(bp); bw.writeBitsSigned(-1, 3); // 111 diff --git a/libtests/dct_compress.cc b/libtests/dct_compress.cc index 65539582d..590af57f2 100644 --- a/libtests/dct_compress.cc +++ b/libtests/dct_compress.cc @@ -42,8 +42,8 @@ int main(int argc, char* argv[]) char* infilename = argv[1]; char* outfilename = argv[2]; - int width = QUtil::string_to_int(argv[3]); - int height = QUtil::string_to_int(argv[4]); + JDIMENSION width = QUtil::string_to_uint(argv[3]); + JDIMENSION height = QUtil::string_to_uint(argv[4]); char* colorspace = argv[5]; J_COLOR_SPACE cs = ((strcmp(colorspace, "rgb") == 0) ? JCS_RGB : diff --git a/libtests/predictors.cc b/libtests/predictors.cc index 47efa2877..9342e22cf 100644 --- a/libtests/predictors.cc +++ b/libtests/predictors.cc @@ -2,6 +2,7 @@ #include #include #include +#include #include #include @@ -11,7 +12,7 @@ void run(char const* filename, char const* filter, bool encode, unsigned int columns, - int bits_per_sample, int samples_per_pixel) + unsigned int bits_per_sample, unsigned int samples_per_pixel) { FILE* in = QUtil::safe_fopen(filename, "rb"); FILE* o1 = QUtil::safe_fopen("out", "wb"); @@ -89,7 +90,9 @@ int main(int argc, char* argv[]) try { run(filename, filter, encode, - columns, bits_per_sample, samples_per_pixel); + QIntC::to_uint(columns), + QIntC::to_uint(bits_per_sample), + QIntC::to_uint(samples_per_pixel)); } catch (std::exception& e) { diff --git a/libtests/qintc.cc b/libtests/qintc.cc index 79fc6f53d..95105aebc 100644 --- a/libtests/qintc.cc +++ b/libtests/qintc.cc @@ -48,10 +48,10 @@ int main() try_convert(true, QIntC::to_uint, ul2); try_convert(true, QIntC::to_offset, u1); try_convert(true, QIntC::to_offset, i1); - try_convert(false, QIntC::to_size, i1); + try_convert(false, QIntC::to_ulonglong, i1); try_convert(true, QIntC::to_char, i2); try_convert(true, QIntC::to_uchar, i2); - try_convert(false, QIntC::to_uchar, c1); + try_convert(false, QIntC::to_uchar, c1); return 0; } diff --git a/libtests/qtest/qintc/qintc.out b/libtests/qtest/qintc/qintc.out index 9b6d35d9b..5c6479e21 100644 --- a/libtests/qtest/qintc/qintc.out +++ b/libtests/qtest/qintc/qintc.out @@ -7,7 +7,7 @@ QIntC::to_int(ul2): 12345 12345 PASSED QIntC::to_uint(ul2): 12345 12345 PASSED QIntC::to_offset(u1): 3141592653 3141592653 PASSED QIntC::to_offset(i1): -1153374643 -1153374643 PASSED -QIntC::to_size(i1): integer out of range converting -1153374643 from a 4-byte signed type to a 8-byte unsigned type PASSED +QIntC::to_ulonglong(i1): integer out of range converting -1153374643 from a 4-byte signed type to a 8-byte unsigned type PASSED QIntC::to_char(i2): 81 Q PASSED QIntC::to_uchar(i2): 81 Q PASSED QIntC::to_uchar(c1): integer out of range converting ÷ from a 1-byte signed type to a 1-byte unsigned type PASSED diff --git a/libtests/qtest/qutil/qutil.out b/libtests/qtest/qutil/qutil.out index 4d19617d2..2f2702267 100644 --- a/libtests/qtest/qutil/qutil.out +++ b/libtests/qtest/qutil/qutil.out @@ -12,6 +12,7 @@ 16059 37273 3ebb +5000093552 one 7 compare okay diff --git a/libtests/qutil.cc b/libtests/qutil.cc index 0e0a063b9..900f0e6fc 100644 --- a/libtests/qutil.cc +++ b/libtests/qutil.cc @@ -93,7 +93,8 @@ void string_conversion_test() << QUtil::double_to_string(.000123456, 5) << std::endl << QUtil::int_to_string_base(16059, 10) << std::endl << QUtil::int_to_string_base(16059, 8) << std::endl - << QUtil::int_to_string_base(16059, 16) << std::endl; + << QUtil::int_to_string_base(16059, 16) << std::endl + << QUtil::int_to_string_base(5000093552LL, 10) << std::endl; std::string embedded_null = "one"; embedded_null += '\0'; diff --git a/libtests/rc4.cc b/libtests/rc4.cc index 7a4d8bd94..f877666ff 100644 --- a/libtests/rc4.cc +++ b/libtests/rc4.cc @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -18,7 +19,7 @@ int main(int argc, char* argv[]) char* hexkey = argv[1]; char* infilename = argv[2]; char* outfilename = argv[3]; - unsigned int hexkeylen = strlen(hexkey); + unsigned int hexkeylen = QIntC::to_uint(strlen(hexkey)); unsigned int keylen = hexkeylen / 2; unsigned char* key = new unsigned char[keylen + 1]; key[keylen] = '\0'; @@ -38,7 +39,7 @@ int main(int argc, char* argv[]) FILE* outfile = QUtil::safe_fopen(outfilename, "wb"); Pl_StdioFile* out = new Pl_StdioFile("stdout", outfile); // Use a small buffer size (64) for testing - Pl_RC4* rc4 = new Pl_RC4("rc4", out, key, keylen, 64); + Pl_RC4* rc4 = new Pl_RC4("rc4", out, key, QIntC::to_int(keylen), 64U); delete [] key; // 64 < buffer size < 512, buffer_size is not a power of 2 for testing diff --git a/qpdf/qpdf-ctest.c b/qpdf/qpdf-ctest.c index 6b5357968..579d58900 100644 --- a/qpdf/qpdf-ctest.c +++ b/qpdf/qpdf-ctest.c @@ -391,7 +391,7 @@ static void test16(char const* infile, qpdf_set_stream_data_mode(qpdf, qpdf_s_uncompress); qpdf_write(qpdf); f = safe_fopen(outfile, "wb"); - buflen = qpdf_get_buffer_length(qpdf); + buflen = (unsigned long)(qpdf_get_buffer_length(qpdf)); buf = qpdf_get_buffer(qpdf); fwrite(buf, 1, buflen, f); fclose(f); diff --git a/qpdf/qpdf.cc b/qpdf/qpdf.cc index 5a8a82d1d..4200903bd 100644 --- a/qpdf/qpdf.cc +++ b/qpdf/qpdf.cc @@ -24,6 +24,7 @@ #include #include +#include static int const EXIT_ERROR = 2; static int const EXIT_WARNING = 3; @@ -1809,8 +1810,7 @@ ArgParser::argKeepFilesOpen(char* parameter) void ArgParser::argKeepFilesOpenThreshold(char* parameter) { - o.keep_files_open_threshold = - static_cast(QUtil::string_to_int(parameter)); + o.keep_files_open_threshold = QUtil::string_to_uint(parameter); } void @@ -2039,25 +2039,25 @@ ArgParser::argRemovePageLabels() void ArgParser::argOiMinWidth(char* parameter) { - o.oi_min_width = QUtil::string_to_int(parameter); + o.oi_min_width = QUtil::string_to_uint(parameter); } void ArgParser::argOiMinHeight(char* parameter) { - o.oi_min_height = QUtil::string_to_int(parameter); + o.oi_min_height = QUtil::string_to_uint(parameter); } void ArgParser::argOiMinArea(char* parameter) { - o.oi_min_area = QUtil::string_to_int(parameter); + o.oi_min_area = QUtil::string_to_uint(parameter); } void ArgParser::argIiMinBytes(char* parameter) { - o.ii_min_bytes = QUtil::string_to_int(parameter); + o.ii_min_bytes = QUtil::string_to_uint(parameter); } void @@ -2318,7 +2318,7 @@ ArgParser::handleArgFileArguments() { argv[i] = new_argv.at(i).getPointer(); } - argc = static_cast(new_argv.size()); + argc = QIntC::to_int(new_argv.size()); argv[argc] = 0; } @@ -2423,7 +2423,7 @@ ArgParser::handleBashArguments() { argv[i] = bash_argv.at(i).getPointer(); } - argc = static_cast(bash_argv.size()); + argc = QIntC::to_int(bash_argv.size()); argv[argc] = 0; } @@ -2648,7 +2648,8 @@ QPDFPageData::QPDFPageData(std::string const& filename, try { this->selected_pages = - QUtil::parse_numrange(range, this->orig_pages.size()); + QUtil::parse_numrange(range, + QIntC::to_int(this->orig_pages.size())); } catch (std::runtime_error& e) { @@ -2805,8 +2806,8 @@ ArgParser::checkCompletion() if (QUtil::get_env("COMP_LINE", &bash_line) && QUtil::get_env("COMP_POINT", &bash_point_env)) { - int p = QUtil::string_to_int(bash_point_env.c_str()); - if ((p > 0) && (p <= static_cast(bash_line.length()))) + size_t p = QUtil::string_to_uint(bash_point_env.c_str()); + if ((p > 0) && (p <= bash_line.length())) { // Truncate the line. We ignore everything at or after the // cursor for completion purposes. @@ -2844,7 +2845,7 @@ ArgParser::checkCompletion() { // Go back to the last separator and set prev based on // that. - int p1 = p; + size_t p1 = p; while (--p1 > 0) { char ch = bash_line.at(p1); @@ -3342,9 +3343,9 @@ static void do_show_pages(QPDF& pdf, Options& o) QPDFObjectHandle image = (*iter).second; QPDFObjectHandle dict = image.getDict(); int width = - dict.getKey("/Width").getIntValue(); + dict.getKey("/Width").getIntValueAsInt(); int height = - dict.getKey("/Height").getIntValue(); + dict.getKey("/Height").getIntValueAsInt(); std::cout << " " << name << ": " << image.unparse() << ", " << width << " x " << height @@ -3410,7 +3411,7 @@ static void do_json_pages(QPDF& pdf, Options& o, JSON& j) QPDFOutlineDocumentHelper odh(pdf); pdh.pushInheritedAttributesToPage(); std::vector pages = pdh.getAllPages(); - size_t pageno = 0; + int pageno = 0; for (std::vector::iterator iter = pages.begin(); iter != pages.end(); ++iter, ++pageno) { @@ -3503,7 +3504,8 @@ static void do_json_page_labels(QPDF& pdf, Options& o, JSON& j) if (pldh.hasPageLabels()) { std::vector labels; - pldh.getLabelsForPageRange(0, pages.size() - 1, 0, labels); + pldh.getLabelsForPageRange( + 0, QIntC::to_int(pages.size()) - 1, 0, labels); for (std::vector::iterator iter = labels.begin(); iter != labels.end(); ++iter) { @@ -3869,10 +3871,24 @@ ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) } // Files have been seen in the wild whose width and height are // floating point, which is goofy, but we can deal with it. - JDIMENSION w = static_cast( - w_obj.isInteger() ? w_obj.getIntValue() : w_obj.getNumericValue()); - JDIMENSION h = static_cast( - h_obj.isInteger() ? h_obj.getIntValue() : h_obj.getNumericValue()); + JDIMENSION w = 0; + if (w_obj.isInteger()) + { + w = w_obj.getUIntValueAsUInt(); + } + else + { + w = static_cast(w_obj.getNumericValue()); + } + JDIMENSION h = 0; + if (h_obj.isInteger()) + { + h = h_obj.getUIntValueAsUInt(); + } + else + { + h = static_cast(h_obj.getNumericValue()); + } std::string colorspace = (colorspace_obj.isName() ? colorspace_obj.getName() : std::string()); @@ -4119,10 +4135,10 @@ static void validate_under_overlay(QPDF& pdf, UnderOverlay* uo, Options& o) return; } QPDFPageDocumentHelper main_pdh(pdf); - int main_npages = static_cast(main_pdh.getAllPages().size()); + int main_npages = QIntC::to_int(main_pdh.getAllPages().size()); uo->pdf = process_file(uo->filename, uo->password, o); QPDFPageDocumentHelper uo_pdh(*(uo->pdf)); - int uo_npages = static_cast(uo_pdh.getAllPages().size()); + int uo_npages = QIntC::to_int(uo_pdh.getAllPages().size()); try { uo->to_pagenos = QUtil::parse_numrange(uo->to_nr, main_npages); @@ -4185,7 +4201,7 @@ static void do_under_overlay_for_page( QPDFPageObjectHelper& dest_page, bool before) { - int pageno = 1 + page_idx; + int pageno = 1 + QIntC::to_int(page_idx); if (! pagenos.count(pageno)) { return; @@ -4206,7 +4222,8 @@ static void do_under_overlay_for_page( { fo[from_pageno] = pdf.copyForeignObject( - pages.at(from_pageno - 1).getFormXObjectForPage()); + pages.at(QIntC::to_size(from_pageno - 1)). + getFormXObjectForPage()); } // If the same page is overlaid or underlaid multiple times, // we'll generate multiple names for it, but that's harmless @@ -4594,7 +4611,8 @@ static void handle_page_specs(QPDF& pdf, Options& o) int pageno = *pageno_iter - 1; pldh.getLabelsForPageRange(pageno, pageno, out_pageno, new_labels); - QPDFPageObjectHelper to_copy = page_data.orig_pages.at(pageno); + QPDFPageObjectHelper to_copy = + page_data.orig_pages.at(QIntC::to_size(pageno)); QPDFObjGen to_copy_og = to_copy.getObjectHandle().getObjGen(); unsigned long long from_uuid = page_data.qpdf->getUniqueId(); if (copied_pages[from_uuid].count(to_copy_og)) @@ -4634,7 +4652,7 @@ static void handle_page_specs(QPDF& pdf, Options& o) // other places, such as the outlines dictionary. for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno) { - if (selected_from_orig.count(pageno) == 0) + if (selected_from_orig.count(QIntC::to_int(pageno)) == 0) { pdf.replaceObject( orig_pages.at(pageno).getObjectHandle().getObjGen(), @@ -4647,7 +4665,7 @@ static void handle_rotations(QPDF& pdf, Options& o) { QPDFPageDocumentHelper dh(pdf); std::vector pages = dh.getAllPages(); - int npages = static_cast(pages.size()); + int npages = QIntC::to_int(pages.size()); for (std::map::iterator iter = o.rotations.begin(); iter != o.rotations.end(); ++iter) @@ -4663,7 +4681,8 @@ static void handle_rotations(QPDF& pdf, Options& o) int pageno = *i2 - 1; if ((pageno >= 0) && (pageno < npages)) { - pages.at(pageno).rotatePage(rspec.angle, rspec.relative); + pages.at(QIntC::to_size(pageno)).rotatePage( + rspec.angle, rspec.relative); } } } @@ -4957,7 +4976,8 @@ static void write_outfile(QPDF& pdf, Options& o) if (num_spot != 0) { QTC::TC("qpdf", "qpdf split-pages %d"); - before = std::string(o.outfilename, (num_spot - o.outfilename)); + before = std::string(o.outfilename, + QIntC::to_size(num_spot - o.outfilename)); after = num_spot + 2; } else if ((len >= 4) && @@ -4980,19 +5000,19 @@ static void write_outfile(QPDF& pdf, Options& o) } QPDFPageLabelDocumentHelper pldh(pdf); std::vector const& pages = pdf.getAllPages(); - int pageno_len = QUtil::int_to_string(pages.size()).length(); - unsigned int num_pages = pages.size(); - for (unsigned int i = 0; i < num_pages; i += o.split_pages) + size_t pageno_len = QUtil::uint_to_string(pages.size()).length(); + size_t num_pages = pages.size(); + for (size_t i = 0; i < num_pages; i += QIntC::to_size(o.split_pages)) { - unsigned int first = i + 1; - unsigned int last = i + o.split_pages; + size_t first = i + 1; + size_t last = i + QIntC::to_size(o.split_pages); if (last > num_pages) { last = num_pages; } QPDF outpdf; outpdf.emptyPDF(); - for (unsigned int pageno = first; pageno <= last; ++pageno) + for (size_t pageno = first; pageno <= last; ++pageno) { QPDFObjectHandle page = pages.at(pageno - 1); outpdf.addPage(page, false); @@ -5000,17 +5020,22 @@ static void write_outfile(QPDF& pdf, Options& o) if (pldh.hasPageLabels()) { std::vector labels; - pldh.getLabelsForPageRange(first - 1, last - 1, 0, labels); + pldh.getLabelsForPageRange( + QIntC::to_longlong(first - 1), + QIntC::to_longlong(last - 1), + 0, labels); QPDFObjectHandle page_labels = QPDFObjectHandle::newDictionary(); page_labels.replaceKey( "/Nums", QPDFObjectHandle::newArray(labels)); outpdf.getRoot().replaceKey("/PageLabels", page_labels); } - std::string page_range = QUtil::int_to_string(first, pageno_len); + std::string page_range = + QUtil::uint_to_string(first, QIntC::to_int(pageno_len)); if (o.split_pages > 1) { - page_range += "-" + QUtil::int_to_string(last, pageno_len); + page_range += "-" + + QUtil::uint_to_string(last, QIntC::to_int(pageno_len)); } std::string outfile = before + page_range + after; QPDFWriter w(outpdf, outfile.c_str()); @@ -5117,8 +5142,10 @@ int wmain(int argc, wchar_t* argv[]) for (size_t j = 0; j < wcslen(argv[i]); ++j) { unsigned short codepoint = static_cast(argv[i][j]); - utf16.append(1, static_cast(codepoint >> 8)); - utf16.append(1, static_cast(codepoint & 0xff)); + utf16.append(1, static_cast( + QIntC::to_uchar(codepoint >> 8))); + utf16.append(1, static_cast( + QIntC::to_uchar(codepoint & 0xff))); } std::string utf8 = QUtil::utf16_to_utf8(utf16); utf8_argv.push_back( @@ -5131,7 +5158,7 @@ int wmain(int argc, wchar_t* argv[]) { new_argv[i] = utf8_argv.at(i).getPointer(); } - argc = static_cast(utf8_argv.size()); + argc = QIntC::to_int(utf8_argv.size()); new_argv[argc] = 0; return realmain(argc, new_argv); } diff --git a/qpdf/test_driver.cc b/qpdf/test_driver.cc index a6a0ef385..76d7dd26a 100644 --- a/qpdf/test_driver.cc +++ b/qpdf/test_driver.cc @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -173,7 +174,7 @@ static void read_file_into_memory( { FILE* f = QUtil::safe_fopen(filename, "rb"); fseek(f, 0, SEEK_END); - size = QUtil::tell(f); + size = QIntC::to_size(QUtil::tell(f)); fseek(f, 0, SEEK_SET); file_buf = PointerHolder(true, new char[size]); char* buf_p = file_buf.getPointer(); @@ -280,7 +281,7 @@ void runtest(int n, char const* filename1, char const* arg2) char* p = file_buf.getPointer(); for (size_t i = 0; i < size; ++i) { - p[i] ^= 0xcc; + p[i] = static_cast(p[i] ^ 0xcc); } pdf.processMemoryFile((std::string(filename1) + ".pdf").c_str(), p, size); @@ -544,8 +545,8 @@ void runtest(int n, char const* filename1, char const* arg2) std::string const& name = (*iter).first; QPDFObjectHandle image = (*iter).second; QPDFObjectHandle dict = image.getDict(); - int width = dict.getKey("/Width").getIntValue(); - int height = dict.getKey("/Height").getIntValue(); + long long width = dict.getKey("/Width").getIntValue(); + long long height = dict.getKey("/Height").getIntValue(); std::cout << " " << name << ": " << width << " x " << height << std::endl; @@ -929,7 +930,8 @@ void runtest(int n, char const* filename1, char const* arg2) page.replaceKey("/Parent", pages); pages.replaceKey( "/Count", - QPDFObjectHandle::newInteger(1 + all_pages.size())); + QPDFObjectHandle::newInteger( + 1 + QIntC::to_longlong(all_pages.size()))); kids.appendItem(page); assert(all_pages.size() == 10); pdf.updateAllPagesCache(); @@ -1096,8 +1098,8 @@ void runtest(int n, char const* filename1, char const* arg2) // Verify that the previously added reserved keys can be // dereferenced properly now - int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValue(); - int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValue(); + int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValueAsInt(); + int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValueAsInt(); if ((i1 == 2) && (i2 == 1)) { std::cout << "circular access and lazy resolution worked" << std::endl; @@ -1424,7 +1426,7 @@ void runtest(int n, char const* filename1, char const* arg2) { std::string t; for (size_t i = 0; - i < std::min(data.size(), static_cast(20)); + i < std::min(data.size(), QIntC::to_size(20)); ++i) { if ((data.at(i) >= 32) && (data.at(i) <= 126)) @@ -1436,7 +1438,7 @@ void runtest(int n, char const* filename1, char const* arg2) t += "."; } } - t += " (" + QUtil::int_to_string(data.size()) + " bytes)"; + t += " (" + QUtil::uint_to_string(data.size()) + " bytes)"; data = t; } std::cout << filename << ":\n" << data << "--END--\n"; @@ -1797,7 +1799,7 @@ void runtest(int n, char const* filename1, char const* arg2) { // Test page labels. QPDFPageLabelDocumentHelper pldh(pdf); - size_t npages = pdf.getRoot().getKey("/Pages"). + long long npages = pdf.getRoot().getKey("/Pages"). getKey("/Count").getIntValue(); std::vector labels; pldh.getLabelsForPageRange(0, npages - 1, 1, labels); @@ -2076,7 +2078,7 @@ void runtest(int n, char const* filename1, char const* arg2) { pdf.processMemoryFile("empty", "", 0); } - catch (QPDFExc& e) + catch (QPDFExc const&) { std::cout << "Caught QPDFExc as expected" << std::endl; } @@ -2084,7 +2086,7 @@ void runtest(int n, char const* filename1, char const* arg2) { QUtil::safe_fopen("/does/not/exist", "r"); } - catch (QPDFSystemError& e) + catch (QPDFSystemError const&) { std::cout << "Caught QPDFSystemError as expected" << std::endl; } @@ -2092,7 +2094,7 @@ void runtest(int n, char const* filename1, char const* arg2) { QUtil::int_to_string_base(0, 12); } - catch (std::logic_error& e) + catch (std::logic_error const&) { std::cout << "Caught logic_error as expected" << std::endl; } @@ -2100,7 +2102,7 @@ void runtest(int n, char const* filename1, char const* arg2) { QUtil::toUTF8(0xffffffff); } - catch (std::runtime_error& e) + catch (std::runtime_error const&) { std::cout << "Caught runtime_error as expected" << std::endl; } @@ -2110,12 +2112,12 @@ void runtest(int n, char const* filename1, char const* arg2) // Test int size checks. This test will fail if int and long // long are the same size. QPDFObjectHandle t = pdf.getTrailer(); - unsigned long long q1_l = 3L * INT_MAX; - long long q1 = static_cast(q1_l); - long long q2_l = 3L * INT_MIN; - long long q2 = static_cast(q2_l); + unsigned long long q1_l = 3ULL * QIntC::to_ulonglong(INT_MAX); + long long q1 = QIntC::to_longlong(q1_l); + long long q2_l = 3LL * QIntC::to_longlong(INT_MIN); + long long q2 = QIntC::to_longlong(q2_l); unsigned int q3_i = UINT_MAX; - long long q3 = static_cast(q3_i); + long long q3 = QIntC::to_longlong(q3_i); t.replaceKey("/Q1", QPDFObjectHandle::newInteger(q1)); t.replaceKey("/Q2", QPDFObjectHandle::newInteger(q2)); t.replaceKey("/Q3", QPDFObjectHandle::newInteger(q3)); diff --git a/qpdf/test_large_file.cc b/qpdf/test_large_file.cc index ab56bb8aa..59367cf92 100644 --- a/qpdf/test_large_file.cc +++ b/qpdf/test_large_file.cc @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -36,37 +37,39 @@ static char const* whoami = 0; // Height should be a multiple of 10 -static int const nstripes = 10; -static int const stripesize_large = 500; -static int const stripesize_small = 5; -static int const npages = 200; +static size_t const nstripes = 10; +static size_t const stripesize_large = 500; +static size_t const stripesize_small = 5; +static size_t const npages = 200; // initialized in main -int stripesize = 0; -int width = 0; -int height = 0; +size_t stripesize = 0; +size_t width = 0; +size_t height = 0; static unsigned char* buf = 0; -static inline unsigned char get_pixel_color(int n, size_t row) +static inline unsigned char get_pixel_color(size_t n, size_t row) { - return (n & (1 << (nstripes - 1 - row))) ? '\xc0' : '\x40'; + return ((n & (1LLU << (nstripes - 1LLU - row))) + ? static_cast('\xc0') + : static_cast('\x40')); } class ImageChecker: public Pipeline { public: - ImageChecker(int n); + ImageChecker(size_t n); virtual ~ImageChecker(); virtual void write(unsigned char* data, size_t len); virtual void finish(); private: - int n; + size_t n; size_t offset; bool okay; }; -ImageChecker::ImageChecker(int n) : +ImageChecker::ImageChecker(size_t n) : Pipeline("image checker", 0), n(n), offset(0), @@ -106,16 +109,16 @@ ImageChecker::finish() class ImageProvider: public QPDFObjectHandle::StreamDataProvider { public: - ImageProvider(int n); + ImageProvider(size_t n); virtual ~ImageProvider(); virtual void provideStreamData(int objid, int generation, Pipeline* pipeline); private: - int n; + size_t n; }; -ImageProvider::ImageProvider(int n) : +ImageProvider::ImageProvider(size_t n) : n(n) { } @@ -133,7 +136,7 @@ ImageProvider::provideStreamData(int objid, int generation, buf = new unsigned char[width * stripesize]; } std::cout << "page " << n << " of " << npages << std::endl; - for (int y = 0; y < nstripes; ++y) + for (size_t y = 0; y < nstripes; ++y) { unsigned char color = get_pixel_color(n, y); memset(buf, color, width * stripesize); @@ -156,16 +159,16 @@ static void set_parameters(bool large) width = height; } -std::string generate_page_contents(int pageno) +std::string generate_page_contents(size_t pageno) { std::string contents = - "BT /F1 24 Tf 72 720 Td (page " + QUtil::int_to_string(pageno) + + "BT /F1 24 Tf 72 720 Td (page " + QUtil::uint_to_string(pageno) + ") Tj ET\n" "q 468 0 0 468 72 72 cm /Im1 Do Q\n"; return contents; } -static QPDFObjectHandle create_page_contents(QPDF& pdf, int pageno) +static QPDFObjectHandle create_page_contents(QPDF& pdf, size_t pageno) { return QPDFObjectHandle::newStream(&pdf, generate_page_contents(pageno)); } @@ -175,9 +178,9 @@ QPDFObjectHandle newName(std::string const& name) return QPDFObjectHandle::newName(name); } -QPDFObjectHandle newInteger(int val) +QPDFObjectHandle newInteger(size_t val) { - return QPDFObjectHandle::newInteger(val); + return QPDFObjectHandle::newInteger(QIntC::to_longlong(val)); } static void create_pdf(char const* filename) @@ -210,7 +213,7 @@ static void create_pdf(char const* filename) mediabox.appendItem(newInteger(792)); QPDFPageDocumentHelper dh(pdf); - for (int pageno = 1; pageno <= npages; ++pageno) + for (size_t pageno = 1; pageno <= npages; ++pageno) { QPDFObjectHandle image = QPDFObjectHandle::newStream(&pdf); QPDFObjectHandle image_dict = image.getDict(); @@ -253,7 +256,7 @@ static void create_pdf(char const* filename) w.write(); } -static void check_page_contents(int pageno, QPDFObjectHandle page) +static void check_page_contents(size_t pageno, QPDFObjectHandle page) { PointerHolder buf = page.getKey("/Contents").getStreamData(); @@ -270,7 +273,7 @@ static void check_page_contents(int pageno, QPDFObjectHandle page) } } -static void check_image(int pageno, QPDFObjectHandle page) +static void check_image(size_t pageno, QPDFObjectHandle page) { QPDFObjectHandle image = page.getKey("/Resources").getKey("/XObject").getKey("/Im1"); @@ -283,10 +286,10 @@ static void check_pdf(char const* filename) QPDF pdf; pdf.processFile(filename); std::vector const& pages = pdf.getAllPages(); - assert(pages.size() == static_cast(npages)); - for (int i = 0; i < npages; ++i) + assert(pages.size() == QIntC::to_size(npages)); + for (size_t i = 0; i < npages; ++i) { - int pageno = i + 1; + size_t pageno = i + 1; std::cout << "page " << pageno << " of " << npages << std::endl; check_page_contents(pageno, pages.at(i)); check_image(pageno, pages.at(i)); diff --git a/qpdf/test_tokenizer.cc b/qpdf/test_tokenizer.cc index 36758a8b1..d0ddf8a1c 100644 --- a/qpdf/test_tokenizer.cc +++ b/qpdf/test_tokenizer.cc @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -46,7 +47,7 @@ Finder::check() QPDFTokenizer::Token t = tokenizer.readToken(is, "finder", true); qpdf_offset_t offset = this->is->tell(); bool result = (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, str)); - this->is->seek(offset - this->str.length(), SEEK_SET); + this->is->seek(offset - QIntC::to_offset(this->str.length()), SEEK_SET); return result; } @@ -286,7 +287,7 @@ int main(int argc, char* argv[]) { usage(); } - max_len = QUtil::string_to_int(argv[i]); + max_len = QUtil::string_to_uint(argv[i]); } else if (strcmp(argv[i], "-no-ignorable") == 0) {