From cb769c62e55599e9f980001830bc61d9fcaa64a9 Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Tue, 8 Feb 2022 09:18:08 -0500 Subject: WHITESPACE ONLY -- expand tabs in source code This comment expands all tabs using an 8-character tab-width. You should ignore this commit when using git blame or use git blame -w. In the early days, I used to use tabs where possible for indentation, since emacs did this automatically. In recent years, I have switched to only using spaces, which means qpdf source code has been a mixture of spaces and tabs. I have avoided cleaning this up because of not wanting gratuitous whitespaces change to cloud the output of git blame, but I changed my mind after discussing with users who view qpdf source code in editors/IDEs that have other tab widths by default and in light of the fact that I am planning to start applying automatic code formatting soon. --- libqpdf/AES_PDF_native.cc | 46 +- libqpdf/BitStream.cc | 22 +- libqpdf/BitWriter.cc | 4 +- libqpdf/Buffer.cc | 14 +- libqpdf/BufferInputSource.cc | 30 +- libqpdf/ContentNormalizer.cc | 6 +- libqpdf/FileInputSource.cc | 10 +- libqpdf/InsecureRandomDataProvider.cc | 8 +- libqpdf/MD5.cc | 50 +- libqpdf/MD5_native.cc | 30 +- libqpdf/Pipeline.cc | 6 +- libqpdf/Pl_AES_PDF.cc | 142 +-- libqpdf/Pl_ASCII85Decoder.cc | 140 +-- libqpdf/Pl_ASCIIHexDecoder.cc | 106 +- libqpdf/Pl_Buffer.cc | 8 +- libqpdf/Pl_Count.cc | 6 +- libqpdf/Pl_Flate.cc | 222 ++-- libqpdf/Pl_LZWDecoder.cc | 202 ++-- libqpdf/Pl_MD5.cc | 4 +- libqpdf/Pl_PNGFilter.cc | 48 +- libqpdf/Pl_QPDFTokenizer.cc | 2 +- libqpdf/Pl_RC4.cc | 20 +- libqpdf/Pl_SHA2.cc | 18 +- libqpdf/Pl_StdioFile.cc | 28 +- libqpdf/Pl_TIFFPredictor.cc | 24 +- libqpdf/QPDF.cc | 1326 +++++++++++----------- libqpdf/QPDFArgParser.cc | 2 +- libqpdf/QPDFCrypto_gnutls.cc | 30 +- libqpdf/QPDFExc.cc | 42 +- libqpdf/QPDFObjGen.cc | 2 +- libqpdf/QPDFObjectHandle.cc | 442 ++++---- libqpdf/QPDFPageObjectHelper.cc | 2 +- libqpdf/QPDFTokenizer.cc | 512 ++++----- libqpdf/QPDFWriter.cc | 1966 ++++++++++++++++----------------- libqpdf/QPDFXRefEntry.cc | 16 +- libqpdf/QPDF_Array.cc | 12 +- libqpdf/QPDF_Dictionary.cc | 46 +- libqpdf/QPDF_Name.cc | 20 +- libqpdf/QPDF_Stream.cc | 138 +-- libqpdf/QPDF_String.cc | 174 +-- libqpdf/QPDF_encryption.cc | 610 +++++----- libqpdf/QPDF_linearization.cc | 1746 ++++++++++++++--------------- libqpdf/QPDF_optimization.cc | 446 ++++---- libqpdf/QPDF_pages.cc | 16 +- libqpdf/QTC.cc | 6 +- libqpdf/QUtil.cc | 114 +- libqpdf/RC4_native.cc | 22 +- libqpdf/SF_FlateLzwDecode.cc | 2 +- libqpdf/SparseOHArray.cc | 14 +- libqpdf/bits.icc | 128 +-- libqpdf/qpdf-c.cc | 160 +-- libqpdf/qpdf/MD5.hh | 6 +- libqpdf/qpdf/MD5_native.hh | 6 +- libqpdf/qpdf/Pl_AES_PDF.hh | 2 +- libqpdf/qpdf/Pl_LZWDecoder.hh | 2 +- libqpdf/qpdf/Pl_PNGFilter.hh | 2 +- libqpdf/qpdf/Pl_RC4.hh | 4 +- libqpdf/qpdf/QPDF_Stream.hh | 18 +- libqpdf/qpdfjob-c.cc | 4 +- libqpdf/sha2.c | 1066 +++++++++--------- libqpdf/sha2big.c | 214 ++-- libqpdf/sph/md_helper.c | 262 ++--- libqpdf/sph/sph_sha2.h | 14 +- libqpdf/sph/sph_types.h | 612 +++++----- 64 files changed, 5701 insertions(+), 5701 deletions(-) (limited to 'libqpdf') diff --git a/libqpdf/AES_PDF_native.cc b/libqpdf/AES_PDF_native.cc index afbc0bdc..b0900f70 100644 --- a/libqpdf/AES_PDF_native.cc +++ b/libqpdf/AES_PDF_native.cc @@ -26,12 +26,12 @@ AES_PDF_native::AES_PDF_native(bool encrypt, unsigned char const* key, std::memset(this->rk.get(), 0, rk_bytes); if (encrypt) { - this->nrounds = rijndaelSetupEncrypt( + this->nrounds = rijndaelSetupEncrypt( this->rk.get(), this->key.get(), keybits); } else { - this->nrounds = rijndaelSetupDecrypt( + this->nrounds = rijndaelSetupDecrypt( this->rk.get(), this->key.get(), keybits); } } @@ -45,33 +45,33 @@ AES_PDF_native::update(unsigned char* in_data, unsigned char* out_data) { if (this->encrypt) { - if (this->cbc_mode) - { - for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) - { - in_data[i] ^= this->cbc_block[i]; - } - } - rijndaelEncrypt(this->rk.get(), + if (this->cbc_mode) + { + for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) + { + in_data[i] ^= this->cbc_block[i]; + } + } + rijndaelEncrypt(this->rk.get(), this->nrounds, in_data, out_data); - if (this->cbc_mode) - { - memcpy(this->cbc_block, out_data, + if (this->cbc_mode) + { + memcpy(this->cbc_block, out_data, QPDFCryptoImpl::rijndael_buf_size); - } + } } else { - rijndaelDecrypt(this->rk.get(), + rijndaelDecrypt(this->rk.get(), this->nrounds, in_data, out_data); - if (this->cbc_mode) - { - for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) - { - out_data[i] ^= this->cbc_block[i]; - } - memcpy(this->cbc_block, in_data, + if (this->cbc_mode) + { + for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) + { + out_data[i] ^= this->cbc_block[i]; + } + memcpy(this->cbc_block, in_data, QPDFCryptoImpl::rijndael_buf_size); - } + } } } diff --git a/libqpdf/BitStream.cc b/libqpdf/BitStream.cc index 4ab049cc..dc8dccfc 100644 --- a/libqpdf/BitStream.cc +++ b/libqpdf/BitStream.cc @@ -20,7 +20,7 @@ BitStream::reset() bit_offset = 7; if (QIntC::to_uint(nbytes) > static_cast(-1) / 8) { - throw std::runtime_error("array too large for bitstream"); + throw std::runtime_error("array too large for bitstream"); } bits_available = 8 * nbytes; } @@ -29,7 +29,7 @@ unsigned long long BitStream::getBits(size_t nbits) { return read_bits(this->p, this->bit_offset, - this->bits_available, nbits); + this->bits_available, nbits); } long long @@ -63,14 +63,14 @@ BitStream::skipToNextByte() { if (bit_offset != 7) { - size_t bits_to_skip = bit_offset + 1; - if (bits_available < bits_to_skip) - { - throw std::logic_error( - "INTERNAL ERROR: overflow skipping to next byte in bitstream"); - } - bit_offset = 7; - ++p; - bits_available -= bits_to_skip; + size_t bits_to_skip = bit_offset + 1; + if (bits_available < bits_to_skip) + { + throw std::logic_error( + "INTERNAL ERROR: overflow skipping to next byte in bitstream"); + } + bit_offset = 7; + ++p; + bits_available -= bits_to_skip; } } diff --git a/libqpdf/BitWriter.cc b/libqpdf/BitWriter.cc index efe19ded..29445f84 100644 --- a/libqpdf/BitWriter.cc +++ b/libqpdf/BitWriter.cc @@ -43,7 +43,7 @@ BitWriter::flush() { if (bit_offset < 7) { - size_t bits_to_write = bit_offset + 1; - write_bits(this->ch, this->bit_offset, 0, bits_to_write, this->pl); + 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/Buffer.cc b/libqpdf/Buffer.cc index a2bd91a3..1c014041 100644 --- a/libqpdf/Buffer.cc +++ b/libqpdf/Buffer.cc @@ -9,11 +9,11 @@ Buffer::Members::Members(size_t size, unsigned char* buf, bool own_memory) : { if (own_memory) { - this->buf = (size ? new unsigned char[size] : 0); + this->buf = (size ? new unsigned char[size] : 0); } else { - this->buf = buf; + this->buf = buf; } } @@ -21,7 +21,7 @@ Buffer::Members::~Members() { if (this->own_memory) { - delete [] this->buf; + delete [] this->buf; } } @@ -58,10 +58,10 @@ Buffer::copy(Buffer const& rhs) if (this != &rhs) { this->m = PointerHolder(new Members(rhs.m->size, 0, true)); - if (this->m->size) - { - memcpy(this->m->buf, rhs.m->buf, this->m->size); - } + if (this->m->size) + { + memcpy(this->m->buf, rhs.m->buf, this->m->size); + } } } diff --git a/libqpdf/BufferInputSource.cc b/libqpdf/BufferInputSource.cc index 6f692fc9..66b34f54 100644 --- a/libqpdf/BufferInputSource.cc +++ b/libqpdf/BufferInputSource.cc @@ -42,7 +42,7 @@ BufferInputSource::~BufferInputSource() { if (this->m->own_memory) { - delete this->m->buf; + delete this->m->buf; } } @@ -56,9 +56,9 @@ BufferInputSource::findAndSkipNextEOL() qpdf_offset_t end_pos = this->m->max_offset; if (this->m->cur_offset >= end_pos) { - this->last_offset = end_pos; + this->last_offset = end_pos; this->m->cur_offset = end_pos; - return end_pos; + return end_pos; } qpdf_offset_t result = 0; @@ -108,23 +108,23 @@ BufferInputSource::seek(qpdf_offset_t offset, int whence) switch (whence) { case SEEK_SET: - this->m->cur_offset = offset; - break; + this->m->cur_offset = offset; + break; case SEEK_END: QIntC::range_check(this->m->max_offset, offset); - this->m->cur_offset = this->m->max_offset + offset; - break; + this->m->cur_offset = this->m->max_offset + offset; + break; case SEEK_CUR: QIntC::range_check(this->m->cur_offset, offset); - this->m->cur_offset += offset; - break; + this->m->cur_offset += offset; + break; default: - throw std::logic_error( - "INTERNAL ERROR: invalid argument to BufferInputSource::seek"); - break; + throw std::logic_error( + "INTERNAL ERROR: invalid argument to BufferInputSource::seek"); + break; } if (this->m->cur_offset < 0) @@ -150,8 +150,8 @@ BufferInputSource::read(char* buffer, size_t length) qpdf_offset_t end_pos = this->m->max_offset; if (this->m->cur_offset >= end_pos) { - this->last_offset = end_pos; - return 0; + this->last_offset = end_pos; + return 0; } this->last_offset = this->m->cur_offset; @@ -167,6 +167,6 @@ BufferInputSource::unreadCh(char ch) { if (this->m->cur_offset > 0) { - --this->m->cur_offset; + --this->m->cur_offset; } } diff --git a/libqpdf/ContentNormalizer.cc b/libqpdf/ContentNormalizer.cc index f08829b2..1793c6f3 100644 --- a/libqpdf/ContentNormalizer.cc +++ b/libqpdf/ContentNormalizer.cc @@ -61,16 +61,16 @@ ContentNormalizer::handleToken(QPDFTokenizer::Token const& token) // quoting of unprintable characters, etc. writeToken(QPDFTokenizer::Token( QPDFTokenizer::tt_string, token.getValue())); - break; + break; case QPDFTokenizer::tt_name: writeToken(QPDFTokenizer::Token( QPDFTokenizer::tt_name, token.getValue())); - break; + break; default: writeToken(token); - break; + break; } value = token.getRawValue(); diff --git a/libqpdf/FileInputSource.cc b/libqpdf/FileInputSource.cc index 951b1270..b64df811 100644 --- a/libqpdf/FileInputSource.cc +++ b/libqpdf/FileInputSource.cc @@ -15,7 +15,7 @@ FileInputSource::Members::~Members() { if (this->file && this->close_file) { - fclose(this->file); + fclose(this->file); } } @@ -108,9 +108,9 @@ FileInputSource::seek(qpdf_offset_t offset, int whence) { QUtil::os_wrapper(std::string("seek to ") + this->m->filename + ", offset " + - QUtil::int_to_string(offset) + " (" + - QUtil::int_to_string(whence) + ")", - QUtil::seek(this->m->file, offset, whence)); + QUtil::int_to_string(offset) + " (" + + QUtil::int_to_string(whence) + ")", + QUtil::seek(this->m->file, offset, whence)); } void @@ -147,5 +147,5 @@ void FileInputSource::unreadCh(char ch) { QUtil::os_wrapper(this->m->filename + ": unread character", - ungetc(static_cast(ch), this->m->file)); + ungetc(static_cast(ch), this->m->file)); } diff --git a/libqpdf/InsecureRandomDataProvider.cc b/libqpdf/InsecureRandomDataProvider.cc index e246ff97..4077a35f 100644 --- a/libqpdf/InsecureRandomDataProvider.cc +++ b/libqpdf/InsecureRandomDataProvider.cc @@ -27,9 +27,9 @@ InsecureRandomDataProvider::random() { if (! this->seeded_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. + // 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. unsigned int seed = static_cast( QUtil::get_current_time() ^ 0xcccc); #ifdef HAVE_RANDOM @@ -37,7 +37,7 @@ InsecureRandomDataProvider::random() #else srand(seed); #endif - this->seeded_random = true; + this->seeded_random = true; } # ifdef HAVE_RANDOM diff --git a/libqpdf/MD5.cc b/libqpdf/MD5.cc index 0b85de0e..dc4460a0 100644 --- a/libqpdf/MD5.cc +++ b/libqpdf/MD5.cc @@ -66,28 +66,28 @@ void MD5::encodeFile(char const *filename, qpdf_offset_t up_to_offset) } do { - if ((up_to_offset >= 0) && ((so_far + to_try) > up_to_size)) - { - to_try = up_to_size - so_far; - } - len = fread(buffer, 1, to_try, file); - if (len > 0) - { - encodeDataIncrementally(buffer, len); - so_far += len; - if ((up_to_offset >= 0) && (so_far >= up_to_size)) - { - break; - } - } + if ((up_to_offset >= 0) && ((so_far + to_try) > up_to_size)) + { + to_try = up_to_size - so_far; + } + len = fread(buffer, 1, to_try, file); + if (len > 0) + { + encodeDataIncrementally(buffer, len); + so_far += len; + if ((up_to_offset >= 0) && (so_far >= up_to_size)) + { + break; + } + } } while (len > 0); if (ferror(file)) { - // Assume, perhaps incorrectly, that errno was set by the - // underlying call to read.... - (void) fclose(file); - QUtil::throw_system_error( - std::string("MD5: read error on ") + filename); + // Assume, perhaps incorrectly, that errno was set by the + // underlying call to read.... + (void) fclose(file); + QUtil::throw_system_error( + std::string("MD5: read error on ") + filename); } (void) fclose(file); @@ -108,7 +108,7 @@ void MD5::print() unsigned int i; for (i = 0; i < 16; ++i) { - printf("%02x", digest_val[i]); + printf("%02x", digest_val[i]); } printf("\n"); } @@ -140,7 +140,7 @@ MD5::getFileChecksum(char const* filename, qpdf_offset_t up_to_offset) bool MD5::checkDataChecksum(char const* const checksum, - char const* buf, size_t len) + char const* buf, size_t len) { std::string actual_checksum = getDataChecksum(buf, len); return (checksum == actual_checksum); @@ -148,17 +148,17 @@ MD5::checkDataChecksum(char const* const checksum, bool MD5::checkFileChecksum(char const* const checksum, - char const* filename, qpdf_offset_t up_to_offset) + char const* filename, qpdf_offset_t up_to_offset) { bool result = false; try { - std::string actual_checksum = getFileChecksum(filename, up_to_offset); - result = (checksum == actual_checksum); + std::string actual_checksum = getFileChecksum(filename, up_to_offset); + result = (checksum == actual_checksum); } catch (std::runtime_error const&) { - // Ignore -- return false + // Ignore -- return false } return result; } diff --git a/libqpdf/MD5_native.cc b/libqpdf/MD5_native.cc index df5c9674..d609c464 100644 --- a/libqpdf/MD5_native.cc +++ b/libqpdf/MD5_native.cc @@ -117,7 +117,7 @@ void MD5_native::init() // context. void MD5_native::update(unsigned char *input, - size_t inputLen) + size_t inputLen) { unsigned int i, index, partLen; @@ -127,7 +127,7 @@ void MD5_native::update(unsigned char *input, // Update number of bits if ((count[0] += (static_cast(inputLen) << 3)) < (static_cast(inputLen) << 3)) - count[1]++; + count[1]++; count[1] += (static_cast(inputLen) >> 29); partLen = 64 - index; @@ -135,16 +135,16 @@ void MD5_native::update(unsigned char *input, // Transform as many times as possible. if (inputLen >= partLen) { - memcpy(&buffer[index], input, partLen); - transform(state, buffer); + memcpy(&buffer[index], input, partLen); + transform(state, buffer); - for (i = partLen; i + 63 < inputLen; i += 64) - transform(state, &input[i]); + for (i = partLen; i + 63 < inputLen; i += 64) + transform(state, &input[i]); - index = 0; + index = 0; } else - i = 0; + i = 0; // Buffer remaining input memcpy(&buffer[index], &input[i], inputLen-i); @@ -156,7 +156,7 @@ void MD5_native::finalize() { if (finalized) { - return; + return; } unsigned char bits[8]; @@ -286,10 +286,10 @@ void MD5_native::encode(unsigned char *output, uint32_t *input, size_t len) unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { - output[j] = static_cast(input[i] & 0xff); - output[j+1] = static_cast((input[i] >> 8) & 0xff); - output[j+2] = static_cast((input[i] >> 16) & 0xff); - output[j+3] = static_cast((input[i] >> 24) & 0xff); + output[j] = static_cast(input[i] & 0xff); + output[j+1] = static_cast((input[i] >> 8) & 0xff); + output[j+2] = static_cast((input[i] >> 16) & 0xff); + output[j+3] = static_cast((input[i] >> 24) & 0xff); } } @@ -300,9 +300,9 @@ void MD5_native::decode(uint32_t *output, unsigned char *input, size_t len) unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = + output[i] = static_cast(input[j]) | (static_cast(input[j+1]) << 8) | - (static_cast(input[j+2]) << 16) | + (static_cast(input[j+2]) << 16) | (static_cast(input[j+3]) << 24); } diff --git a/libqpdf/Pipeline.cc b/libqpdf/Pipeline.cc index e4ad3741..097ed0f2 100644 --- a/libqpdf/Pipeline.cc +++ b/libqpdf/Pipeline.cc @@ -17,9 +17,9 @@ Pipeline::getNext(bool allow_null) { if ((this->next == 0) && (! allow_null)) { - throw std::logic_error( - this->identifier + - ": Pipeline::getNext() called on pipeline with no next"); + throw std::logic_error( + this->identifier + + ": Pipeline::getNext() called on pipeline with no next"); } return this->next; } diff --git a/libqpdf/Pl_AES_PDF.cc b/libqpdf/Pl_AES_PDF.cc index de1f666f..581ca9ab 100644 --- a/libqpdf/Pl_AES_PDF.cc +++ b/libqpdf/Pl_AES_PDF.cc @@ -12,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, + bool encrypt, unsigned char const* key, size_t key_bytes) : Pipeline(identifier, next), crypto(QPDFCryptoProvider::getImpl()), @@ -81,17 +81,17 @@ Pl_AES_PDF::write(unsigned char* data, size_t len) while (bytes_left > 0) { - if (this->offset == this->buf_size) - { - flush(false); - } - - size_t available = this->buf_size - this->offset; - size_t bytes = (bytes_left < available ? bytes_left : available); - bytes_left -= bytes; - std::memcpy(this->inbuf + this->offset, p, bytes); - this->offset += bytes; - p += bytes; + if (this->offset == this->buf_size) + { + flush(false); + } + + size_t available = this->buf_size - this->offset; + size_t bytes = (bytes_left < available ? bytes_left : available); + bytes_left -= bytes; + std::memcpy(this->inbuf + this->offset, p, bytes); + this->offset += bytes; + p += bytes; } } @@ -100,10 +100,10 @@ Pl_AES_PDF::finish() { if (this->encrypt) { - if (this->offset == this->buf_size) - { - flush(false); - } + if (this->offset == this->buf_size) + { + flush(false); + } if (! this->disable_padding) { // Pad as described in section 3.5.1 of version 1.7 of the PDF @@ -118,19 +118,19 @@ Pl_AES_PDF::finish() } else { - if (this->offset != this->buf_size) - { - // This is never supposed to happen as the output is - // always supposed to be padded. However, we have - // encountered files for which the output is not a - // multiple of the block size. In this case, pad with - // zeroes and hope for the best. - assert(this->buf_size > this->offset); - std::memset(this->inbuf + this->offset, 0, - this->buf_size - this->offset); - this->offset = this->buf_size; - } - flush(! this->disable_padding); + if (this->offset != this->buf_size) + { + // This is never supposed to happen as the output is + // always supposed to be padded. However, we have + // encountered files for which the output is not a + // multiple of the block size. In this case, pad with + // zeroes and hope for the best. + assert(this->buf_size > this->offset); + std::memset(this->inbuf + this->offset, 0, + this->buf_size - this->offset); + this->offset = this->buf_size; + } + flush(! this->disable_padding); } this->crypto->rijndael_finalize(); getNext()->finish(); @@ -141,10 +141,10 @@ Pl_AES_PDF::initializeVector() { if (use_zero_iv) { - for (unsigned int i = 0; i < this->buf_size; ++i) - { - this->cbc_block[i] = 0; - } + for (unsigned int i = 0; i < this->buf_size; ++i) + { + this->cbc_block[i] = 0; + } } else if (use_specified_iv) { @@ -152,10 +152,10 @@ Pl_AES_PDF::initializeVector() } else if (use_static_iv) { - for (unsigned int i = 0; i < this->buf_size; ++i) - { - this->cbc_block[i] = static_cast(14U * (1U + i)); - } + for (unsigned int i = 0; i < this->buf_size; ++i) + { + this->cbc_block[i] = static_cast(14U * (1U + i)); + } } else { @@ -170,35 +170,35 @@ Pl_AES_PDF::flush(bool strip_padding) if (first) { - first = false; + first = false; bool return_after_init = false; - if (this->cbc_mode) - { - if (encrypt) - { - // Set cbc_block to the initialization vector, and if - // not zero, write it to the output stream. - initializeVector(); + if (this->cbc_mode) + { + if (encrypt) + { + // Set cbc_block to the initialization vector, and if + // not zero, write it to the output stream. + initializeVector(); if (! (this->use_zero_iv || this->use_specified_iv)) { getNext()->write(this->cbc_block, this->buf_size); } - } - else if (this->use_zero_iv || this->use_specified_iv) + } + else if (this->use_zero_iv || this->use_specified_iv) { // Initialize vector with zeroes; zero vector was not // written to the beginning of the input file. initializeVector(); } else - { - // Take the first block of input as the initialization - // vector. There's nothing to write at this time. - memcpy(this->cbc_block, this->inbuf, this->buf_size); - this->offset = 0; + { + // Take the first block of input as the initialization + // vector. There's nothing to write at this time. + memcpy(this->cbc_block, this->inbuf, this->buf_size); + this->offset = 0; return_after_init = true; - } - } + } + } this->crypto->rijndael_init( encrypt, this->key.get(), key_bytes, this->cbc_mode, this->cbc_block); @@ -212,23 +212,23 @@ Pl_AES_PDF::flush(bool strip_padding) unsigned int bytes = this->buf_size; if (strip_padding) { - unsigned char last = this->outbuf[this->buf_size - 1]; - if (last <= this->buf_size) - { - bool strip = true; - for (unsigned int i = 1; i <= last; ++i) - { - if (this->outbuf[this->buf_size - i] != last) - { - strip = false; - break; - } - } - if (strip) - { - bytes -= last; - } - } + unsigned char last = this->outbuf[this->buf_size - 1]; + if (last <= this->buf_size) + { + bool strip = true; + for (unsigned int i = 1; i <= last; ++i) + { + if (this->outbuf[this->buf_size - i] != last) + { + strip = false; + break; + } + } + if (strip) + { + bytes -= last; + } + } } this->offset = 0; getNext()->write(this->outbuf, bytes); diff --git a/libqpdf/Pl_ASCII85Decoder.cc b/libqpdf/Pl_ASCII85Decoder.cc index 21926d95..c8e6d860 100644 --- a/libqpdf/Pl_ASCII85Decoder.cc +++ b/libqpdf/Pl_ASCII85Decoder.cc @@ -21,77 +21,77 @@ Pl_ASCII85Decoder::write(unsigned char* buf, size_t len) { if (eod > 1) { - return; + return; } for (size_t i = 0; i < len; ++i) { - if (eod > 1) - { - break; - } - else if (eod == 1) - { - if (buf[i] == '>') - { - flush(); - eod = 2; - } - else - { - throw std::runtime_error( - "broken end-of-data sequence in base 85 data"); - } - } - else - { - switch (buf[i]) - { - case ' ': - case '\f': - case '\v': - case '\t': - case '\r': - case '\n': - QTC::TC("libtests", "Pl_ASCII85Decoder ignore space"); - // ignore whitespace - break; + if (eod > 1) + { + break; + } + else if (eod == 1) + { + if (buf[i] == '>') + { + flush(); + eod = 2; + } + else + { + throw std::runtime_error( + "broken end-of-data sequence in base 85 data"); + } + } + else + { + switch (buf[i]) + { + case ' ': + case '\f': + case '\v': + case '\t': + case '\r': + case '\n': + QTC::TC("libtests", "Pl_ASCII85Decoder ignore space"); + // ignore whitespace + break; - case '~': - eod = 1; - break; + case '~': + eod = 1; + break; - case 'z': - if (pos != 0) - { - throw std::runtime_error( - "unexpected z during base 85 decode"); - } - else - { - QTC::TC("libtests", "Pl_ASCII85Decoder read z"); + case 'z': + if (pos != 0) + { + throw std::runtime_error( + "unexpected z during base 85 decode"); + } + else + { + QTC::TC("libtests", "Pl_ASCII85Decoder read z"); unsigned char zeroes[4]; memset(zeroes, '\0', 4); - getNext()->write(zeroes, 4); - } - break; + getNext()->write(zeroes, 4); + } + break; - default: - if ((buf[i] < 33) || (buf[i] > 117)) - { - throw std::runtime_error( - "character out of range during base 85 decode"); - } - else - { - this->inbuf[this->pos++] = buf[i]; - if (pos == 5) - { - flush(); - } - } - break; - } - } + default: + if ((buf[i] < 33) || (buf[i] > 117)) + { + throw std::runtime_error( + "character out of range during base 85 decode"); + } + else + { + this->inbuf[this->pos++] = buf[i]; + if (pos == 5) + { + flush(); + } + } + break; + } + } } } @@ -100,26 +100,26 @@ Pl_ASCII85Decoder::flush() { if (this->pos == 0) { - QTC::TC("libtests", "Pl_ASCII85Decoder no-op flush"); - return; + QTC::TC("libtests", "Pl_ASCII85Decoder no-op flush"); + return; } unsigned long lval = 0; for (int i = 0; i < 5; ++i) { - lval *= 85; - lval += (this->inbuf[i] - 33U); + lval *= 85; + lval += (this->inbuf[i] - 33U); } unsigned char outbuf[4]; memset(outbuf, 0, 4); for (int i = 3; i >= 0; --i) { - outbuf[i] = lval & 0xff; - lval >>= 8; + outbuf[i] = lval & 0xff; + lval >>= 8; } QTC::TC("libtests", "Pl_ASCII85Decoder partial flush", - (this->pos == 5) ? 0 : 1); + (this->pos == 5) ? 0 : 1); // Reset before calling getNext()->write in case that throws an // exception. auto t = this->pos - 1; diff --git a/libqpdf/Pl_ASCIIHexDecoder.cc b/libqpdf/Pl_ASCIIHexDecoder.cc index 6fe4d959..594d4ed5 100644 --- a/libqpdf/Pl_ASCIIHexDecoder.cc +++ b/libqpdf/Pl_ASCIIHexDecoder.cc @@ -24,53 +24,53 @@ Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len) { if (this->eod) { - return; + return; } for (size_t i = 0; i < len; ++i) { - char ch = static_cast(toupper(buf[i])); - switch (ch) - { - case ' ': - case '\f': - case '\v': - case '\t': - case '\r': - case '\n': - QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space"); - // ignore whitespace - break; + char ch = static_cast(toupper(buf[i])); + switch (ch) + { + case ' ': + case '\f': + case '\v': + case '\t': + case '\r': + case '\n': + QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space"); + // ignore whitespace + break; - case '>': - this->eod = true; - flush(); - break; + case '>': + this->eod = true; + flush(); + break; - default: - if (((ch >= '0') && (ch <= '9')) || - ((ch >= 'A') && (ch <= 'F'))) - { - this->inbuf[this->pos++] = ch; - if (this->pos == 2) - { - flush(); - } - } - else - { - char t[2]; - t[0] = ch; - t[1] = 0; - throw std::runtime_error( - std::string("character out of range" - " during base Hex decode: ") + t); - } - break; - } - if (this->eod) - { - break; - } + default: + if (((ch >= '0') && (ch <= '9')) || + ((ch >= 'A') && (ch <= 'F'))) + { + this->inbuf[this->pos++] = ch; + if (this->pos == 2) + { + flush(); + } + } + else + { + char t[2]; + t[0] = ch; + t[1] = 0; + throw std::runtime_error( + std::string("character out of range" + " during base Hex decode: ") + t); + } + break; + } + if (this->eod) + { + break; + } } } @@ -79,25 +79,25 @@ Pl_ASCIIHexDecoder::flush() { if (this->pos == 0) { - QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush"); - return; + QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush"); + return; } int b[2]; for (int i = 0; i < 2; ++i) { - if (this->inbuf[i] >= 'A') - { - b[i] = this->inbuf[i] - 'A' + 10; - } - else - { - b[i] = this->inbuf[i] - '0'; - } + if (this->inbuf[i] >= 'A') + { + b[i] = this->inbuf[i] - 'A' + 10; + } + else + { + b[i] = this->inbuf[i] - '0'; + } } unsigned char ch = static_cast((b[0] << 4) + b[1]); QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", - (this->pos == 2) ? 0 : 1); + (this->pos == 2) ? 0 : 1); // Reset before calling getNext()->write in case that throws an // exception. this->pos = 0; diff --git a/libqpdf/Pl_Buffer.cc b/libqpdf/Pl_Buffer.cc index 39e9b298..b38edc98 100644 --- a/libqpdf/Pl_Buffer.cc +++ b/libqpdf/Pl_Buffer.cc @@ -51,7 +51,7 @@ Pl_Buffer::write(unsigned char* buf, size_t len) if (getNext(true)) { - getNext()->write(buf, len); + getNext()->write(buf, len); } } @@ -61,7 +61,7 @@ Pl_Buffer::finish() this->m->ready = true; if (getNext(true)) { - getNext()->finish(); + getNext()->finish(); } } @@ -70,7 +70,7 @@ Pl_Buffer::getBuffer() { if (! this->m->ready) { - throw std::logic_error("Pl_Buffer::getBuffer() called when not ready"); + throw std::logic_error("Pl_Buffer::getBuffer() called when not ready"); } Buffer* b = new Buffer(this->m->total_size); @@ -94,7 +94,7 @@ Pl_Buffer::getMallocBuffer(unsigned char **buf, size_t* len) { if (! this->m->ready) { - throw std::logic_error( + throw std::logic_error( "Pl_Buffer::getMallocBuffer() called when not ready"); } diff --git a/libqpdf/Pl_Count.cc b/libqpdf/Pl_Count.cc index b245866c..65fd9e3f 100644 --- a/libqpdf/Pl_Count.cc +++ b/libqpdf/Pl_Count.cc @@ -27,9 +27,9 @@ Pl_Count::write(unsigned char* buf, size_t len) { if (len) { - this->m->count += QIntC::to_offset(len); - this->m->last_char = buf[len - 1]; - getNext()->write(buf, len); + this->m->count += QIntC::to_offset(len); + this->m->last_char = buf[len - 1]; + getNext()->write(buf, len); } } diff --git a/libqpdf/Pl_Flate.cc b/libqpdf/Pl_Flate.cc index 586c3ea6..e32c4544 100644 --- a/libqpdf/Pl_Flate.cc +++ b/libqpdf/Pl_Flate.cc @@ -61,7 +61,7 @@ Pl_Flate::Members::~Members() } Pl_Flate::Pl_Flate(char const* identifier, Pipeline* next, - action_e action, unsigned int out_bufsize_int) : + action_e action, unsigned int out_bufsize_int) : Pipeline(identifier, next), m(new Members(QIntC::to_size(out_bufsize_int), action)) { @@ -91,9 +91,9 @@ Pl_Flate::write(unsigned char* data, size_t len) { if (this->m->outbuf.get() == 0) { - throw std::logic_error( - this->identifier + - ": Pl_Flate: write() called after finish() called"); + throw std::logic_error( + this->identifier + + ": Pl_Flate: write() called after finish() called"); } // Write in chunks in case len is too big to fit in an int. @@ -103,10 +103,10 @@ Pl_Flate::write(unsigned char* data, size_t len) unsigned char* buf = data; while (bytes_left > 0) { - size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); + size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); handleData(buf, bytes, (this->m->action == a_inflate ? Z_SYNC_FLUSH : Z_NO_FLUSH)); - bytes_left -= bytes; + bytes_left -= bytes; buf += bytes; } } @@ -126,7 +126,7 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) if (! this->m->initialized) { - int err = Z_OK; + int err = Z_OK; // deflateInit and inflateInit are macros that use old-style // casts. @@ -135,21 +135,21 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wold-style-cast" #endif - if (this->m->action == a_deflate) - { - err = deflateInit(&zstream, compression_level); - } - else - { - err = inflateInit(&zstream); - } + if (this->m->action == a_deflate) + { + err = deflateInit(&zstream, compression_level); + } + else + { + err = inflateInit(&zstream); + } #if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ defined(__clang__)) # pragma GCC diagnostic pop #endif - checkError("Init", err); - this->m->initialized = true; + checkError("Init", err); + this->m->initialized = true; } int err = Z_OK; @@ -157,14 +157,14 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) bool done = false; while (! done) { - if (this->m->action == a_deflate) - { - err = deflate(&zstream, flush); - } - else - { - err = inflate(&zstream, flush); - } + if (this->m->action == a_deflate) + { + err = deflate(&zstream, flush); + } + else + { + err = inflate(&zstream, flush); + } if ((this->m->action == a_inflate) && (err != Z_OK) && zstream.msg && (strcmp(zstream.msg, "incorrect data check") == 0)) { @@ -173,52 +173,52 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) // broken zlib streams without losing data. err = Z_STREAM_END; } - switch (err) - { - case Z_BUF_ERROR: - // Probably shouldn't be able to happen, but possible as a - // boundary condition: if the last call to inflate exactly - // filled the output buffer, it's possible that the next - // call to inflate could have nothing to do. There are PDF - // files in the wild that have this error (including at - // least one in qpdf's test suite). In some cases, we want - // to know about this, because it indicates incorrect - // compression, so call a callback if provided. + switch (err) + { + case Z_BUF_ERROR: + // Probably shouldn't be able to happen, but possible as a + // boundary condition: if the last call to inflate exactly + // filled the output buffer, it's possible that the next + // call to inflate could have nothing to do. There are PDF + // files in the wild that have this error (including at + // least one in qpdf's test suite). In some cases, we want + // to know about this, because it indicates incorrect + // compression, so call a callback if provided. this->warn( "input stream is complete but output may still be valid", err); - done = true; - break; - - case Z_STREAM_END: - done = true; - // fall through - - case Z_OK: - { - if ((zstream.avail_in == 0) && - (zstream.avail_out > 0)) - { - // There is nothing left to read, and there was - // sufficient buffer space to write everything we - // needed, so we're done for now. - done = true; - } - uLong ready = + done = true; + break; + + case Z_STREAM_END: + done = true; + // fall through + + case Z_OK: + { + if ((zstream.avail_in == 0) && + (zstream.avail_out > 0)) + { + // There is nothing left to read, and there was + // sufficient buffer space to write everything we + // needed, so we're done for now. + done = true; + } + uLong ready = QIntC::to_ulong(this->m->out_bufsize - zstream.avail_out); - if (ready > 0) - { - this->getNext()->write(this->m->outbuf.get(), ready); - zstream.next_out = this->m->outbuf.get(); - zstream.avail_out = QIntC::to_uint(this->m->out_bufsize); - } - } - break; - - default: - this->checkError("data", err); - break; - } + if (ready > 0) + { + this->getNext()->write(this->m->outbuf.get(), ready); + zstream.next_out = this->m->outbuf.get(); + zstream.avail_out = QIntC::to_uint(this->m->out_bufsize); + } + } + break; + + default: + this->checkError("data", err); + break; + } } } @@ -278,50 +278,50 @@ Pl_Flate::checkError(char const* prefix, int error_code) z_stream& zstream = *(static_cast(this->m->zdata)); if (error_code != Z_OK) { - char const* action_str = + char const* action_str = (this->m->action == a_deflate ? "deflate" : "inflate"); - std::string msg = - this->identifier + ": " + action_str + ": " + prefix + ": "; - - if (zstream.msg) - { - msg += zstream.msg; - } - else - { - switch (error_code) - { - case Z_ERRNO: - msg += "zlib system error"; - break; - - case Z_STREAM_ERROR: - msg += "zlib stream error"; - break; - - case Z_DATA_ERROR: - msg += "zlib data error"; - break; - - case Z_MEM_ERROR: - msg += "zlib memory error"; - break; - - case Z_BUF_ERROR: - msg += "zlib buffer error"; - break; - - case Z_VERSION_ERROR: - msg += "zlib version error"; - break; - - default: - msg += std::string("zlib unknown error (") + - QUtil::int_to_string(error_code) + ")"; - break; - } - } - - throw std::runtime_error(msg); + std::string msg = + this->identifier + ": " + action_str + ": " + prefix + ": "; + + if (zstream.msg) + { + msg += zstream.msg; + } + else + { + switch (error_code) + { + case Z_ERRNO: + msg += "zlib system error"; + break; + + case Z_STREAM_ERROR: + msg += "zlib stream error"; + break; + + case Z_DATA_ERROR: + msg += "zlib data error"; + break; + + case Z_MEM_ERROR: + msg += "zlib memory error"; + break; + + case Z_BUF_ERROR: + msg += "zlib buffer error"; + break; + + case Z_VERSION_ERROR: + msg += "zlib version error"; + break; + + default: + msg += std::string("zlib unknown error (") + + QUtil::int_to_string(error_code) + ")"; + break; + } + } + + throw std::runtime_error(msg); } } diff --git a/libqpdf/Pl_LZWDecoder.cc b/libqpdf/Pl_LZWDecoder.cc index 81069da6..bace3854 100644 --- a/libqpdf/Pl_LZWDecoder.cc +++ b/libqpdf/Pl_LZWDecoder.cc @@ -8,7 +8,7 @@ #include Pl_LZWDecoder::Pl_LZWDecoder(char const* identifier, Pipeline* next, - bool early_code_change) : + bool early_code_change) : Pipeline(identifier, next), code_size(9), next(0), @@ -31,16 +31,16 @@ Pl_LZWDecoder::write(unsigned char* bytes, size_t len) { for (size_t i = 0; i < len; ++i) { - this->buf[next++] = bytes[i]; - if (this->next == 3) - { - this->next = 0; - } - this->bits_available += 8; - if (this->bits_available >= this->code_size) - { - sendNextCode(); - } + this->buf[next++] = bytes[i]; + if (this->next == 3) + { + this->next = 0; + } + this->bits_available += 8; + if (this->bits_available >= this->code_size) + { + sendNextCode(); + } } } @@ -62,8 +62,8 @@ Pl_LZWDecoder::sendNextCode() unsigned int bits_from_low = 0; if (bits_from_med > 8) { - bits_from_low = bits_from_med - 8; - bits_from_med = 8; + bits_from_low = bits_from_med - 8; + bits_from_med = 8; } unsigned int high_mask = (1U << bits_from_high) - 1U; unsigned int med_mask = 0xff - ((1U << (8 - bits_from_med)) - 1U); @@ -73,21 +73,21 @@ Pl_LZWDecoder::sendNextCode() code += ((this->buf[med] & med_mask) >> (8 - bits_from_med)); if (bits_from_low) { - code <<= bits_from_low; - code += ((this->buf[low] & low_mask) >> (8 - bits_from_low)); - this->byte_pos = low; - this->bit_pos = bits_from_low; + code <<= bits_from_low; + code += ((this->buf[low] & low_mask) >> (8 - bits_from_low)); + this->byte_pos = low; + this->bit_pos = bits_from_low; } else { - this->byte_pos = med; - this->bit_pos = bits_from_med; + this->byte_pos = med; + this->bit_pos = bits_from_med; } if (this->bit_pos == 8) { - this->bit_pos = 0; - ++this->byte_pos; - this->byte_pos %= 3; + this->bit_pos = 0; + ++this->byte_pos; + this->byte_pos %= 3; } this->bits_available -= this->code_size; @@ -100,18 +100,18 @@ Pl_LZWDecoder::getFirstChar(unsigned int code) unsigned char result = '\0'; if (code < 256) { - result = static_cast(code); + result = static_cast(code); } else if (code > 257) { - unsigned int idx = code - 258; - if (idx >= table.size()) + unsigned int idx = code - 258; + if (idx >= table.size()) { throw std::runtime_error( "Pl_LZWDecoder::getFirstChar: table overflow"); } - Buffer& b = table.at(idx); - result = b.getBuffer()[0]; + Buffer& b = table.at(idx); + result = b.getBuffer()[0]; } else { @@ -131,21 +131,21 @@ Pl_LZWDecoder::addToTable(unsigned char next) if (this->last_code < 256) { - tmp[0] = static_cast(this->last_code); - last_data = tmp; - last_size = 1; + tmp[0] = static_cast(this->last_code); + last_data = tmp; + last_size = 1; } else if (this->last_code > 257) { - unsigned int idx = this->last_code - 258; - if (idx >= table.size()) + unsigned int idx = this->last_code - 258; + if (idx >= table.size()) { throw std::runtime_error( "Pl_LZWDecoder::addToTable: table overflow"); } - Buffer& b = table.at(idx); - last_data = b.getBuffer(); - last_size = QIntC::to_uint(b.getSize()); + Buffer& b = table.at(idx); + last_data = b.getBuffer(); + last_size = QIntC::to_uint(b.getSize()); } else { @@ -166,88 +166,88 @@ Pl_LZWDecoder::handleCode(unsigned int code) { if (this->eod) { - return; + return; } if (code == 256) { - if (! this->table.empty()) - { - QTC::TC("libtests", "Pl_LZWDecoder intermediate reset"); - } - this->table.clear(); - this->code_size = 9; + if (! this->table.empty()) + { + QTC::TC("libtests", "Pl_LZWDecoder intermediate reset"); + } + this->table.clear(); + this->code_size = 9; } else if (code == 257) { - this->eod = true; + this->eod = true; } else { - if (this->last_code != 256) - { - // Add to the table from last time. New table entry would - // be what we read last plus the first character of what - // we're reading now. - unsigned char next = '\0'; - unsigned int table_size = QIntC::to_uint(table.size()); - if (code < 256) - { - // just read < 256; last time's next was code - next = static_cast(code); - } - else if (code > 257) - { - size_t idx = code - 258; - if (idx > table_size) - { - throw std::runtime_error("LZWDecoder: bad code received"); - } - else if (idx == table_size) - { - // The encoder would have just created this entry, - // so the first character of this entry would have - // been the same as the first character of the - // last entry. - QTC::TC("libtests", "Pl_LZWDecoder last was table size"); - next = getFirstChar(this->last_code); - } - else - { - next = getFirstChar(code); - } - } - unsigned int new_idx = 258 + table_size; - if (new_idx == 4096) - { - throw std::runtime_error("LZWDecoder: table full"); - } - addToTable(next); - unsigned int change_idx = new_idx + code_change_delta; - if ((change_idx == 511) || - (change_idx == 1023) || - (change_idx == 2047)) - { - ++this->code_size; - } - } - - if (code < 256) - { - unsigned char ch = static_cast(code); - getNext()->write(&ch, 1); - } - else - { + if (this->last_code != 256) + { + // Add to the table from last time. New table entry would + // be what we read last plus the first character of what + // we're reading now. + unsigned char next = '\0'; + unsigned int table_size = QIntC::to_uint(table.size()); + if (code < 256) + { + // just read < 256; last time's next was code + next = static_cast(code); + } + else if (code > 257) + { + size_t idx = code - 258; + if (idx > table_size) + { + throw std::runtime_error("LZWDecoder: bad code received"); + } + else if (idx == table_size) + { + // The encoder would have just created this entry, + // so the first character of this entry would have + // been the same as the first character of the + // last entry. + QTC::TC("libtests", "Pl_LZWDecoder last was table size"); + next = getFirstChar(this->last_code); + } + else + { + next = getFirstChar(code); + } + } + unsigned int new_idx = 258 + table_size; + if (new_idx == 4096) + { + throw std::runtime_error("LZWDecoder: table full"); + } + addToTable(next); + unsigned int change_idx = new_idx + code_change_delta; + if ((change_idx == 511) || + (change_idx == 1023) || + (change_idx == 2047)) + { + ++this->code_size; + } + } + + if (code < 256) + { + unsigned char ch = static_cast(code); + getNext()->write(&ch, 1); + } + else + { unsigned int idx = code - 258; if (idx >= table.size()) { throw std::runtime_error( "Pl_LZWDecoder::handleCode: table overflow"); } - Buffer& b = table.at(idx); - getNext()->write(b.getBuffer(), b.getSize()); - } + Buffer& b = table.at(idx); + getNext()->write(b.getBuffer(), b.getSize()); + } } this->last_code = code; diff --git a/libqpdf/Pl_MD5.cc b/libqpdf/Pl_MD5.cc index 93a0c8a1..9bffa2a6 100644 --- a/libqpdf/Pl_MD5.cc +++ b/libqpdf/Pl_MD5.cc @@ -70,8 +70,8 @@ Pl_MD5::getHexDigest() { if (! this->enabled) { - throw std::logic_error( - "digest requested for a disabled MD5 Pipeline"); + throw std::logic_error( + "digest requested for a disabled MD5 Pipeline"); } this->in_progress = false; return this->md5.unparse(); diff --git a/libqpdf/Pl_PNGFilter.cc b/libqpdf/Pl_PNGFilter.cc index b9aa6b2b..1dca43bb 100644 --- a/libqpdf/Pl_PNGFilter.cc +++ b/libqpdf/Pl_PNGFilter.cc @@ -13,7 +13,7 @@ static int abs_diff(int a, int b) } Pl_PNGFilter::Pl_PNGFilter(char const* identifier, Pipeline* next, - action_e action, unsigned int columns, + action_e action, unsigned int columns, unsigned int samples_per_pixel, unsigned int bits_per_sample) : Pipeline(identifier, next), @@ -74,24 +74,24 @@ Pl_PNGFilter::write(unsigned char* data, size_t len) size_t offset = 0; while (len >= left) { - // finish off current row - memcpy(this->cur_row + this->pos, data + offset, left); - offset += left; - len -= left; + // finish off current row + memcpy(this->cur_row + this->pos, data + offset, left); + offset += left; + len -= left; - processRow(); + processRow(); - // Swap rows - unsigned char* t = this->prev_row; - this->prev_row = this->cur_row; - this->cur_row = t ? t : this->buf2.get(); - memset(this->cur_row, 0, this->bytes_per_row + 1); - left = this->incoming; - this->pos = 0; + // Swap rows + unsigned char* t = this->prev_row; + this->prev_row = this->cur_row; + this->cur_row = t ? t : this->buf2.get(); + memset(this->cur_row, 0, this->bytes_per_row + 1); + left = this->incoming; + this->pos = 0; } if (len) { - memcpy(this->cur_row + this->pos, data + offset, len); + memcpy(this->cur_row + this->pos, data + offset, len); } this->pos += len; } @@ -101,11 +101,11 @@ Pl_PNGFilter::processRow() { if (this->action == a_encode) { - encodeRow(); + encodeRow(); } else { - decodeRow(); + decodeRow(); } } @@ -250,16 +250,16 @@ Pl_PNGFilter::encodeRow() getNext()->write(&ch, 1); if (this->prev_row) { - for (unsigned int i = 0; i < this->bytes_per_row; ++i) - { - ch = static_cast( + for (unsigned int i = 0; i < this->bytes_per_row; ++i) + { + ch = static_cast( this->cur_row[i] - this->prev_row[i]); - getNext()->write(&ch, 1); - } + getNext()->write(&ch, 1); + } } else { - getNext()->write(this->cur_row, this->bytes_per_row); + getNext()->write(this->cur_row, this->bytes_per_row); } } @@ -268,8 +268,8 @@ Pl_PNGFilter::finish() { if (this->pos) { - // write partial row - processRow(); + // write partial row + processRow(); } this->prev_row = 0; this->cur_row = buf1.get(); diff --git a/libqpdf/Pl_QPDFTokenizer.cc b/libqpdf/Pl_QPDFTokenizer.cc index f6002df7..0fc7144c 100644 --- a/libqpdf/Pl_QPDFTokenizer.cc +++ b/libqpdf/Pl_QPDFTokenizer.cc @@ -52,7 +52,7 @@ Pl_QPDFTokenizer::finish() QPDFTokenizer::Token token = this->m->tokenizer.readToken( input, "offset " + QUtil::int_to_string(input->tell()), true); - this->m->filter->handleToken(token); + this->m->filter->handleToken(token); if (token.getType() == QPDFTokenizer::tt_eof) { break; diff --git a/libqpdf/Pl_RC4.cc b/libqpdf/Pl_RC4.cc index 26d9303f..aa4c089e 100644 --- a/libqpdf/Pl_RC4.cc +++ b/libqpdf/Pl_RC4.cc @@ -3,8 +3,8 @@ #include Pl_RC4::Pl_RC4(char const* identifier, Pipeline* next, - unsigned char const* key_data, int key_len, - size_t out_bufsize) : + unsigned char const* key_data, int key_len, + size_t out_bufsize) : Pipeline(identifier, next), out_bufsize(out_bufsize), rc4(key_data, key_len) @@ -21,9 +21,9 @@ Pl_RC4::write(unsigned char* data, size_t len) { if (this->outbuf.get() == 0) { - throw std::logic_error( - this->identifier + - ": Pl_RC4: write() called after finish() called"); + throw std::logic_error( + this->identifier + + ": Pl_RC4: write() called after finish() called"); } size_t bytes_left = len; @@ -31,13 +31,13 @@ Pl_RC4::write(unsigned char* data, size_t len) while (bytes_left > 0) { - size_t bytes = + size_t bytes = (bytes_left < this->out_bufsize ? bytes_left : out_bufsize); - bytes_left -= bytes; + bytes_left -= bytes; // lgtm[cpp/weak-cryptographic-algorithm] - rc4.process(p, bytes, outbuf.get()); - p += bytes; - getNext()->write(outbuf.get(), bytes); + rc4.process(p, bytes, outbuf.get()); + p += bytes; + getNext()->write(outbuf.get(), bytes); } } diff --git a/libqpdf/Pl_SHA2.cc b/libqpdf/Pl_SHA2.cc index 5057da45..8844eb16 100644 --- a/libqpdf/Pl_SHA2.cc +++ b/libqpdf/Pl_SHA2.cc @@ -25,7 +25,7 @@ Pl_SHA2::write(unsigned char* buf, size_t len) { if (! this->in_progress) { - this->in_progress = true; + this->in_progress = true; } // Write in chunks in case len is too big to fit in an int. @@ -35,9 +35,9 @@ Pl_SHA2::write(unsigned char* buf, size_t len) unsigned char* data = buf; while (bytes_left > 0) { - size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); + size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); this->crypto->SHA2_update(data, bytes); - bytes_left -= bytes; + bytes_left -= bytes; data += bytes; } @@ -63,8 +63,8 @@ Pl_SHA2::resetBits(int bits) { if (this->in_progress) { - throw std::logic_error( - "bit reset requested for in-progress SHA2 Pipeline"); + throw std::logic_error( + "bit reset requested for in-progress SHA2 Pipeline"); } this->crypto = QPDFCryptoProvider::getImpl(); this->crypto->SHA2_init(bits); @@ -75,8 +75,8 @@ Pl_SHA2::getRawDigest() { if (this->in_progress) { - throw std::logic_error( - "digest requested for in-progress SHA2 Pipeline"); + throw std::logic_error( + "digest requested for in-progress SHA2 Pipeline"); } return this->crypto->SHA2_digest(); } @@ -86,8 +86,8 @@ Pl_SHA2::getHexDigest() { if (this->in_progress) { - throw std::logic_error( - "digest requested for in-progress SHA2 Pipeline"); + throw std::logic_error( + "digest requested for in-progress SHA2 Pipeline"); } return QUtil::hex_encode(getRawDigest()); } diff --git a/libqpdf/Pl_StdioFile.cc b/libqpdf/Pl_StdioFile.cc index f19a84d5..e4b96a9e 100644 --- a/libqpdf/Pl_StdioFile.cc +++ b/libqpdf/Pl_StdioFile.cc @@ -31,17 +31,17 @@ Pl_StdioFile::write(unsigned char* buf, size_t len) size_t so_far = 0; while (len > 0) { - so_far = fwrite(buf, 1, len, this->m->file); - if (so_far == 0) - { - QUtil::throw_system_error( - this->identifier + ": Pl_StdioFile::write"); - } - else - { - buf += so_far; - len -= so_far; - } + so_far = fwrite(buf, 1, len, this->m->file); + if (so_far == 0) + { + QUtil::throw_system_error( + this->identifier + ": Pl_StdioFile::write"); + } + else + { + buf += so_far; + len -= so_far; + } } } @@ -51,8 +51,8 @@ Pl_StdioFile::finish() if ((fflush(this->m->file) == -1) && (errno == EBADF)) { - throw std::logic_error( - this->identifier + - ": Pl_StdioFile::finish: stream already closed"); + throw std::logic_error( + this->identifier + + ": Pl_StdioFile::finish: stream already closed"); } } diff --git a/libqpdf/Pl_TIFFPredictor.cc b/libqpdf/Pl_TIFFPredictor.cc index 5705eca3..7f12a4a1 100644 --- a/libqpdf/Pl_TIFFPredictor.cc +++ b/libqpdf/Pl_TIFFPredictor.cc @@ -56,21 +56,21 @@ Pl_TIFFPredictor::write(unsigned char* data, size_t len) size_t offset = 0; while (len >= left) { - // finish off current row - memcpy(this->cur_row.get() + this->pos, data + offset, left); - offset += left; - len -= left; + // finish off current row + memcpy(this->cur_row.get() + this->pos, data + offset, left); + offset += left; + len -= left; - processRow(); + processRow(); - // Prepare for next row - memset(this->cur_row.get(), 0, this->bytes_per_row); - left = this->bytes_per_row; - this->pos = 0; + // Prepare for next row + memset(this->cur_row.get(), 0, this->bytes_per_row); + left = this->bytes_per_row; + this->pos = 0; } if (len) { - memcpy(this->cur_row.get() + this->pos, data + offset, len); + memcpy(this->cur_row.get() + this->pos, data + offset, len); } this->pos += len; } @@ -116,8 +116,8 @@ Pl_TIFFPredictor::finish() { if (this->pos) { - // write partial row - processRow(); + // write partial row + processRow(); } this->pos = 0; memset(this->cur_row.get(), 0, this->bytes_per_row); diff --git a/libqpdf/QPDF.cc b/libqpdf/QPDF.cc index 64d98233..02a003a5 100644 --- a/libqpdf/QPDF.cc +++ b/libqpdf/QPDF.cc @@ -257,10 +257,10 @@ QPDF::~QPDF() this->m->xref_table.clear(); for (std::map::iterator iter = this->m->obj_cache.begin(); - iter != this->m->obj_cache.end(); ++iter) + iter != this->m->obj_cache.end(); ++iter) { - QPDFObject::ObjAccessor::releaseResolved( - (*iter).second.object.get()); + QPDFObject::ObjAccessor::releaseResolved( + (*iter).second.object.get()); } } @@ -283,11 +283,11 @@ QPDF::processFile(char const* description, FILE* filep, void QPDF::processMemoryFile(char const* description, - char const* buf, size_t length, - char const* password) + char const* buf, size_t length, + char const* password) { processInputSource( - PointerHolder( + PointerHolder( new BufferInputSource( description, new Buffer(QUtil::unsigned_char_pointer(buf), length), @@ -455,15 +455,15 @@ QPDF::parse(char const* password) { if (password) { - this->m->encp->provided_password = password; + this->m->encp->provided_password = password; } // Find the header anywhere in the first 1024 bytes of the file. PatternFinder hf(*this, &QPDF::findHeader); if (! this->m->file->findFirst("%PDF-", 0, 1024, hf)) { - QTC::TC("qpdf", "QPDF not a pdf file"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + QTC::TC("qpdf", "QPDF not a pdf file"); + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, "can't find PDF header")); // QPDFWriter writes files that usually require at least // version 1.2 for /FlateDecode @@ -486,12 +486,12 @@ QPDF::parse(char const* password) try { - if (xref_offset == 0) - { - QTC::TC("qpdf", "QPDF can't find startxref"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "can't find startxref"); - } + if (xref_offset == 0) + { + QTC::TC("qpdf", "QPDF can't find startxref"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, + "can't find startxref"); + } try { read_xref(xref_offset); @@ -502,22 +502,22 @@ QPDF::parse(char const* password) } catch (std::exception& e) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - std::string("error reading xref: ") + e.what()); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, + std::string("error reading xref: ") + e.what()); } } catch (QPDFExc& e) { - if (this->m->attempt_recovery) - { - reconstruct_xref(e); - QTC::TC("qpdf", "QPDF reconstructed xref table"); - } - else - { - throw e; - } + if (this->m->attempt_recovery) + { + reconstruct_xref(e); + QTC::TC("qpdf", "QPDF reconstructed xref table"); + } + else + { + throw e; + } } initializeEncryption(); @@ -544,7 +544,7 @@ QPDF::warn(QPDFExc const& e) this->m->warnings.push_back(e); if (! this->m->suppress_warnings) { - *this->m->err_stream + *this->m->err_stream << "WARNING: " << this->m->warnings.back().what() << std::endl; } @@ -555,7 +555,7 @@ QPDF::setTrailer(QPDFObjectHandle obj) { if (this->m->trailer.isInitialized()) { - return; + return; } this->m->trailer = obj; } @@ -574,26 +574,26 @@ QPDF::reconstruct_xref(QPDFExc& e) this->m->reconstructed_xref = true; warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "file is damaged")); + "file is damaged")); warn(e); warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "Attempting to reconstruct cross-reference table")); + "Attempting to reconstruct cross-reference table")); // Delete all references to type 1 (uncompressed) objects std::set to_delete; for (std::map::iterator iter = - this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) + this->m->xref_table.begin(); + iter != this->m->xref_table.end(); ++iter) { - if (((*iter).second).getType() == 1) - { - to_delete.insert((*iter).first); - } + if (((*iter).second).getType() == 1) + { + to_delete.insert((*iter).first); + } } for (std::set::iterator iter = to_delete.begin(); - iter != to_delete.end(); ++iter) + iter != to_delete.end(); ++iter) { - this->m->xref_table.erase(*iter); + this->m->xref_table.erase(*iter); } this->m->file->seek(0, SEEK_END); @@ -615,7 +615,7 @@ QPDF::reconstruct_xref(QPDFExc& e) // don't process yet -- wait until we get to the line // containing this token } - else if (t1.getType() == QPDFTokenizer::tt_integer) + else if (t1.getType() == QPDFTokenizer::tt_integer) { QPDFTokenizer::Token t2 = readToken(this->m->file, MAX_LEN); @@ -643,22 +643,22 @@ QPDF::reconstruct_xref(QPDFExc& e) { setTrailer(t); } - } + } this->m->file->seek(next_line_start, SEEK_SET); line_start = next_line_start; } if (! this->m->trailer.isInitialized()) { - // We could check the last encountered object to see if it was - // an xref stream. If so, we could try to get the trailer - // from there. This may make it possible to recover files - // with bad startxref pointers even when they have object - // streams. + // We could check the last encountered object to see if it was + // an xref stream. If so, we could try to get the trailer + // from there. This may make it possible to recover files + // with bad startxref pointers even when they have object + // streams. - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "unable to find trailer " - "dictionary while recovering damaged file"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, + "unable to find trailer " + "dictionary while recovering damaged file"); } // We could iterate through the objects looking for streams and @@ -680,7 +680,7 @@ QPDF::read_xref(qpdf_offset_t xref_offset) visited.insert(xref_offset); char buf[7]; memset(buf, 0, sizeof(buf)); - this->m->file->seek(xref_offset, SEEK_SET); + this->m->file->seek(xref_offset, SEEK_SET); // Some files miss the mark a little with startxref. We could // do a better job of searching in the neighborhood for // something that looks like either an xref table or stream, @@ -712,13 +712,13 @@ QPDF::read_xref(qpdf_offset_t xref_offset) } } - this->m->file->read(buf, sizeof(buf) - 1); + this->m->file->read(buf, sizeof(buf) - 1); // The PDF spec says xref must be followed by a line // terminator, but files exist in the wild where it is // terminated by arbitrary whitespace. if ((strncmp(buf, "xref", 4) == 0) && QUtil::is_space(buf[4])) - { + { if (skipped_space) { QTC::TC("qpdf", "QPDF xref skipped space"); @@ -738,11 +738,11 @@ QPDF::read_xref(qpdf_offset_t xref_offset) ++skip; } xref_offset = read_xrefTable(xref_offset + skip); - } - else - { - xref_offset = read_xrefStream(xref_offset); - } + } + else + { + xref_offset = read_xrefStream(xref_offset); + } if (visited.count(xref_offset) != 0) { QTC::TC("qpdf", "QPDF xref loop"); @@ -760,20 +760,20 @@ QPDF::read_xref(qpdf_offset_t xref_offset) int max_obj = 0; if (! this->m->xref_table.empty()) { - max_obj = (*(this->m->xref_table.rbegin())).first.getObj(); + max_obj = (*(this->m->xref_table.rbegin())).first.getObj(); } if (! this->m->deleted_objects.empty()) { - max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin())); + max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin())); } if ((size < 1) || (size - 1 != max_obj)) { - QTC::TC("qpdf", "QPDF xref size mismatch"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - std::string("reported number of objects (") + - QUtil::int_to_string(size) + - ") is not one plus the highest object number (" + - QUtil::int_to_string(max_obj) + ")")); + QTC::TC("qpdf", "QPDF xref size mismatch"); + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, + std::string("reported number of objects (") + + QUtil::int_to_string(size) + + ") is not one plus the highest object number (" + + QUtil::int_to_string(max_obj) + ")")); } // We no longer need the deleted_objects table, so go ahead and @@ -946,143 +946,143 @@ QPDF::read_xrefTable(qpdf_offset_t xref_offset) char linebuf[51]; memset(linebuf, 0, sizeof(linebuf)); this->m->file->read(linebuf, sizeof(linebuf) - 1); - std::string line = linebuf; + std::string line = linebuf; int obj = 0; int num = 0; int bytes = 0; if (! parse_xrefFirst(line, obj, num, bytes)) - { - QTC::TC("qpdf", "QPDF invalid xref"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref table", this->m->file->getLastOffset(), - "xref syntax invalid"); - } + { + QTC::TC("qpdf", "QPDF invalid xref"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref table", this->m->file->getLastOffset(), + "xref syntax invalid"); + } this->m->file->seek(this->m->file->getLastOffset() + bytes, SEEK_SET); - for (qpdf_offset_t i = obj; i - num < obj; ++i) - { - if (i == 0) - { - // This is needed by checkLinearization() - this->m->first_xref_item_offset = this->m->file->tell(); - } - std::string xref_entry = this->m->file->readLine(30); + for (qpdf_offset_t i = obj; i - num < obj; ++i) + { + if (i == 0) + { + // This is needed by checkLinearization() + this->m->first_xref_item_offset = this->m->file->tell(); + } + std::string xref_entry = this->m->file->readLine(30); // For xref_table, these will always be small enough to be ints - qpdf_offset_t f1 = 0; - int f2 = 0; - char type = '\0'; + qpdf_offset_t f1 = 0; + int f2 = 0; + char type = '\0'; if (! parse_xrefEntry(xref_entry, f1, f2, type)) - { - QTC::TC("qpdf", "QPDF invalid xref entry"); - throw QPDFExc( - qpdf_e_damaged_pdf, this->m->file->getName(), - "xref table", this->m->file->getLastOffset(), - "invalid xref entry (obj=" + - QUtil::int_to_string(i) + ")"); - } - if (type == 'f') - { - // Save deleted items until after we've checked the - // XRefStm, if any. - deleted_items.push_back(QPDFObjGen(toI(i), f2)); - } - else - { - insertXrefEntry(toI(i), 1, f1, f2); - } - } - qpdf_offset_t pos = this->m->file->tell(); - QPDFTokenizer::Token t = readToken(this->m->file); - if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer")) - { - done = true; - } - else - { - this->m->file->seek(pos, SEEK_SET); - } + { + QTC::TC("qpdf", "QPDF invalid xref entry"); + throw QPDFExc( + qpdf_e_damaged_pdf, this->m->file->getName(), + "xref table", this->m->file->getLastOffset(), + "invalid xref entry (obj=" + + QUtil::int_to_string(i) + ")"); + } + if (type == 'f') + { + // Save deleted items until after we've checked the + // XRefStm, if any. + deleted_items.push_back(QPDFObjGen(toI(i), f2)); + } + else + { + insertXrefEntry(toI(i), 1, f1, f2); + } + } + qpdf_offset_t pos = this->m->file->tell(); + QPDFTokenizer::Token t = readToken(this->m->file); + if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer")) + { + done = true; + } + else + { + this->m->file->seek(pos, SEEK_SET); + } } // Set offset to previous xref table if any QPDFObjectHandle cur_trailer = - readObject(this->m->file, "trailer", 0, 0, false); + readObject(this->m->file, "trailer", 0, 0, false); if (! cur_trailer.isDictionary()) { - QTC::TC("qpdf", "QPDF missing trailer"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", this->m->file->getLastOffset(), - "expected trailer dictionary"); + QTC::TC("qpdf", "QPDF missing trailer"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "", this->m->file->getLastOffset(), + "expected trailer dictionary"); } if (! this->m->trailer.isInitialized()) { - setTrailer(cur_trailer); - - if (! this->m->trailer.hasKey("/Size")) - { - QTC::TC("qpdf", "QPDF trailer lacks size"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "trailer dictionary lacks /Size key"); - } - if (! this->m->trailer.getKey("/Size").isInteger()) - { - QTC::TC("qpdf", "QPDF trailer size not integer"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "/Size key in trailer dictionary is not " - "an integer"); - } + setTrailer(cur_trailer); + + if (! this->m->trailer.hasKey("/Size")) + { + QTC::TC("qpdf", "QPDF trailer lacks size"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "trailer", this->m->file->getLastOffset(), + "trailer dictionary lacks /Size key"); + } + if (! this->m->trailer.getKey("/Size").isInteger()) + { + QTC::TC("qpdf", "QPDF trailer size not integer"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "trailer", this->m->file->getLastOffset(), + "/Size key in trailer dictionary is not " + "an integer"); + } } if (cur_trailer.hasKey("/XRefStm")) { - if (this->m->ignore_xref_streams) - { - QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer"); - } - else - { - if (cur_trailer.getKey("/XRefStm").isInteger()) - { - // Read the xref stream but disregard any return value - // -- we'll use our trailer's /Prev key instead of the - // xref stream's. - (void) read_xrefStream( - cur_trailer.getKey("/XRefStm").getIntValue()); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "invalid /XRefStm"); - } - } + if (this->m->ignore_xref_streams) + { + QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer"); + } + else + { + if (cur_trailer.getKey("/XRefStm").isInteger()) + { + // Read the xref stream but disregard any return value + // -- we'll use our trailer's /Prev key instead of the + // xref stream's. + (void) read_xrefStream( + cur_trailer.getKey("/XRefStm").getIntValue()); + } + else + { + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", xref_offset, + "invalid /XRefStm"); + } + } } // Handle any deleted items now that we've read the /XRefStm. for (std::vector::iterator iter = deleted_items.begin(); - iter != deleted_items.end(); ++iter) + iter != deleted_items.end(); ++iter) { - QPDFObjGen& og = *iter; - insertXrefEntry(og.getObj(), 0, 0, og.getGen()); + QPDFObjGen& og = *iter; + insertXrefEntry(og.getObj(), 0, 0, og.getGen()); } if (cur_trailer.hasKey("/Prev")) { - if (! cur_trailer.getKey("/Prev").isInteger()) - { - QTC::TC("qpdf", "QPDF trailer prev not integer"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "/Prev key in trailer dictionary is not " - "an integer"); - } - QTC::TC("qpdf", "QPDF prev key in trailer dictionary"); - xref_offset = cur_trailer.getKey("/Prev").getIntValue(); + if (! cur_trailer.getKey("/Prev").isInteger()) + { + QTC::TC("qpdf", "QPDF trailer prev not integer"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "trailer", this->m->file->getLastOffset(), + "/Prev key in trailer dictionary is not " + "an integer"); + } + QTC::TC("qpdf", "QPDF prev key in trailer dictionary"); + xref_offset = cur_trailer.getKey("/Prev").getIntValue(); } else { - xref_offset = 0; + xref_offset = 0; } return xref_offset; @@ -1094,31 +1094,31 @@ QPDF::read_xrefStream(qpdf_offset_t xref_offset) bool found = false; if (! this->m->ignore_xref_streams) { - int xobj; - int xgen; - QPDFObjectHandle xref_obj; - try - { - xref_obj = readObjectAtOffset( - false, xref_offset, "xref stream", -1, 0, xobj, xgen); - } - catch (QPDFExc&) - { - // ignore -- report error below - } + int xobj; + int xgen; + QPDFObjectHandle xref_obj; + try + { + xref_obj = readObjectAtOffset( + false, xref_offset, "xref stream", -1, 0, xobj, xgen); + } + catch (QPDFExc&) + { + // ignore -- report error below + } if (xref_obj.isStreamOfType("/XRef")) - { - QTC::TC("qpdf", "QPDF found xref stream"); - found = true; - xref_offset = processXRefStream(xref_offset, xref_obj); - } + { + QTC::TC("qpdf", "QPDF found xref stream"); + found = true; + xref_offset = processXRefStream(xref_offset, xref_obj); + } } if (! found) { - QTC::TC("qpdf", "QPDF can't find xref"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", xref_offset, "xref not found"); + QTC::TC("qpdf", "QPDF can't find xref"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "", xref_offset, "xref not found"); } return xref_offset; @@ -1131,17 +1131,17 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) QPDFObjectHandle W_obj = dict.getKey("/W"); QPDFObjectHandle Index_obj = dict.getKey("/Index"); if (! (W_obj.isArray() && - (W_obj.getArrayNItems() >= 3) && - W_obj.getArrayItem(0).isInteger() && - W_obj.getArrayItem(1).isInteger() && - W_obj.getArrayItem(2).isInteger() && - dict.getKey("/Size").isInteger() && - (Index_obj.isArray() || Index_obj.isNull()))) + (W_obj.getArrayNItems() >= 3) && + W_obj.getArrayItem(0).isInteger() && + W_obj.getArrayItem(1).isInteger() && + W_obj.getArrayItem(2).isInteger() && + dict.getKey("/Size").isInteger() && + (Index_obj.isArray() || Index_obj.isNull()))) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream does not have" - " proper /W and /Index keys"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", xref_offset, + "Cross-reference stream does not have" + " proper /W and /Index keys"); } int W[3]; @@ -1149,7 +1149,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).getIntValueAsInt(); + W[i] = W_obj.getArrayItem(i).getIntValueAsInt(); if (W[i] > max_bytes) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), @@ -1157,7 +1157,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) "Cross-reference stream's /W contains" " impossibly large values"); } - entry_size += toS(W[i]); + entry_size += toS(W[i]); } if (entry_size == 0) { @@ -1172,38 +1172,38 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) std::vector indx; if (Index_obj.isArray()) { - int n_index = Index_obj.getArrayNItems(); - if ((n_index % 2) || (n_index < 2)) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream's /Index has an" - " invalid number of values"); - } - for (int i = 0; i < n_index; ++i) - { - if (Index_obj.getArrayItem(i).isInteger()) - { - indx.push_back(Index_obj.getArrayItem(i).getIntValue()); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream's /Index's item " + - QUtil::int_to_string(i) + - " is not an integer"); - } - } - QTC::TC("qpdf", "QPDF xref /Index is array", - n_index == 2 ? 0 : 1); + int n_index = Index_obj.getArrayNItems(); + if ((n_index % 2) || (n_index < 2)) + { + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", xref_offset, + "Cross-reference stream's /Index has an" + " invalid number of values"); + } + for (int i = 0; i < n_index; ++i) + { + if (Index_obj.getArrayItem(i).isInteger()) + { + indx.push_back(Index_obj.getArrayItem(i).getIntValue()); + } + else + { + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", xref_offset, + "Cross-reference stream's /Index's item " + + QUtil::int_to_string(i) + + " is not an integer"); + } + } + QTC::TC("qpdf", "QPDF xref /Index is array", + n_index == 2 ? 0 : 1); } else { - QTC::TC("qpdf", "QPDF xref /Index is null"); - long long size = dict.getKey("/Size").getIntValue(); - indx.push_back(0); - indx.push_back(size); + QTC::TC("qpdf", "QPDF xref /Index is null"); + long long size = dict.getKey("/Size").getIntValue(); + indx.push_back(0); + indx.push_back(size); } size_t num_entries = 0; @@ -1219,7 +1219,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) QUtil::uint_to_string(max_num_entries) + " " + QUtil::uint_to_string(num_entries)); } - num_entries += toS(indx.at(i)); + num_entries += toS(indx.at(i)); } // entry_size and num_entries have both been validated to ensure @@ -1231,19 +1231,19 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) if (expected_size != actual_size) { - QPDFExc x(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream data has the wrong size;" - " expected = " + QUtil::uint_to_string(expected_size) + - "; actual = " + QUtil::uint_to_string(actual_size)); - if (expected_size > actual_size) - { - throw x; - } - else - { - warn(x); - } + QPDFExc x(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", xref_offset, + "Cross-reference stream data has the wrong size;" + " expected = " + QUtil::uint_to_string(expected_size) + + "; actual = " + QUtil::uint_to_string(actual_size)); + if (expected_size > actual_size) + { + throw x; + } + else + { + warn(x); + } } size_t cur_chunk = 0; @@ -1257,30 +1257,30 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) unsigned char const* data = bp->getBuffer(); for (size_t i = 0; i < num_entries; ++i) { - // Read this entry - unsigned char const* entry = data + (entry_size * i); - qpdf_offset_t fields[3]; - unsigned char const* p = entry; - for (int j = 0; j < 3; ++j) - { - fields[j] = 0; - if ((j == 0) && (W[0] == 0)) - { - QTC::TC("qpdf", "QPDF default for xref stream field 0"); - fields[0] = 1; - } - for (int k = 0; k < W[j]; ++k) - { - fields[j] <<= 8; - fields[j] += toI(*p++); - } - } - - // Get the object and generation number. The object number is - // based on /Index. The generation number is 0 unless this is - // an uncompressed object record, in which case the generation - // number appears as the third field. - int obj = toI(indx.at(cur_chunk)); + // Read this entry + unsigned char const* entry = data + (entry_size * i); + qpdf_offset_t fields[3]; + unsigned char const* p = entry; + for (int j = 0; j < 3; ++j) + { + fields[j] = 0; + if ((j == 0) && (W[0] == 0)) + { + QTC::TC("qpdf", "QPDF default for xref stream field 0"); + fields[0] = 1; + } + for (int k = 0; k < W[j]; ++k) + { + fields[j] <<= 8; + fields[j] += toI(*p++); + } + } + + // Get the object and generation number. The object number is + // based on /Index. The generation number is 0 unless this is + // an uncompressed object record, in which case the generation + // number appears as the third field. + int obj = toI(indx.at(cur_chunk)); if ((obj < 0) || ((std::numeric_limits::max() - obj) < chunk_count)) { @@ -1292,29 +1292,29 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) throw std::range_error(msg.str()); } obj += chunk_count; - ++chunk_count; - if (chunk_count >= indx.at(cur_chunk + 1)) - { - cur_chunk += 2; - chunk_count = 0; - } - - if (saw_first_compressed_object) - { - if (fields[0] != 2) - { - this->m->uncompressed_after_compressed = true; - } - } - else if (fields[0] == 2) - { - saw_first_compressed_object = true; - } - if (obj == 0) - { - // This is needed by checkLinearization() - this->m->first_xref_item_offset = xref_offset; - } + ++chunk_count; + if (chunk_count >= indx.at(cur_chunk + 1)) + { + cur_chunk += 2; + chunk_count = 0; + } + + if (saw_first_compressed_object) + { + if (fields[0] != 2) + { + this->m->uncompressed_after_compressed = true; + } + } + else if (fields[0] == 2) + { + saw_first_compressed_object = true; + } + if (obj == 0) + { + // This is needed by checkLinearization() + this->m->first_xref_item_offset = xref_offset; + } if (fields[0] == 0) { // Ignore fields[2], which we don't care about in this @@ -1323,30 +1323,30 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) // objects. fields[2] = 0; } - insertXrefEntry(obj, toI(fields[0]), + insertXrefEntry(obj, toI(fields[0]), fields[1], toI(fields[2])); } if (! this->m->trailer.isInitialized()) { - setTrailer(dict); + setTrailer(dict); } if (dict.hasKey("/Prev")) { - if (! dict.getKey("/Prev").isInteger()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", this->m->file->getLastOffset(), - "/Prev key in xref stream dictionary is not " - "an integer"); - } - QTC::TC("qpdf", "QPDF prev key in xref stream dictionary"); - xref_offset = dict.getKey("/Prev").getIntValue(); + if (! dict.getKey("/Prev").isInteger()) + { + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", this->m->file->getLastOffset(), + "/Prev key in xref stream dictionary is not " + "an integer"); + } + QTC::TC("qpdf", "QPDF prev key in xref stream dictionary"); + xref_offset = dict.getKey("/Prev").getIntValue(); } else { - xref_offset = 0; + xref_offset = 0; } return xref_offset; @@ -1367,50 +1367,50 @@ QPDF::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2, bool overwrite) // the table, it means that a later xref table has registered this // object. Disregard this one. { // private scope - int gen = (f0 == 2 ? 0 : f2); - QPDFObjGen og(obj, gen); - if (this->m->xref_table.count(og)) - { - if (overwrite) - { - QTC::TC("qpdf", "QPDF xref overwrite object"); - this->m->xref_table.erase(og); - } - else - { - QTC::TC("qpdf", "QPDF xref reused object"); - return; - } - } - if (this->m->deleted_objects.count(obj)) - { - QTC::TC("qpdf", "QPDF xref deleted object"); - return; - } + int gen = (f0 == 2 ? 0 : f2); + QPDFObjGen og(obj, gen); + if (this->m->xref_table.count(og)) + { + if (overwrite) + { + QTC::TC("qpdf", "QPDF xref overwrite object"); + this->m->xref_table.erase(og); + } + else + { + QTC::TC("qpdf", "QPDF xref reused object"); + return; + } + } + if (this->m->deleted_objects.count(obj)) + { + QTC::TC("qpdf", "QPDF xref deleted object"); + return; + } } switch (f0) { case 0: - this->m->deleted_objects.insert(obj); - break; + this->m->deleted_objects.insert(obj); + break; case 1: - // f2 is generation - QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0)); - this->m->xref_table[QPDFObjGen(obj, f2)] = QPDFXRefEntry(f0, f1, f2); - break; + // f2 is generation + QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0)); + this->m->xref_table[QPDFObjGen(obj, f2)] = QPDFXRefEntry(f0, f1, f2); + break; case 2: - this->m->xref_table[QPDFObjGen(obj, 0)] = QPDFXRefEntry(f0, f1, f2); - break; + this->m->xref_table[QPDFObjGen(obj, 0)] = QPDFXRefEntry(f0, f1, f2); + break; default: - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", this->m->file->getLastOffset(), - "unknown xref stream entry type " + - QUtil::int_to_string(f0)); - break; + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "xref stream", this->m->file->getLastOffset(), + "unknown xref stream entry type " + + QUtil::int_to_string(f0)); + break; } } @@ -1418,32 +1418,32 @@ void QPDF::showXRefTable() { for (std::map::iterator iter = - this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { - QPDFObjGen const& og = (*iter).first; - QPDFXRefEntry const& entry = (*iter).second; - *this->m->out_stream << og.getObj() << "/" << og.getGen() << ": "; - switch (entry.getType()) - { - case 1: - *this->m->out_stream + this->m->xref_table.begin(); + iter != this->m->xref_table.end(); ++iter) + { + QPDFObjGen const& og = (*iter).first; + QPDFXRefEntry const& entry = (*iter).second; + *this->m->out_stream << og.getObj() << "/" << og.getGen() << ": "; + switch (entry.getType()) + { + case 1: + *this->m->out_stream << "uncompressed; offset = " << entry.getOffset(); - break; + break; - case 2: - *this->m->out_stream + case 2: + *this->m->out_stream << "compressed; stream = " << entry.getObjStreamNumber() << ", index = " << entry.getObjStreamIndex(); - break; + break; - default: - throw std::logic_error("unknown cross-reference table type while" - " showing xref_table"); - break; - } - *this->m->out_stream << std::endl; + default: + throw std::logic_error("unknown cross-reference table type while" + " showing xref_table"); + break; + } + *this->m->out_stream << std::endl; } } @@ -1460,16 +1460,16 @@ QPDF::fixDanglingReferences(bool force) // we've previously resolved and those that we have created. std::set to_process; for (std::map::iterator iter = - this->m->obj_cache.begin(); - iter != this->m->obj_cache.end(); ++iter) + this->m->obj_cache.begin(); + iter != this->m->obj_cache.end(); ++iter) { - to_process.insert((*iter).first); + to_process.insert((*iter).first); } for (std::map::iterator iter = - this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) + this->m->xref_table.begin(); + iter != this->m->xref_table.end(); ++iter) { - to_process.insert((*iter).first); + to_process.insert((*iter).first); } // For each non-scalar item to process, put it in the queue. @@ -1551,7 +1551,7 @@ QPDF::getObjectCount() QPDFObjGen og(0, 0); if (! this->m->obj_cache.empty()) { - og = (*(this->m->obj_cache.rbegin())).first; + og = (*(this->m->obj_cache.rbegin())).first; } return toS(og.getObj()); } @@ -1564,11 +1564,11 @@ QPDF::getAllObjects() fixDanglingReferences(true); std::vector result; for (std::map::iterator iter = - this->m->obj_cache.begin(); - iter != this->m->obj_cache.end(); ++iter) + this->m->obj_cache.begin(); + iter != this->m->obj_cache.end(); ++iter) { - QPDFObjGen const& og = (*iter).first; + QPDFObjGen const& og = (*iter).first; result.push_back(QPDFObjectHandle::Factory::newIndirect( this, og.getObj(), og.getGen())); } @@ -1577,29 +1577,29 @@ QPDF::getAllObjects() void QPDF::setLastObjectDescription(std::string const& description, - int objid, int generation) + int objid, int generation) { this->m->last_object_description.clear(); if (! description.empty()) { - this->m->last_object_description += description; - if (objid > 0) - { - this->m->last_object_description += ": "; - } + this->m->last_object_description += description; + if (objid > 0) + { + this->m->last_object_description += ": "; + } } if (objid > 0) { - this->m->last_object_description += "object " + - QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation); + this->m->last_object_description += "object " + + QUtil::int_to_string(objid) + " " + + QUtil::int_to_string(generation); } } QPDFObjectHandle QPDF::readObject(PointerHolder input, - std::string const& description, - int objid, int generation, bool in_object_stream) + std::string const& description, + int objid, int generation, bool in_object_stream) { setLastObjectDescription(description, objid, generation); qpdf_offset_t offset = input->tell(); @@ -1801,14 +1801,14 @@ QPDF::findEndstream() size_t QPDF::recoverStreamLength(PointerHolder input, - int objid, int generation, + int objid, int generation, qpdf_offset_t stream_offset) { // Try to reconstruct stream length by looking for // endstream or endobj warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, stream_offset, - "attempting to recover stream length")); + this->m->last_object_description, stream_offset, + "attempting to recover stream length")); PatternFinder ef(*this, &QPDF::findEndstream); size_t length = 0; @@ -1825,40 +1825,40 @@ QPDF::recoverStreamLength(PointerHolder input, if (length) { - qpdf_offset_t this_obj_offset = 0; - QPDFObjGen this_obj(0, 0); - - // Make sure this is inside this object - for (std::map::iterator iter = - this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { - QPDFObjGen const& og = (*iter).first; - QPDFXRefEntry const& entry = (*iter).second; - if (entry.getType() == 1) - { - qpdf_offset_t obj_offset = entry.getOffset(); - if ((obj_offset > stream_offset) && - ((this_obj_offset == 0) || - (this_obj_offset > obj_offset))) - { - this_obj_offset = obj_offset; - this_obj = og; - } - } - } - if (this_obj_offset && - (this_obj.getObj() == objid) && - (this_obj.getGen() == generation)) - { - // Well, we found endstream\nendobj within the space - // allowed for this object, so we're probably in good - // shape. - } - else - { - QTC::TC("qpdf", "QPDF found wrong endstream in recovery"); - } + qpdf_offset_t this_obj_offset = 0; + QPDFObjGen this_obj(0, 0); + + // Make sure this is inside this object + for (std::map::iterator iter = + this->m->xref_table.begin(); + iter != this->m->xref_table.end(); ++iter) + { + QPDFObjGen const& og = (*iter).first; + QPDFXRefEntry const& entry = (*iter).second; + if (entry.getType() == 1) + { + qpdf_offset_t obj_offset = entry.getOffset(); + if ((obj_offset > stream_offset) && + ((this_obj_offset == 0) || + (this_obj_offset > obj_offset))) + { + this_obj_offset = obj_offset; + this_obj = og; + } + } + } + if (this_obj_offset && + (this_obj.getObj() == objid) && + (this_obj.getGen() == generation)) + { + // Well, we found endstream\nendobj within the space + // allowed for this object, so we're probably in good + // shape. + } + else + { + QTC::TC("qpdf", "QPDF found wrong endstream in recovery"); + } } if (length == 0) @@ -1889,9 +1889,9 @@ QPDF::readToken(PointerHolder input, size_t max_len) QPDFObjectHandle QPDF::readObjectAtOffset(bool try_recovery, - qpdf_offset_t offset, std::string const& description, - int exp_objid, int exp_generation, - int& objid, int& generation) + qpdf_offset_t offset, std::string const& description, + int exp_objid, int exp_generation, + int& objid, int& generation) { if (! this->m->attempt_recovery) { @@ -1907,9 +1907,9 @@ QPDF::readObjectAtOffset(bool try_recovery, if (offset == 0) { QTC::TC("qpdf", "QPDF bogus 0 offset", 0); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, 0, - "object has offset 0")); + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, 0, + "object has offset 0")); return QPDFObjectHandle::newNull(); } @@ -1929,15 +1929,15 @@ QPDF::readObjectAtOffset(bool try_recovery, try { - if (! (objidok && genok && objok)) - { - QTC::TC("qpdf", "QPDF expected n n obj"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, offset, - "expected n n obj"); - } - objid = QUtil::string_to_int(tobjid.getValue().c_str()); - generation = QUtil::string_to_int(tgen.getValue().c_str()); + if (! (objidok && genok && objok)) + { + QTC::TC("qpdf", "QPDF expected n n obj"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, offset, + "expected n n obj"); + } + objid = QUtil::string_to_int(tobjid.getValue().c_str()); + generation = QUtil::string_to_int(tgen.getValue().c_str()); if (objid == 0) { @@ -1947,11 +1947,11 @@ QPDF::readObjectAtOffset(bool try_recovery, "object with ID 0"); } - if ((exp_objid >= 0) && - (! ((objid == exp_objid) && (generation == exp_generation)))) - { - QTC::TC("qpdf", "QPDF err wrong objid/generation"); - QPDFExc e(qpdf_e_damaged_pdf, this->m->file->getName(), + if ((exp_objid >= 0) && + (! ((objid == exp_objid) && (generation == exp_generation)))) + { + QTC::TC("qpdf", "QPDF err wrong objid/generation"); + QPDFExc e(qpdf_e_damaged_pdf, this->m->file->getName(), this->m->last_object_description, offset, std::string("expected ") + QUtil::int_to_string(exp_objid) + " " + @@ -1967,100 +1967,100 @@ QPDF::readObjectAtOffset(bool try_recovery, // doesn't match. warn(e); } - } + } } catch (QPDFExc& e) { - if ((exp_objid >= 0) && try_recovery) - { - // Try again after reconstructing xref table - reconstruct_xref(e); - QPDFObjGen og(exp_objid, exp_generation); - if (this->m->xref_table.count(og) && - (this->m->xref_table[og].getType() == 1)) - { - qpdf_offset_t new_offset = this->m->xref_table[og].getOffset(); - QPDFObjectHandle result = readObjectAtOffset( - false, new_offset, description, - exp_objid, exp_generation, objid, generation); - QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset"); - return result; - } - else - { - QTC::TC("qpdf", "QPDF object gone after xref reconstruction"); - warn(QPDFExc( - qpdf_e_damaged_pdf, this->m->file->getName(), - "", 0, - std::string( - "object " + - QUtil::int_to_string(exp_objid) + - " " + - QUtil::int_to_string(exp_generation) + - " not found in file after regenerating" - " cross reference table"))); - return QPDFObjectHandle::newNull(); - } - } - else - { - throw e; - } + if ((exp_objid >= 0) && try_recovery) + { + // Try again after reconstructing xref table + reconstruct_xref(e); + QPDFObjGen og(exp_objid, exp_generation); + if (this->m->xref_table.count(og) && + (this->m->xref_table[og].getType() == 1)) + { + qpdf_offset_t new_offset = this->m->xref_table[og].getOffset(); + QPDFObjectHandle result = readObjectAtOffset( + false, new_offset, description, + exp_objid, exp_generation, objid, generation); + QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset"); + return result; + } + else + { + QTC::TC("qpdf", "QPDF object gone after xref reconstruction"); + warn(QPDFExc( + qpdf_e_damaged_pdf, this->m->file->getName(), + "", 0, + std::string( + "object " + + QUtil::int_to_string(exp_objid) + + " " + + QUtil::int_to_string(exp_generation) + + " not found in file after regenerating" + " cross reference table"))); + return QPDFObjectHandle::newNull(); + } + } + else + { + throw e; + } } QPDFObjectHandle oh = readObject( - this->m->file, description, objid, generation, false); + this->m->file, description, objid, generation, false); if (! (readToken(this->m->file) == - QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj"))) + QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj"))) { - QTC::TC("qpdf", "QPDF err expected endobj"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, + QTC::TC("qpdf", "QPDF err expected endobj"); + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, this->m->file->getLastOffset(), - "expected endobj")); + "expected endobj")); } QPDFObjGen og(objid, generation); if (! this->m->obj_cache.count(og)) { - // Store the object in the cache here so it gets cached - // whether we first know the offset or whether we first know - // the object ID and generation (in which we case we would get - // here through resolve). - - // Determine the end offset of this object before and after - // white space. We use these numbers to validate - // linearization hint tables. Offsets and lengths of objects - // may imply the end of an object to be anywhere between these - // values. - qpdf_offset_t end_before_space = this->m->file->tell(); - - // skip over spaces - while (true) - { - char ch; - if (this->m->file->read(&ch, 1)) - { - if (! isspace(static_cast(ch))) - { - this->m->file->seek(-1, SEEK_CUR); - break; - } - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, + // Store the object in the cache here so it gets cached + // whether we first know the offset or whether we first know + // the object ID and generation (in which we case we would get + // here through resolve). + + // Determine the end offset of this object before and after + // white space. We use these numbers to validate + // linearization hint tables. Offsets and lengths of objects + // may imply the end of an object to be anywhere between these + // values. + qpdf_offset_t end_before_space = this->m->file->tell(); + + // skip over spaces + while (true) + { + char ch; + if (this->m->file->read(&ch, 1)) + { + if (! isspace(static_cast(ch))) + { + this->m->file->seek(-1, SEEK_CUR); + break; + } + } + else + { + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, this->m->file->tell(), - "EOF after endobj"); - } - } - qpdf_offset_t end_after_space = this->m->file->tell(); + "EOF after endobj"); + } + } + qpdf_offset_t end_after_space = this->m->file->tell(); - this->m->obj_cache[og] = - ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), - end_before_space, end_after_space); + this->m->obj_cache[og] = + ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), + end_before_space, end_after_space); } return oh; @@ -2102,19 +2102,19 @@ QPDF::resolve(int objid, int generation) // This can happen if an object references itself directly or // indirectly in some key that has to be resolved during // object parsing, such as stream length. - QTC::TC("qpdf", "QPDF recursion loop in resolve"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", this->m->file->getLastOffset(), - "loop detected resolving object " + - QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation))); + QTC::TC("qpdf", "QPDF recursion loop in resolve"); + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "", this->m->file->getLastOffset(), + "loop detected resolving object " + + QUtil::int_to_string(objid) + " " + + QUtil::int_to_string(generation))); return PointerHolder(new QPDF_Null); } ResolveRecorder rr(this, og); if ((! this->m->obj_cache.count(og)) && this->m->xref_table.count(og)) { - QPDFXRefEntry const& entry = this->m->xref_table[og]; + QPDFXRefEntry const& entry = this->m->xref_table[og]; try { switch (entry.getType()) @@ -2189,12 +2189,12 @@ QPDF::resolveObjectsInStream(int obj_stream_number) QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0); if (! obj_stream.isStream()) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "supposed object stream " + - QUtil::int_to_string(obj_stream_number) + - " is not a stream"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "supposed object stream " + + QUtil::int_to_string(obj_stream_number) + + " is not a stream"); } // For linearization data in the object, use the data from the @@ -2208,8 +2208,8 @@ QPDF::resolveObjectsInStream(int obj_stream_number) QPDFObjectHandle dict = obj_stream.getDict(); if (! dict.isDictionaryOfType("/ObjStm")) { - QTC::TC("qpdf", "QPDF ERR object stream with wrong type"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + QTC::TC("qpdf", "QPDF ERR object stream with wrong type"); + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), this->m->last_object_description, this->m->file->getLastOffset(), "supposed object stream " + @@ -2218,14 +2218,14 @@ QPDF::resolveObjectsInStream(int obj_stream_number) } if (! (dict.getKey("/N").isInteger() && - dict.getKey("/First").isInteger())) + dict.getKey("/First").isInteger())) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "object stream " + - QUtil::int_to_string(obj_stream_number) + - " has incorrect keys"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "object stream " + + QUtil::int_to_string(obj_stream_number) + + " has incorrect keys"); } int n = dict.getKey("/N").getIntValueAsInt(); @@ -2242,20 +2242,20 @@ QPDF::resolveObjectsInStream(int obj_stream_number) for (int i = 0; i < n; ++i) { - QPDFTokenizer::Token tnum = readToken(input); - QPDFTokenizer::Token toffset = readToken(input); - if (! ((tnum.getType() == QPDFTokenizer::tt_integer) && - (toffset.getType() == QPDFTokenizer::tt_integer))) - { - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, + QPDFTokenizer::Token tnum = readToken(input); + QPDFTokenizer::Token toffset = readToken(input); + if (! ((tnum.getType() == QPDFTokenizer::tt_integer) && + (toffset.getType() == QPDFTokenizer::tt_integer))) + { + throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), + this->m->last_object_description, input->getLastOffset(), - "expected integer in object stream header"); - } + "expected integer in object stream header"); + } - int num = QUtil::string_to_int(tnum.getValue().c_str()); - long long offset = QUtil::string_to_int(toffset.getValue().c_str()); - offsets[num] = QIntC::to_int(offset + first); + int num = QUtil::string_to_int(tnum.getValue().c_str()); + long long offset = QUtil::string_to_int(toffset.getValue().c_str()); + offsets[num] = QIntC::to_int(offset + first); } // To avoid having to read the object stream multiple times, store @@ -2264,10 +2264,10 @@ QPDF::resolveObjectsInStream(int obj_stream_number) // objects appended to the file, so it is necessary to recheck the // xref table and only cache what would actually be resolved here. for (std::map::iterator iter = offsets.begin(); - iter != offsets.end(); ++iter) + iter != offsets.end(); ++iter) { - int obj = (*iter).first; - QPDFObjGen og(obj, 0); + int obj = (*iter).first; + QPDFObjGen og(obj, 0); QPDFXRefEntry const& entry = this->m->xref_table[og]; if ((entry.getType() == 2) && (entry.getObjStreamNumber() == obj_stream_number)) @@ -2297,7 +2297,7 @@ QPDF::makeIndirectObject(QPDFObjectHandle oh) } QPDFObjGen next(max_objid + 1, 0); this->m->obj_cache[next] = - ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1); + ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1); return QPDFObjectHandle::Factory::newIndirect( this, next.getObj(), next.getGen()); } @@ -2325,9 +2325,9 @@ QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh) { if (oh.isIndirect()) { - QTC::TC("qpdf", "QPDF replaceObject called with indirect object"); - throw std::logic_error( - "QPDF::replaceObject called with indirect object handle"); + QTC::TC("qpdf", "QPDF replaceObject called with indirect object"); + throw std::logic_error( + "QPDF::replaceObject called with indirect object handle"); } // Force new object to appear in the cache @@ -2337,7 +2337,7 @@ QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh) QPDFObjGen og(objid, generation); this->m->ever_replaced_objects = true; this->m->obj_cache[og] = - ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1); + ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1); } void @@ -2399,8 +2399,8 @@ QPDF::copyForeignObject(QPDFObjectHandle foreign) if (! foreign.isIndirect()) { QTC::TC("qpdf", "QPDF copyForeign direct"); - throw std::logic_error( - "QPDF::copyForeign called with direct object handle"); + throw std::logic_error( + "QPDF::copyForeign called with direct object handle"); } QPDF* other = foreign.getOwningQPDF(); if (other == this) @@ -2509,21 +2509,21 @@ QPDF::reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, if (foreign.isArray()) { QTC::TC("qpdf", "QPDF reserve array"); - int n = foreign.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + int n = foreign.getArrayNItems(); + for (int i = 0; i < n; ++i) + { reserveObjects(foreign.getArrayItem(i), obj_copier, false); - } + } } else if (foreign.isDictionary()) { QTC::TC("qpdf", "QPDF reserve dictionary"); - std::set keys = foreign.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + std::set keys = foreign.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { reserveObjects(foreign.getKey(*iter), obj_copier, false); - } + } } else if (foreign.isStream()) { @@ -2565,27 +2565,27 @@ QPDF::replaceForeignIndirectObjects( { QTC::TC("qpdf", "QPDF replace array"); result = QPDFObjectHandle::newArray(); - int n = foreign.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + int n = foreign.getArrayNItems(); + for (int i = 0; i < n; ++i) + { result.appendItem( replaceForeignIndirectObjects( foreign.getArrayItem(i), obj_copier, false)); - } + } } else if (foreign.isDictionary()) { QTC::TC("qpdf", "QPDF replace dictionary"); result = QPDFObjectHandle::newDictionary(); - std::set keys = foreign.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + std::set keys = foreign.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { result.replaceKey( *iter, replaceForeignIndirectObjects( foreign.getKey(*iter), obj_copier, false)); - } + } } else if (foreign.isStream()) { @@ -2806,15 +2806,15 @@ void QPDF::getObjectStreamData(std::map& omap) { for (std::map::iterator iter = - this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) + this->m->xref_table.begin(); + iter != this->m->xref_table.end(); ++iter) { - QPDFObjGen const& og = (*iter).first; - QPDFXRefEntry const& entry = (*iter).second; - if (entry.getType() == 2) - { - omap[og.getObj()] = entry.getObjStreamNumber(); - } + QPDFObjGen const& og = (*iter).first; + QPDFXRefEntry const& entry = (*iter).second; + if (entry.getType() == 2) + { + omap[og.getObj()] = entry.getObjStreamNumber(); + } } } @@ -2841,69 +2841,69 @@ QPDF::getCompressibleObjGens() std::vector result; while (! queue.empty()) { - QPDFObjectHandle obj = queue.front(); - queue.pop_front(); - if (obj.isIndirect()) - { - QPDFObjGen og = obj.getObjGen(); - if (visited.count(og)) - { - QTC::TC("qpdf", "QPDF loop detected traversing objects"); - continue; - } - if (og == encryption_dict_og) - { - QTC::TC("qpdf", "QPDF exclude encryption dictionary"); - } + QPDFObjectHandle obj = queue.front(); + queue.pop_front(); + if (obj.isIndirect()) + { + QPDFObjGen og = obj.getObjGen(); + if (visited.count(og)) + { + QTC::TC("qpdf", "QPDF loop detected traversing objects"); + continue; + } + if (og == encryption_dict_og) + { + QTC::TC("qpdf", "QPDF exclude encryption dictionary"); + } else if (! (obj.isStream() || (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") && obj.hasKey("/Contents")))) - { - result.push_back(og); - } - visited.insert(og); - } - if (obj.isStream()) - { - QPDFObjectHandle dict = obj.getDict(); - std::set keys = dict.getKeys(); - for (std::set::reverse_iterator iter = keys.rbegin(); - iter != keys.rend(); ++iter) - { - std::string const& key = *iter; - QPDFObjectHandle value = dict.getKey(key); - if (key == "/Length") - { - // omit stream lengths - if (value.isIndirect()) - { - QTC::TC("qpdf", "QPDF exclude indirect length"); - } - } - else - { - queue.push_front(value); - } - } - } - else if (obj.isDictionary()) - { - std::set keys = obj.getKeys(); - for (std::set::reverse_iterator iter = keys.rbegin(); - iter != keys.rend(); ++iter) - { - queue.push_front(obj.getKey(*iter)); - } - } - else if (obj.isArray()) - { - int n = obj.getArrayNItems(); - for (int i = 1; i <= n; ++i) - { - queue.push_front(obj.getArrayItem(n - i)); - } - } + { + result.push_back(og); + } + visited.insert(og); + } + if (obj.isStream()) + { + QPDFObjectHandle dict = obj.getDict(); + std::set keys = dict.getKeys(); + for (std::set::reverse_iterator iter = keys.rbegin(); + iter != keys.rend(); ++iter) + { + std::string const& key = *iter; + QPDFObjectHandle value = dict.getKey(key); + if (key == "/Length") + { + // omit stream lengths + if (value.isIndirect()) + { + QTC::TC("qpdf", "QPDF exclude indirect length"); + } + } + else + { + queue.push_front(value); + } + } + } + else if (obj.isDictionary()) + { + std::set keys = obj.getKeys(); + for (std::set::reverse_iterator iter = keys.rbegin(); + iter != keys.rend(); ++iter) + { + queue.push_front(obj.getKey(*iter)); + } + } + else if (obj.isArray()) + { + int n = obj.getArrayNItems(); + for (int i = 1; i <= n; ++i) + { + queue.push_front(obj.getArrayItem(n - i)); + } + } } return result; @@ -2914,16 +2914,16 @@ QPDF::pipeStreamData(PointerHolder encp, PointerHolder file, QPDF& qpdf_for_warning, int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle stream_dict, - Pipeline* pipeline, + qpdf_offset_t offset, size_t length, + QPDFObjectHandle stream_dict, + Pipeline* pipeline, bool suppress_warnings, bool will_retry) { std::vector> to_delete; if (encp->encrypted) { - decryptStream(encp, file, qpdf_for_warning, + decryptStream(encp, file, qpdf_for_warning, pipeline, objid, generation, stream_dict, to_delete); } @@ -2931,23 +2931,23 @@ QPDF::pipeStreamData(PointerHolder encp, bool success = false; try { - file->seek(offset, SEEK_SET); - char buf[10240]; - while (length > 0) - { - size_t to_read = (sizeof(buf) < length ? sizeof(buf) : length); - size_t len = file->read(buf, to_read); - if (len == 0) - { - throw QPDFExc(qpdf_e_damaged_pdf, - file->getName(), - "", - file->getLastOffset(), - "unexpected EOF reading stream data"); - } - length -= len; - pipeline->write(QUtil::unsigned_char_pointer(buf), len); - } + file->seek(offset, SEEK_SET); + char buf[10240]; + while (length > 0) + { + size_t to_read = (sizeof(buf) < length ? sizeof(buf) : length); + size_t len = file->read(buf, to_read); + if (len == 0) + { + throw QPDFExc(qpdf_e_damaged_pdf, + file->getName(), + "", + file->getLastOffset(), + "unexpected EOF reading stream data"); + } + length -= len; + pipeline->write(QUtil::unsigned_char_pointer(buf), len); + } pipeline->finish(); success = true; } @@ -2995,9 +2995,9 @@ QPDF::pipeStreamData(PointerHolder encp, bool QPDF::pipeStreamData(int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle stream_dict, - Pipeline* pipeline, + qpdf_offset_t offset, size_t length, + QPDFObjectHandle stream_dict, + Pipeline* pipeline, bool suppress_warnings, bool will_retry) { diff --git a/libqpdf/QPDFArgParser.cc b/libqpdf/QPDFArgParser.cc index 9ddb120c..0e072c10 100644 --- a/libqpdf/QPDFArgParser.cc +++ b/libqpdf/QPDFArgParser.cc @@ -25,7 +25,7 @@ QPDFArgParser::Members::Members( // Remove prefix added by libtool for consistency during testing. if (strncmp(p, "lt-", 3) == 0) { - p += 3; + p += 3; } whoami = p; } diff --git a/libqpdf/QPDFCrypto_gnutls.cc b/libqpdf/QPDFCrypto_gnutls.cc index f5fdba8a..8c05f314 100644 --- a/libqpdf/QPDFCrypto_gnutls.cc +++ b/libqpdf/QPDFCrypto_gnutls.cc @@ -20,11 +20,11 @@ QPDFCrypto_gnutls::~QPDFCrypto_gnutls() { if (this->hash_ctx) { - gnutls_hash_deinit(this->hash_ctx, digest); + gnutls_hash_deinit(this->hash_ctx, digest); } if (cipher_ctx) { - gnutls_cipher_deinit(this->cipher_ctx); + gnutls_cipher_deinit(this->cipher_ctx); } this->aes_key_data = nullptr; this->aes_key_len = 0; @@ -36,8 +36,8 @@ QPDFCrypto_gnutls::provideRandomData(unsigned char* data, size_t len) int code = gnutls_rnd (GNUTLS_RND_KEY, data, len); if (code < 0) { - throw std::runtime_error( - std::string("gnutls: random number generation error: ") + + throw std::runtime_error( + std::string("gnutls: random number generation error: ") + std::string(gnutls_strerror(code))); } } @@ -50,8 +50,8 @@ QPDFCrypto_gnutls::MD5_init() if (code < 0) { this->hash_ctx = nullptr; - throw std::runtime_error( - std::string("gnutls: MD5 error: ") + + throw std::runtime_error( + std::string("gnutls: MD5 error: ") + std::string(gnutls_strerror(code))); } } @@ -84,7 +84,7 @@ QPDFCrypto_gnutls::RC4_init(unsigned char const* key_data, int key_len) RC4_finalize(); if (key_len == -1) { - key_len = QIntC::to_int( + key_len = QIntC::to_int( strlen(reinterpret_cast(key_data))); } gnutls_datum_t key; @@ -96,8 +96,8 @@ QPDFCrypto_gnutls::RC4_init(unsigned char const* key_data, int key_len) if (code < 0) { this->cipher_ctx = nullptr; - throw std::runtime_error( - std::string("gnutls: RC4 error: ") + + throw std::runtime_error( + std::string("gnutls: RC4 error: ") + std::string(gnutls_strerror(code))); } } @@ -118,8 +118,8 @@ QPDFCrypto_gnutls::RC4_finalize() { if (this->cipher_ctx) { - gnutls_cipher_deinit(this->cipher_ctx); - this->cipher_ctx = nullptr; + gnutls_cipher_deinit(this->cipher_ctx); + this->cipher_ctx = nullptr; } } @@ -148,8 +148,8 @@ QPDFCrypto_gnutls::SHA2_init(int bits) if (code < 0) { this->hash_ctx = nullptr; - throw std::runtime_error( - std::string("gnutls: SHA") + QUtil::int_to_string(bits) + + throw std::runtime_error( + std::string("gnutls: SHA") + QUtil::int_to_string(bits) + " error: " + std::string(gnutls_strerror(code))); } } @@ -278,8 +278,8 @@ QPDFCrypto_gnutls::rijndael_finalize() { if (this->cipher_ctx) { - gnutls_cipher_deinit(this->cipher_ctx); - this->cipher_ctx = nullptr; + gnutls_cipher_deinit(this->cipher_ctx); + this->cipher_ctx = nullptr; } } diff --git a/libqpdf/QPDFExc.cc b/libqpdf/QPDFExc.cc index 6215f8a6..df8ceaff 100644 --- a/libqpdf/QPDFExc.cc +++ b/libqpdf/QPDFExc.cc @@ -3,10 +3,10 @@ #include QPDFExc::QPDFExc(qpdf_error_code_e error_code, - std::string const& filename, - std::string const& object, - qpdf_offset_t offset, - std::string const& message) : + std::string const& filename, + std::string const& object, + qpdf_offset_t offset, + std::string const& message) : std::runtime_error(createWhat(filename, object, offset, message)), error_code(error_code), filename(filename), @@ -18,14 +18,14 @@ QPDFExc::QPDFExc(qpdf_error_code_e error_code, std::string QPDFExc::createWhat(std::string const& filename, - std::string const& object, - qpdf_offset_t offset, - std::string const& message) + std::string const& object, + qpdf_offset_t offset, + std::string const& message) { std::string result; if (! filename.empty()) { - result += filename; + result += filename; } if (! (object.empty() && offset == 0)) { @@ -33,18 +33,18 @@ QPDFExc::createWhat(std::string const& filename, { result += " ("; } - if (! object.empty()) - { - result += object; - if (offset > 0) - { - result += ", "; - } - } - if (offset > 0) - { - result += "offset " + QUtil::int_to_string(offset); - } + if (! object.empty()) + { + result += object; + if (offset > 0) + { + result += ", "; + } + } + if (offset > 0) + { + result += "offset " + QUtil::int_to_string(offset); + } if (! filename.empty()) { result += ")"; @@ -52,7 +52,7 @@ QPDFExc::createWhat(std::string const& filename, } if (! result.empty()) { - result += ": "; + result += ": "; } result += message; return result; diff --git a/libqpdf/QPDFObjGen.cc b/libqpdf/QPDFObjGen.cc index 341cd93a..25ec8dfd 100644 --- a/libqpdf/QPDFObjGen.cc +++ b/libqpdf/QPDFObjGen.cc @@ -18,7 +18,7 @@ bool QPDFObjGen::operator<(QPDFObjGen const& rhs) const { return ((this->obj < rhs.obj) || - ((this->obj == rhs.obj) && (this->gen < rhs.gen))); + ((this->obj == rhs.obj) && (this->gen < rhs.gen))); } bool diff --git a/libqpdf/QPDFObjectHandle.cc b/libqpdf/QPDFObjectHandle.cc index 0bb8ea4a..c2917157 100644 --- a/libqpdf/QPDFObjectHandle.cc +++ b/libqpdf/QPDFObjectHandle.cc @@ -117,7 +117,7 @@ QPDFObjectHandle::TokenFilter::write(char const* data, size_t len) } if (len) { - this->pipeline->write(QUtil::unsigned_char_pointer(data), len); + this->pipeline->write(QUtil::unsigned_char_pointer(data), len); } } @@ -241,14 +241,14 @@ QPDFObjectHandle::releaseResolved() // destruction. See comments in QPDF::~QPDF(). if (isIndirect()) { - if (this->obj.get()) - { - this->obj = 0; - } + if (this->obj.get()) + { + this->obj = 0; + } } else { - QPDFObject::ObjAccessor::releaseResolved(this->obj.get()); + QPDFObject::ObjAccessor::releaseResolved(this->obj.get()); } } @@ -304,11 +304,11 @@ class QPDFObjectTypeAccessor public: static bool check(QPDFObject* o) { - return (o && dynamic_cast(o)); + return (o && dynamic_cast(o)); } static bool check(QPDFObject const* o) { - return (o && dynamic_cast(o)); + return (o && dynamic_cast(o)); } }; @@ -377,11 +377,11 @@ QPDFObjectHandle::getNumericValue() double result = 0.0; if (isInteger()) { - result = static_cast(getIntValue()); + result = static_cast(getIntValue()); } else if (isReal()) { - result = atof(getRealValue().c_str()); + result = atof(getRealValue().c_str()); } else { @@ -1443,7 +1443,7 @@ QPDFObjectHandle::getOwningQPDF() void QPDFObjectHandle::replaceKey(std::string const& key, - QPDFObjectHandle value) + QPDFObjectHandle value) { if (isDictionary()) { @@ -1474,7 +1474,7 @@ QPDFObjectHandle::removeKey(std::string const& key) void QPDFObjectHandle::replaceOrRemoveKey(std::string const& key, - QPDFObjectHandle value) + QPDFObjectHandle value) { if (isDictionary()) { @@ -1548,7 +1548,7 @@ QPDFObjectHandle::pipeStreamData(Pipeline* p, bool* filtering_attempted, { assertStream(); return dynamic_cast(obj.get())->pipeStreamData( - p, filtering_attempted, encode_flags, decode_level, + p, filtering_attempted, encode_flags, decode_level, suppress_warnings, will_retry); } @@ -1561,14 +1561,14 @@ QPDFObjectHandle::pipeStreamData(Pipeline* p, assertStream(); bool filtering_attempted; dynamic_cast(obj.get())->pipeStreamData( - p, &filtering_attempted, encode_flags, decode_level, + p, &filtering_attempted, encode_flags, decode_level, suppress_warnings, will_retry); return filtering_attempted; } bool QPDFObjectHandle::pipeStreamData(Pipeline* p, bool filter, - bool normalize, bool compress) + bool normalize, bool compress) { int encode_flags = 0; qpdf_stream_decode_level_e decode_level = qpdf_dl_none; @@ -1589,35 +1589,35 @@ QPDFObjectHandle::pipeStreamData(Pipeline* p, bool filter, void QPDFObjectHandle::replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); dynamic_cast(obj.get())->replaceStreamData( - data, filter, decode_parms); + data, filter, decode_parms); } void QPDFObjectHandle::replaceStreamData(std::string const& data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); auto b = make_pointer_holder(data.length()); unsigned char* bp = b->getBuffer(); memcpy(bp, data.c_str(), data.length()); dynamic_cast(obj.get())->replaceStreamData( - b, filter, decode_parms); + b, filter, decode_parms); } void QPDFObjectHandle::replaceStreamData(PointerHolder provider, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); dynamic_cast(obj.get())->replaceStreamData( - provider, filter, decode_parms); + provider, filter, decode_parms); } class FunctionProvider: public QPDFObjectHandle::StreamDataProvider @@ -1662,7 +1662,7 @@ QPDFObjectHandle::replaceStreamData(std::function provider, auto sdp = PointerHolder( new FunctionProvider(provider)); dynamic_cast(obj.get())->replaceStreamData( - sdp, filter, decode_parms); + sdp, filter, decode_parms); } void @@ -1675,7 +1675,7 @@ QPDFObjectHandle::replaceStreamData( auto sdp = PointerHolder( new FunctionProvider(provider)); dynamic_cast(obj.get())->replaceStreamData( - sdp, filter, decode_parms); + sdp, filter, decode_parms); } QPDFObjGen @@ -1710,28 +1710,28 @@ QPDFObjectHandle::arrayOrStreamToStreamArray( std::vector result; if (isArray()) { - int n_items = getArrayNItems(); - for (int i = 0; i < n_items; ++i) - { - QPDFObjectHandle item = getArrayItem(i); - if (item.isStream()) + int n_items = getArrayNItems(); + for (int i = 0; i < n_items; ++i) + { + QPDFObjectHandle item = getArrayItem(i); + if (item.isStream()) { result.push_back(item); } else - { + { QTC::TC("qpdf", "QPDFObjectHandle non-stream in stream array"); warn(item.getOwningQPDF(), QPDFExc(qpdf_e_damaged_pdf, description, "item index " + QUtil::int_to_string(i) + " (from 0)", 0, "ignoring non-stream in an array of streams")); - } - } + } + } } else if (isStream()) { - result.push_back(*this); + result.push_back(*this); } else if (! isNull()) { @@ -1784,18 +1784,18 @@ QPDFObjectHandle::addPageContents(QPDFObjectHandle new_contents, bool first) std::vector content_streams; if (first) { - QTC::TC("qpdf", "QPDFObjectHandle prepend page contents"); - content_streams.push_back(new_contents); + QTC::TC("qpdf", "QPDFObjectHandle prepend page contents"); + content_streams.push_back(new_contents); } for (std::vector::iterator iter = orig_contents.begin(); - iter != orig_contents.end(); ++iter) + iter != orig_contents.end(); ++iter) { - QTC::TC("qpdf", "QPDFObjectHandle append page contents"); - content_streams.push_back(*iter); + QTC::TC("qpdf", "QPDFObjectHandle append page contents"); + content_streams.push_back(*iter); } if (! first) { - content_streams.push_back(new_contents); + content_streams.push_back(new_contents); } QPDFObjectHandle contents = QPDFObjectHandle::newArray(content_streams); @@ -1899,12 +1899,12 @@ QPDFObjectHandle::unparse() std::string result; if (this->isIndirect()) { - result = QUtil::int_to_string(this->objid) + " " + - QUtil::int_to_string(this->generation) + " R"; + result = QUtil::int_to_string(this->objid) + " " + + QUtil::int_to_string(this->generation) + " R"; } else { - result = unparseResolved(); + result = unparseResolved(); } return result; } @@ -2253,10 +2253,10 @@ QPDFObjectHandle::parseInternal(PointerHolder input, std::string& contents_string = contents_string_stack.back(); qpdf_offset_t& contents_offset = contents_offset_stack.back(); - object = QPDFObjectHandle(); - set_offset = false; + object = QPDFObjectHandle(); + set_offset = false; - QPDFTokenizer::Token token = + QPDFTokenizer::Token token = tokenizer.readToken(input, object_description, true); std::string const& token_error_message = token.getErrorMessage(); if (! token_error_message.empty()) @@ -2269,8 +2269,8 @@ QPDFObjectHandle::parseInternal(PointerHolder input, token_error_message)); } - switch (token.getType()) - { + switch (token.getType()) + { case QPDFTokenizer::tt_eof: if (! content_stream) { @@ -2286,14 +2286,14 @@ QPDFObjectHandle::parseInternal(PointerHolder input, break; case QPDFTokenizer::tt_bad: - QTC::TC("qpdf", "QPDFObjectHandle bad token in parse"); + QTC::TC("qpdf", "QPDFObjectHandle bad token in parse"); bad = true; object = newNull(); - break; + break; - case QPDFTokenizer::tt_brace_open: - case QPDFTokenizer::tt_brace_close: - QTC::TC("qpdf", "QPDFObjectHandle bad brace"); + case QPDFTokenizer::tt_brace_open: + case QPDFTokenizer::tt_brace_close: + QTC::TC("qpdf", "QPDFObjectHandle bad brace"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, @@ -2301,16 +2301,16 @@ QPDFObjectHandle::parseInternal(PointerHolder input, "treating unexpected brace token as null")); bad = true; object = newNull(); - break; + break; - case QPDFTokenizer::tt_array_close: - if (state == st_array) - { + case QPDFTokenizer::tt_array_close: + if (state == st_array) + { state = st_stop; - } - else - { - QTC::TC("qpdf", "QPDFObjectHandle bad array close"); + } + else + { + QTC::TC("qpdf", "QPDFObjectHandle bad array close"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, @@ -2318,17 +2318,17 @@ QPDFObjectHandle::parseInternal(PointerHolder input, "treating unexpected array close token as null")); bad = true; object = newNull(); - } - break; + } + break; - case QPDFTokenizer::tt_dict_close: - if (state == st_dictionary) - { + case QPDFTokenizer::tt_dict_close: + if (state == st_dictionary) + { state = st_stop; - } - else - { - QTC::TC("qpdf", "QPDFObjectHandle bad dictionary close"); + } + else + { + QTC::TC("qpdf", "QPDFObjectHandle bad dictionary close"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, @@ -2336,14 +2336,14 @@ QPDFObjectHandle::parseInternal(PointerHolder input, "unexpected dictionary close token")); bad = true; object = newNull(); - } - break; + } + break; - case QPDFTokenizer::tt_array_open: - case QPDFTokenizer::tt_dict_open: + case QPDFTokenizer::tt_array_open: + case QPDFTokenizer::tt_dict_open: if (olist_stack.size() > 500) { - QTC::TC("qpdf", "QPDFObjectHandle too deep"); + QTC::TC("qpdf", "QPDFObjectHandle too deep"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, @@ -2365,54 +2365,54 @@ QPDFObjectHandle::parseInternal(PointerHolder input, contents_string_stack.push_back(""); contents_offset_stack.push_back(-1); } - break; - - case QPDFTokenizer::tt_bool: - object = newBool((token.getValue() == "true")); - break; - - case QPDFTokenizer::tt_null: - object = newNull(); - break; - - case QPDFTokenizer::tt_integer: - object = newInteger(QUtil::string_to_ll(token.getValue().c_str())); - break; - - case QPDFTokenizer::tt_real: - object = newReal(token.getValue()); - break; - - case QPDFTokenizer::tt_name: - { - std::string name = token.getValue(); - object = newName(name); - - if (name == "/Contents") - { - b_contents = true; - } - else - { - b_contents = false; - } - } - break; - - case QPDFTokenizer::tt_word: - { - std::string const& value = token.getValue(); + break; + + case QPDFTokenizer::tt_bool: + object = newBool((token.getValue() == "true")); + break; + + case QPDFTokenizer::tt_null: + object = newNull(); + break; + + case QPDFTokenizer::tt_integer: + object = newInteger(QUtil::string_to_ll(token.getValue().c_str())); + break; + + case QPDFTokenizer::tt_real: + object = newReal(token.getValue()); + break; + + case QPDFTokenizer::tt_name: + { + std::string name = token.getValue(); + object = newName(name); + + if (name == "/Contents") + { + b_contents = true; + } + else + { + b_contents = false; + } + } + break; + + case QPDFTokenizer::tt_word: + { + std::string const& value = token.getValue(); if (content_stream) { object = QPDFObjectHandle::newOperator(value); } - else if ((value == "R") && (state != st_top) && + else if ((value == "R") && (state != st_top) && (olist.size() >= 2) && (! olist.at(olist.size() - 1).isIndirect()) && (olist.at(olist.size() - 1).isInteger()) && (! olist.at(olist.size() - 2).isIndirect()) && (olist.at(olist.size() - 2).isInteger())) - { + { if (context == 0) { QTC::TC("qpdf", "QPDFObjectHandle indirect without context"); @@ -2420,25 +2420,25 @@ QPDFObjectHandle::parseInternal(PointerHolder input, "QPDFObjectHandle::parse called without context" " on an object with indirect references"); } - // Try to resolve indirect objects - object = newIndirect( - context, - olist.at(olist.size() - 2).getIntValueAsInt(), - olist.at(olist.size() - 1).getIntValueAsInt()); - olist.remove_last(); - olist.remove_last(); - } - else if ((value == "endobj") && (state == st_top)) - { - // We just saw endobj without having read - // anything. Treat this as a null and do not move - // the input source's offset. - object = newNull(); - input->seek(input->getLastOffset(), SEEK_SET); + // Try to resolve indirect objects + object = newIndirect( + context, + olist.at(olist.size() - 2).getIntValueAsInt(), + olist.at(olist.size() - 1).getIntValueAsInt()); + olist.remove_last(); + olist.remove_last(); + } + else if ((value == "endobj") && (state == st_top)) + { + // We just saw endobj without having read + // anything. Treat this as a null and do not move + // the input source's offset. + object = newNull(); + input->seek(input->getLastOffset(), SEEK_SET); empty = true; - } - else - { + } + else + { QTC::TC("qpdf", "QPDFObjectHandle treat word as string"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), @@ -2448,13 +2448,13 @@ QPDFObjectHandle::parseInternal(PointerHolder input, " treating as string")); bad = true; object = newString(value); - } - } - break; + } + } + break; - case QPDFTokenizer::tt_string: - { - std::string val = token.getValue(); + case QPDFTokenizer::tt_string: + { + std::string val = token.getValue(); if (decrypter) { if (b_contents) @@ -2465,12 +2465,12 @@ QPDFObjectHandle::parseInternal(PointerHolder input, } decrypter->decryptString(val); } - object = QPDFObjectHandle::newString(val); - } + object = QPDFObjectHandle::newString(val); + } - break; + break; - default: + default: warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, @@ -2479,8 +2479,8 @@ QPDFObjectHandle::parseInternal(PointerHolder input, "reading object")); bad = true; object = newNull(); - break; - } + break; + } if ((! object.isInitialized()) && (! ((state == st_start) || @@ -2656,17 +2656,17 @@ QPDFObjectHandle::parseInternal(PointerHolder input, } dict[key] = val; } - if (!contents_string.empty() && - dict.count("/Type") && + if (!contents_string.empty() && + dict.count("/Type") && dict["/Type"].isNameAndEquals("/Sig") && - dict.count("/ByteRange") && - dict.count("/Contents") && - dict["/Contents"].isString()) - { - dict["/Contents"] - = QPDFObjectHandle::newString(contents_string); - dict["/Contents"].setParsedOffset(contents_offset); - } + dict.count("/ByteRange") && + dict.count("/Contents") && + dict["/Contents"].isString()) + { + dict["/Contents"] + = QPDFObjectHandle::newString(contents_string); + dict["/Contents"].setParsedOffset(contents_offset); + } object = newDictionary(dict); setObjectDescriptionFromInput( object, context, object_description, input, offset); @@ -2889,12 +2889,12 @@ QPDFObjectHandle::newDictionary( QPDFObjectHandle QPDFObjectHandle::newStream(QPDF* qpdf, int objid, int generation, - QPDFObjectHandle stream_dict, - qpdf_offset_t offset, size_t length) + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, size_t length) { QPDFObjectHandle result = QPDFObjectHandle(new QPDF_Stream( - qpdf, objid, generation, - stream_dict, offset, length)); + qpdf, objid, generation, + stream_dict, offset, length)); if (offset) { result.setParsedOffset(offset); @@ -2913,8 +2913,8 @@ QPDFObjectHandle::newStream(QPDF* qpdf) QTC::TC("qpdf", "QPDFObjectHandle newStream"); QPDFObjectHandle stream_dict = newDictionary(); QPDFObjectHandle result = qpdf->makeIndirectObject( - QPDFObjectHandle( - new QPDF_Stream(qpdf, 0, 0, stream_dict, 0, 0))); + QPDFObjectHandle( + new QPDF_Stream(qpdf, 0, 0, stream_dict, 0, 0))); result.dereference(); QPDF_Stream* stream = dynamic_cast(result.obj.get()); @@ -2946,7 +2946,7 @@ QPDFObjectHandle::newReserved(QPDF* qpdf) // Reserve a spot for this object by assigning it an object // number, but then return an unresolved handle to the object. QPDFObjectHandle reserved = qpdf->makeIndirectObject( - QPDFObjectHandle(new QPDF_Reserved())); + QPDFObjectHandle(new QPDF_Reserved())); QPDFObjectHandle result = newIndirect(qpdf, reserved.objid, reserved.generation); result.reserved = true; @@ -3003,14 +3003,14 @@ QPDFObjectHandle::shallowCopyInternal(QPDFObjectHandle& new_obj, if (isStream()) { - QTC::TC("qpdf", "QPDFObjectHandle ERR shallow copy stream"); - throw std::runtime_error( - "attempt to make a shallow copy of a stream"); + QTC::TC("qpdf", "QPDFObjectHandle ERR shallow copy stream"); + throw std::runtime_error( + "attempt to make a shallow copy of a stream"); } if (isArray()) { - QTC::TC("qpdf", "QPDFObjectHandle shallow copy array"); + QTC::TC("qpdf", "QPDFObjectHandle shallow copy array"); // No newArray for shallow copying the sparse array QPDF_Array* arr = dynamic_cast(obj.get()); new_obj = QPDFObjectHandle( @@ -3018,12 +3018,12 @@ QPDFObjectHandle::shallowCopyInternal(QPDFObjectHandle& new_obj, } else if (isDictionary()) { - QTC::TC("qpdf", "QPDFObjectHandle shallow copy dictionary"); + QTC::TC("qpdf", "QPDFObjectHandle shallow copy dictionary"); new_obj = newDictionary(getDictAsMap()); } else { - QTC::TC("qpdf", "QPDFObjectHandle shallow copy scalar"); + QTC::TC("qpdf", "QPDFObjectHandle shallow copy scalar"); new_obj = *this; } @@ -3040,27 +3040,27 @@ QPDFObjectHandle::copyObject(std::set& visited, if (isStream()) { - QTC::TC("qpdf", "QPDFObjectHandle copy stream", + QTC::TC("qpdf", "QPDFObjectHandle copy stream", stop_at_streams ? 0 : 1); if (stop_at_streams) { return; } - throw std::runtime_error( - "attempt to make a stream into a direct object"); + throw std::runtime_error( + "attempt to make a stream into a direct object"); } QPDFObjGen cur_og(this->objid, this->generation); if (cur_og.getObj() != 0) { - if (visited.count(cur_og)) - { - QTC::TC("qpdf", "QPDFObjectHandle makeDirect loop"); - throw std::runtime_error( - "loop detected while converting object from " - "indirect to direct"); - } - visited.insert(cur_og); + if (visited.count(cur_og)) + { + QTC::TC("qpdf", "QPDFObjectHandle makeDirect loop"); + throw std::runtime_error( + "loop detected while converting object from " + "indirect to direct"); + } + visited.insert(cur_og); } if (isReserved()) @@ -3079,42 +3079,42 @@ QPDFObjectHandle::copyObject(std::set& visited, if (isBool()) { - QTC::TC("qpdf", "QPDFObjectHandle clone bool"); - new_obj = PointerHolder(new QPDF_Bool(getBoolValue())); + QTC::TC("qpdf", "QPDFObjectHandle clone bool"); + new_obj = PointerHolder(new QPDF_Bool(getBoolValue())); } else if (isNull()) { - QTC::TC("qpdf", "QPDFObjectHandle clone null"); - new_obj = PointerHolder(new QPDF_Null()); + QTC::TC("qpdf", "QPDFObjectHandle clone null"); + new_obj = PointerHolder(new QPDF_Null()); } else if (isInteger()) { - QTC::TC("qpdf", "QPDFObjectHandle clone integer"); - new_obj = PointerHolder(new QPDF_Integer(getIntValue())); + QTC::TC("qpdf", "QPDFObjectHandle clone integer"); + new_obj = PointerHolder(new QPDF_Integer(getIntValue())); } else if (isReal()) { - QTC::TC("qpdf", "QPDFObjectHandle clone real"); - new_obj = PointerHolder(new QPDF_Real(getRealValue())); + QTC::TC("qpdf", "QPDFObjectHandle clone real"); + new_obj = PointerHolder(new QPDF_Real(getRealValue())); } else if (isName()) { - QTC::TC("qpdf", "QPDFObjectHandle clone name"); - new_obj = PointerHolder(new QPDF_Name(getName())); + QTC::TC("qpdf", "QPDFObjectHandle clone name"); + new_obj = PointerHolder(new QPDF_Name(getName())); } else if (isString()) { - QTC::TC("qpdf", "QPDFObjectHandle clone string"); - new_obj = PointerHolder(new QPDF_String(getStringValue())); + QTC::TC("qpdf", "QPDFObjectHandle clone string"); + new_obj = PointerHolder(new QPDF_String(getStringValue())); } else if (isArray()) { - QTC::TC("qpdf", "QPDFObjectHandle clone array"); - std::vector items; - int n = getArrayNItems(); - for (int i = 0; i < n; ++i) - { - items.push_back(getArrayItem(i)); + QTC::TC("qpdf", "QPDFObjectHandle clone array"); + std::vector items; + int n = getArrayNItems(); + for (int i = 0; i < n; ++i) + { + items.push_back(getArrayItem(i)); if ((! first_level_only) && (cross_indirect || (! items.back().isIndirect()))) { @@ -3122,18 +3122,18 @@ QPDFObjectHandle::copyObject(std::set& visited, visited, cross_indirect, first_level_only, stop_at_streams); } - } - new_obj = PointerHolder(new QPDF_Array(items)); + } + new_obj = PointerHolder(new QPDF_Array(items)); } else if (isDictionary()) { - QTC::TC("qpdf", "QPDFObjectHandle clone dictionary"); - std::set keys = getKeys(); - std::map items; - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - items[*iter] = getKey(*iter); + QTC::TC("qpdf", "QPDFObjectHandle clone dictionary"); + std::set keys = getKeys(); + std::map items; + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + items[*iter] = getKey(*iter); if ((! first_level_only) && (cross_indirect || (! items[*iter].isIndirect()))) { @@ -3141,20 +3141,20 @@ QPDFObjectHandle::copyObject(std::set& visited, visited, cross_indirect, first_level_only, stop_at_streams); } - } - new_obj = PointerHolder(new QPDF_Dictionary(items)); + } + new_obj = PointerHolder(new QPDF_Dictionary(items)); } else { - throw std::logic_error("QPDFObjectHandle::makeDirectInternal: " - "unknown object type"); + throw std::logic_error("QPDFObjectHandle::makeDirectInternal: " + "unknown object type"); } this->obj = new_obj; if (cur_og.getObj()) { - visited.erase(cur_og); + visited.erase(cur_og); } } @@ -3198,8 +3198,8 @@ QPDFObjectHandle::assertInitialized() const { if (! this->initialized) { - throw std::logic_error("operation attempted on uninitialized " - "QPDFObjectHandle"); + throw std::logic_error("operation attempted on uninitialized " + "QPDFObjectHandle"); } } @@ -3257,7 +3257,7 @@ QPDFObjectHandle::assertType(char const* type_name, bool istype) { if (! istype) { - throw std::runtime_error(std::string("operation for ") + type_name + + throw std::runtime_error(std::string("operation for ") + type_name + " attempted on object of type " + getTypeName()); } @@ -3340,7 +3340,7 @@ QPDFObjectHandle::assertIndirect() { if (! isIndirect()) { - throw std::logic_error( + throw std::logic_error( "operation for indirect object attempted on direct object"); } } @@ -3437,7 +3437,7 @@ QPDFObjectHandle::assertPageObject() { if (! isPageObject()) { - throw std::runtime_error("page operation called on non-Page object"); + throw std::runtime_error("page operation called on non-Page object"); } } @@ -3458,13 +3458,13 @@ QPDFObjectHandle::dereference() if (this->obj.get() == 0) { PointerHolder obj = QPDF::Resolver::resolve( - this->qpdf, this->objid, this->generation); - if (obj.get() == 0) - { + this->qpdf, this->objid, this->generation); + if (obj.get() == 0) + { // QPDF::resolve never returns an uninitialized object, but // check just in case. - this->obj = PointerHolder(new QPDF_Null()); - } + this->obj = PointerHolder(new QPDF_Null()); + } else if (dynamic_cast(obj.get())) { // Do not resolve diff --git a/libqpdf/QPDFPageObjectHelper.cc b/libqpdf/QPDFPageObjectHelper.cc index 87275850..6d06364a 100644 --- a/libqpdf/QPDFPageObjectHelper.cc +++ b/libqpdf/QPDFPageObjectHelper.cc @@ -430,7 +430,7 @@ QPDFPageObjectHelper::forEachXObject( queue.push_back(QPDFPageObjectHelper(obj)); } } - } + } } } diff --git a/libqpdf/QPDFTokenizer.cc b/libqpdf/QPDFTokenizer.cc index fb22317a..decbc511 100644 --- a/libqpdf/QPDFTokenizer.cc +++ b/libqpdf/QPDFTokenizer.cc @@ -240,9 +240,9 @@ QPDFTokenizer::presentCharacter(char ch) { if (this->m->state == st_token_ready) { - throw std::logic_error( - "INTERNAL ERROR: QPDF tokenizer presented character " - "while token is waiting"); + throw std::logic_error( + "INTERNAL ERROR: QPDF tokenizer presented character " + "while token is waiting"); } char orig_ch = ch; @@ -254,87 +254,87 @@ QPDFTokenizer::presentCharacter(char ch) bool handled = true; if (this->m->state == st_top) { - // Note: we specifically do not use ctype here. It is - // locale-dependent. - if (isSpace(ch)) - { + // Note: we specifically do not use ctype here. It is + // locale-dependent. + if (isSpace(ch)) + { if (this->m->include_ignorable) { this->m->state = st_in_space; this->m->val += ch; } - } - else if (ch == '%') - { - this->m->state = st_in_comment; + } + else if (ch == '%') + { + this->m->state = st_in_comment; if (this->m->include_ignorable) { this->m->val += ch; } - } - else if (ch == '(') - { - this->m->string_depth = 1; - this->m->string_ignoring_newline = false; - memset(this->m->bs_num_register, '\0', + } + else if (ch == '(') + { + this->m->string_depth = 1; + this->m->string_ignoring_newline = false; + memset(this->m->bs_num_register, '\0', sizeof(this->m->bs_num_register)); - this->m->last_char_was_bs = false; - this->m->last_char_was_cr = false; - this->m->state = st_in_string; - } - else if (ch == '<') - { - this->m->state = st_lt; - } - else if (ch == '>') - { - this->m->state = st_gt; - } - else - { - this->m->val += ch; - if (ch == ')') - { - this->m->type = tt_bad; - QTC::TC("qpdf", "QPDFTokenizer bad )"); - this->m->error_message = "unexpected )"; - this->m->state = st_token_ready; - } - else if (ch == '[') - { - this->m->type = tt_array_open; - this->m->state = st_token_ready; - } - else if (ch == ']') - { - this->m->type = tt_array_close; - this->m->state = st_token_ready; - } - else if (ch == '{') - { - this->m->type = tt_brace_open; - this->m->state = st_token_ready; - } - else if (ch == '}') - { - this->m->type = tt_brace_close; - this->m->state = st_token_ready; - } - else - { - this->m->state = st_literal; - } - } + this->m->last_char_was_bs = false; + this->m->last_char_was_cr = false; + this->m->state = st_in_string; + } + else if (ch == '<') + { + this->m->state = st_lt; + } + else if (ch == '>') + { + this->m->state = st_gt; + } + else + { + this->m->val += ch; + if (ch == ')') + { + this->m->type = tt_bad; + QTC::TC("qpdf", "QPDFTokenizer bad )"); + this->m->error_message = "unexpected )"; + this->m->state = st_token_ready; + } + else if (ch == '[') + { + this->m->type = tt_array_open; + this->m->state = st_token_ready; + } + else if (ch == ']') + { + this->m->type = tt_array_close; + this->m->state = st_token_ready; + } + else if (ch == '{') + { + this->m->type = tt_brace_open; + this->m->state = st_token_ready; + } + else if (ch == '}') + { + this->m->type = tt_brace_close; + this->m->state = st_token_ready; + } + else + { + this->m->state = st_literal; + } + } } else if (this->m->state == st_in_space) { // We only enter this state if include_ignorable is true. if (! isSpace(ch)) { - this->m->type = tt_space; - this->m->unread_char = true; - this->m->char_to_unread = ch; - this->m->state = st_token_ready; + this->m->type = tt_space; + this->m->unread_char = true; + this->m->char_to_unread = ch; + this->m->state = st_token_ready; } else { @@ -343,7 +343,7 @@ QPDFTokenizer::presentCharacter(char ch) } else if (this->m->state == st_in_comment) { - if ((ch == '\r') || (ch == '\n')) + if ((ch == '\r') || (ch == '\n')) { if (this->m->include_ignorable) { @@ -364,124 +364,124 @@ QPDFTokenizer::presentCharacter(char ch) } else if (this->m->state == st_lt) { - if (ch == '<') - { - this->m->val = "<<"; - this->m->type = tt_dict_open; - this->m->state = st_token_ready; - } - else - { - handled = false; - this->m->state = st_in_hexstring; - } + if (ch == '<') + { + this->m->val = "<<"; + this->m->type = tt_dict_open; + this->m->state = st_token_ready; + } + else + { + handled = false; + this->m->state = st_in_hexstring; + } } else if (this->m->state == st_gt) { - if (ch == '>') - { - this->m->val = ">>"; - this->m->type = tt_dict_close; - this->m->state = st_token_ready; - } - else - { - this->m->val = ">"; - this->m->type = tt_bad; - QTC::TC("qpdf", "QPDFTokenizer bad >"); - this->m->error_message = "unexpected >"; - this->m->unread_char = true; - this->m->char_to_unread = ch; - this->m->state = st_token_ready; - } + if (ch == '>') + { + this->m->val = ">>"; + this->m->type = tt_dict_close; + this->m->state = st_token_ready; + } + else + { + this->m->val = ">"; + this->m->type = tt_bad; + QTC::TC("qpdf", "QPDFTokenizer bad >"); + this->m->error_message = "unexpected >"; + this->m->unread_char = true; + this->m->char_to_unread = ch; + this->m->state = st_token_ready; + } } else if (this->m->state == st_in_string) { - if (this->m->string_ignoring_newline && (ch != '\n')) - { - this->m->string_ignoring_newline = false; - } - - size_t bs_num_count = strlen(this->m->bs_num_register); - bool ch_is_octal = ((ch >= '0') && (ch <= '7')); - if ((bs_num_count == 3) || ((bs_num_count > 0) && (! ch_is_octal))) - { - // We've accumulated \ddd. PDF Spec says to ignore - // high-order overflow. - this->m->val += static_cast( + if (this->m->string_ignoring_newline && (ch != '\n')) + { + this->m->string_ignoring_newline = false; + } + + size_t bs_num_count = strlen(this->m->bs_num_register); + bool ch_is_octal = ((ch >= '0') && (ch <= '7')); + if ((bs_num_count == 3) || ((bs_num_count > 0) && (! ch_is_octal))) + { + // We've accumulated \ddd. PDF Spec says to ignore + // high-order overflow. + this->m->val += static_cast( strtol(this->m->bs_num_register, 0, 8)); - memset(this->m->bs_num_register, '\0', + memset(this->m->bs_num_register, '\0', sizeof(this->m->bs_num_register)); - bs_num_count = 0; - } + bs_num_count = 0; + } - if (this->m->string_ignoring_newline && (ch == '\n')) - { - // ignore + if (this->m->string_ignoring_newline && (ch == '\n')) + { + // ignore this->m->string_ignoring_newline = false; - } - else if (ch_is_octal && + } + else if (ch_is_octal && (this->m->last_char_was_bs || (bs_num_count > 0))) - { - this->m->bs_num_register[bs_num_count++] = ch; - } - else if (this->m->last_char_was_bs) - { - switch (ch) - { - case 'n': - this->m->val += '\n'; - break; - - case 'r': - this->m->val += '\r'; - break; - - case 't': - this->m->val += '\t'; - break; - - case 'b': - this->m->val += '\b'; - break; - - case 'f': - this->m->val += '\f'; - break; - - case '\n': + { + this->m->bs_num_register[bs_num_count++] = ch; + } + else if (this->m->last_char_was_bs) + { + switch (ch) + { + case 'n': + this->m->val += '\n'; break; - case '\r': - this->m->string_ignoring_newline = true; - break; - - default: - // PDF spec says backslash is ignored before anything else - this->m->val += ch; - break; - } - } - else if (ch == '\\') - { - // last_char_was_bs is set/cleared below as appropriate - if (bs_num_count) - { - throw std::logic_error( - "INTERNAL ERROR: QPDFTokenizer: bs_num_count != 0 " - "when ch == '\\'"); - } - } - else if (ch == '(') - { - this->m->val += ch; - ++this->m->string_depth; - } - else if ((ch == ')') && (--this->m->string_depth == 0)) - { - this->m->type = tt_string; - this->m->state = st_token_ready; - } + case 'r': + this->m->val += '\r'; + break; + + case 't': + this->m->val += '\t'; + break; + + case 'b': + this->m->val += '\b'; + break; + + case 'f': + this->m->val += '\f'; + break; + + case '\n': + break; + + case '\r': + this->m->string_ignoring_newline = true; + break; + + default: + // PDF spec says backslash is ignored before anything else + this->m->val += ch; + break; + } + } + else if (ch == '\\') + { + // last_char_was_bs is set/cleared below as appropriate + if (bs_num_count) + { + throw std::logic_error( + "INTERNAL ERROR: QPDFTokenizer: bs_num_count != 0 " + "when ch == '\\'"); + } + } + else if (ch == '(') + { + this->m->val += ch; + ++this->m->string_depth; + } + else if ((ch == ')') && (--this->m->string_depth == 0)) + { + this->m->type = tt_string; + this->m->state = st_token_ready; + } else if (ch == '\r') { // CR by itself is converted to LF @@ -495,37 +495,37 @@ QPDFTokenizer::presentCharacter(char ch) this->m->val += ch; } } - else - { - this->m->val += ch; - } + else + { + this->m->val += ch; + } this->m->last_char_was_cr = ((! this->m->string_ignoring_newline) && (ch == '\r')); - this->m->last_char_was_bs = + this->m->last_char_was_bs = ((! this->m->last_char_was_bs) && (ch == '\\')); } else if (this->m->state == st_literal) { - if (isDelimiter(ch)) - { - // A C-locale whitespace character or delimiter terminates - // token. It is important to unread the whitespace - // character even though it is ignored since it may be the - // newline after a stream keyword. Removing it here could - // make the stream-reading code break on some files, - // though not on any files in the test suite as of this - // writing. - - this->m->type = tt_word; - this->m->unread_char = true; - this->m->char_to_unread = ch; - this->m->state = st_token_ready; - } - else - { - this->m->val += ch; - } + if (isDelimiter(ch)) + { + // A C-locale whitespace character or delimiter terminates + // token. It is important to unread the whitespace + // character even though it is ignored since it may be the + // newline after a stream keyword. Removing it here could + // make the stream-reading code break on some files, + // though not on any files in the test suite as of this + // writing. + + this->m->type = tt_word; + this->m->unread_char = true; + this->m->char_to_unread = ch; + this->m->state = st_token_ready; + } + else + { + this->m->val += ch; + } } else if (this->m->state == st_inline_image) { @@ -541,58 +541,58 @@ QPDFTokenizer::presentCharacter(char ch) } else { - handled = false; + handled = false; } if (handled) { - // okay + // okay } else if (this->m->state == st_in_hexstring) { - if (ch == '>') - { - this->m->type = tt_string; - this->m->state = st_token_ready; - if (this->m->val.length() % 2) - { - // PDF spec says odd hexstrings have implicit - // trailing 0. - this->m->val += '0'; - } - char num[3]; - num[2] = '\0'; - std::string nval; - for (unsigned int i = 0; i < this->m->val.length(); i += 2) - { - num[0] = this->m->val.at(i); - num[1] = this->m->val.at(i+1); - char nch = static_cast(strtol(num, 0, 16)); - nval += nch; - } - this->m->val = nval; - } - else if (QUtil::is_hex_digit(ch)) - { - this->m->val += ch; - } - else if (isSpace(ch)) - { - // ignore - } - else - { - this->m->type = tt_bad; - QTC::TC("qpdf", "QPDFTokenizer bad hexstring character"); - this->m->error_message = std::string("invalid character (") + - ch + ") in hexstring"; - this->m->state = st_token_ready; - } + if (ch == '>') + { + this->m->type = tt_string; + this->m->state = st_token_ready; + if (this->m->val.length() % 2) + { + // PDF spec says odd hexstrings have implicit + // trailing 0. + this->m->val += '0'; + } + char num[3]; + num[2] = '\0'; + std::string nval; + for (unsigned int i = 0; i < this->m->val.length(); i += 2) + { + num[0] = this->m->val.at(i); + num[1] = this->m->val.at(i+1); + char nch = static_cast(strtol(num, 0, 16)); + nval += nch; + } + this->m->val = nval; + } + else if (QUtil::is_hex_digit(ch)) + { + this->m->val += ch; + } + else if (isSpace(ch)) + { + // ignore + } + else + { + this->m->type = tt_bad; + QTC::TC("qpdf", "QPDFTokenizer bad hexstring character"); + this->m->error_message = std::string("invalid character (") + + ch + ") in hexstring"; + this->m->state = st_token_ready; + } } else { - throw std::logic_error( - "INTERNAL ERROR: invalid state while reading token"); + throw std::logic_error( + "INTERNAL ERROR: invalid state while reading token"); } if ((this->m->state == st_token_ready) && (this->m->type == tt_word)) @@ -603,7 +603,7 @@ QPDFTokenizer::presentCharacter(char ch) if (! (betweenTokens() || ((this->m->state == st_token_ready) && this->m->unread_char))) { - this->m->raw_val += orig_ch; + this->m->raw_val += orig_ch; } } @@ -782,9 +782,9 @@ QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch) { this->m->val = this->m->raw_val; } - token = Token(this->m->type, this->m->val, + token = Token(this->m->type, this->m->val, this->m->raw_val, this->m->error_message); - this->m->reset(); + this->m->reset(); } return ready; } @@ -811,9 +811,9 @@ QPDFTokenizer::readToken(PointerHolder input, bool presented_eof = false; while (! getToken(token, unread_char, char_to_unread)) { - char ch; - if (input->read(&ch, 1) == 0) - { + char ch; + if (input->read(&ch, 1) == 0) + { if (! presented_eof) { presentEOF(); @@ -833,14 +833,14 @@ QPDFTokenizer::readToken(PointerHolder input, throw std::logic_error( "getToken returned false after presenting EOF"); } - } - else - { - presentCharacter(ch); - if (betweenTokens() && (input->getLastOffset() == offset)) - { - ++offset; - } + } + else + { + presentCharacter(ch); + if (betweenTokens() && (input->getLastOffset() == offset)) + { + ++offset; + } if (max_len && (this->m->raw_val.length() >= max_len) && (this->m->state != st_token_ready)) { @@ -851,12 +851,12 @@ QPDFTokenizer::readToken(PointerHolder input, this->m->error_message = "exceeded allowable length while reading token"; } - } + } } if (unread_char) { - input->unreadCh(char_to_unread); + input->unreadCh(char_to_unread); } if (token.getType() != tt_eof) diff --git a/libqpdf/QPDFWriter.cc b/libqpdf/QPDFWriter.cc index 7940034e..bb568623 100644 --- a/libqpdf/QPDFWriter.cc +++ b/libqpdf/QPDFWriter.cc @@ -78,7 +78,7 @@ QPDFWriter::Members::~Members() { if (file && close_file) { - fclose(file); + fclose(file); } delete output_buffer; } @@ -113,16 +113,16 @@ QPDFWriter::setOutputFilename(char const* filename) bool close_file = false; if (filename == 0) { - description = "standard output"; - QTC::TC("qpdf", "QPDFWriter write to stdout"); - f = stdout; - QUtil::binary_stdout(); + description = "standard output"; + QTC::TC("qpdf", "QPDFWriter write to stdout"); + f = stdout; + QUtil::binary_stdout(); } else { - QTC::TC("qpdf", "QPDFWriter write to file"); - f = QUtil::safe_fopen(filename, "wb+"); - close_file = true; + QTC::TC("qpdf", "QPDFWriter write to file"); + f = QUtil::safe_fopen(filename, "wb+"); + close_file = true; } setOutputFile(description, f, close_file); } @@ -256,26 +256,26 @@ QPDFWriter::setMinimumPDFVersion(std::string const& version, bool set_extension_level = false; if (this->m->min_pdf_version.empty()) { - set_version = true; + set_version = true; set_extension_level = true; } else { - int old_major = 0; - int old_minor = 0; - int min_major = 0; - int min_minor = 0; - parseVersion(version, old_major, old_minor); - parseVersion(this->m->min_pdf_version, min_major, min_minor); + int old_major = 0; + int old_minor = 0; + int min_major = 0; + int min_minor = 0; + parseVersion(version, old_major, old_minor); + parseVersion(this->m->min_pdf_version, min_major, min_minor); int compare = compareVersions( old_major, old_minor, min_major, min_minor); - if (compare > 0) - { - QTC::TC("qpdf", "QPDFWriter increasing minimum version", + if (compare > 0) + { + QTC::TC("qpdf", "QPDFWriter increasing minimum version", extension_level == 0 ? 0 : 1); - set_version = true; + set_version = true; set_extension_level = true; - } + } else if (compare == 0) { if (extension_level > this->m->min_extension_level) @@ -283,12 +283,12 @@ QPDFWriter::setMinimumPDFVersion(std::string const& version, QTC::TC("qpdf", "QPDFWriter increasing extension level"); set_extension_level = true; } - } + } } if (set_version) { - this->m->min_pdf_version = version; + this->m->min_pdf_version = version; } if (set_extension_level) { @@ -337,7 +337,7 @@ QPDFWriter::setStaticAesIV(bool val) { if (val) { - Pl_AES_PDF::useStaticIV(); + Pl_AES_PDF::useStaticIV(); } } @@ -388,19 +388,19 @@ QPDFWriter::setR2EncryptionParameters( std::set clear; if (! allow_print) { - clear.insert(3); + clear.insert(3); } if (! allow_modify) { - clear.insert(4); + clear.insert(4); } if (! allow_extract) { - clear.insert(5); + clear.insert(5); } if (! allow_annotate) { - clear.insert(6); + clear.insert(6); } setEncryptionParameters(user_password, owner_password, 1, 2, 5, clear); @@ -414,8 +414,8 @@ QPDFWriter::setR3EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, true, true, true, true, print, modify); setEncryptionParameters(user_password, owner_password, 2, 3, 16, clear); } @@ -430,8 +430,8 @@ QPDFWriter::setR3EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, allow_assemble, allow_annotate_and_form, allow_form_filling, allow_modify_other, print, qpdf_r3m_all); @@ -447,8 +447,8 @@ QPDFWriter::setR4EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, true, true, true, true, print, modify); this->m->encrypt_use_aes = use_aes; this->m->encrypt_metadata = encrypt_metadata; @@ -466,8 +466,8 @@ QPDFWriter::setR4EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, allow_assemble, allow_annotate_and_form, allow_form_filling, allow_modify_other, print, qpdf_r3m_all); @@ -485,8 +485,8 @@ QPDFWriter::setR5EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, true, true, true, true, print, modify); this->m->encrypt_use_aes = true; this->m->encrypt_metadata = encrypt_metadata; @@ -504,8 +504,8 @@ QPDFWriter::setR5EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, allow_assemble, allow_annotate_and_form, allow_form_filling, allow_modify_other, print, qpdf_r3m_all); @@ -523,8 +523,8 @@ QPDFWriter::setR6EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, true, true, true, true, print, modify); this->m->encrypt_use_aes = true; this->m->encrypt_metadata = encrypt_metadata; @@ -542,8 +542,8 @@ QPDFWriter::setR6EncryptionParameters( { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, + clear, user_password, owner_password, + allow_accessibility, allow_extract, allow_assemble, allow_annotate_and_form, allow_form_filling, allow_modify_other, print, qpdf_r3m_all); @@ -594,11 +594,11 @@ QPDFWriter::interpretR3EncryptionParameters( if (! allow_accessibility) { // setEncryptionParameters sets this if R > 3 - clear.insert(10); + clear.insert(10); } if (! allow_extract) { - clear.insert(5); + clear.insert(5); } // Note: these switch statements all "fall through" (no break @@ -606,15 +606,15 @@ QPDFWriter::interpretR3EncryptionParameters( switch (print) { case qpdf_r3p_none: - clear.insert(3); // any printing + clear.insert(3); // any printing case qpdf_r3p_low: - clear.insert(12); // high resolution printing + clear.insert(12); // high resolution printing case qpdf_r3p_full: - break; + break; - // no default so gcc warns for missing cases + // no default so gcc warns for missing cases } // Modify options. The qpdf_r3_modify_e options control groups of @@ -627,21 +627,21 @@ QPDFWriter::interpretR3EncryptionParameters( switch (modify) { case qpdf_r3m_none: - clear.insert(11); // document assembly + clear.insert(11); // document assembly case qpdf_r3m_assembly: - clear.insert(9); // filling in form fields + clear.insert(9); // filling in form fields case qpdf_r3m_form: - clear.insert(6); // modify annotations, fill in form fields + clear.insert(6); // modify annotations, fill in form fields case qpdf_r3m_annotate: - clear.insert(4); // other modifications + clear.insert(4); // other modifications case qpdf_r3m_all: - break; + break; - // no default so gcc warns for missing cases + // no default so gcc warns for missing cases } // END NOT EXERCISED IN TEST SUITE @@ -686,9 +686,9 @@ QPDFWriter::setEncryptionParameters( int P = 0; // Create the complement of P, then invert. for (std::set::iterator iter = bits_to_clear.begin(); - iter != bits_to_clear.end(); ++iter) + iter != bits_to_clear.end(); ++iter) { - P |= (1 << ((*iter) - 1)); + P |= (1 << ((*iter) - 1)); } P = ~P; @@ -713,7 +713,7 @@ QPDFWriter::setEncryptionParameters( encryption_key, O, U, OE, UE, Perms); } setEncryptionParametersInternal( - V, R, key_len, P, O, U, OE, UE, Perms, + V, R, key_len, P, O, U, OE, UE, Perms, this->m->id1, user_password, encryption_key); } @@ -727,19 +727,19 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf) generateID(); this->m->id1 = trailer.getKey("/ID").getArrayItem(0).getStringValue(); - QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); - int V = encrypt.getKey("/V").getIntValueAsInt(); - int key_len = 5; - if (V > 1) - { - key_len = encrypt.getKey("/Length").getIntValueAsInt() / 8; - } - if (encrypt.hasKey("/EncryptMetadata") && - encrypt.getKey("/EncryptMetadata").isBool()) - { - this->m->encrypt_metadata = - encrypt.getKey("/EncryptMetadata").getBoolValue(); - } + QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); + int V = encrypt.getKey("/V").getIntValueAsInt(); + int key_len = 5; + if (V > 1) + { + key_len = encrypt.getKey("/Length").getIntValueAsInt() / 8; + } + if (encrypt.hasKey("/EncryptMetadata") && + encrypt.getKey("/EncryptMetadata").isBool()) + { + this->m->encrypt_metadata = + encrypt.getKey("/EncryptMetadata").getBoolValue(); + } if (V >= 4) { // When copying encryption parameters, use AES even if the @@ -750,8 +750,8 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf) // different values. this->m->encrypt_use_aes = true; } - QTC::TC("qpdf", "QPDFWriter copy encrypt metadata", - this->m->encrypt_metadata ? 0 : 1); + QTC::TC("qpdf", "QPDFWriter copy encrypt metadata", + this->m->encrypt_metadata ? 0 : 1); QTC::TC("qpdf", "QPDFWriter copy use_aes", this->m->encrypt_use_aes ? 0 : 1); std::string OE; @@ -761,24 +761,24 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf) if (V >= 5) { QTC::TC("qpdf", "QPDFWriter copy V5"); - OE = encrypt.getKey("/OE").getStringValue(); + OE = encrypt.getKey("/OE").getStringValue(); UE = encrypt.getKey("/UE").getStringValue(); - Perms = encrypt.getKey("/Perms").getStringValue(); + Perms = encrypt.getKey("/Perms").getStringValue(); encryption_key = qpdf.getEncryptionKey(); } - setEncryptionParametersInternal( - V, - encrypt.getKey("/R").getIntValueAsInt(), - key_len, - static_cast(encrypt.getKey("/P").getIntValue()), - encrypt.getKey("/O").getStringValue(), - encrypt.getKey("/U").getStringValue(), + setEncryptionParametersInternal( + V, + encrypt.getKey("/R").getIntValueAsInt(), + key_len, + static_cast(encrypt.getKey("/P").getIntValue()), + encrypt.getKey("/O").getStringValue(), + encrypt.getKey("/U").getStringValue(), OE, UE, Perms, - this->m->id1, // this->m->id1 == the other file's id1 - qpdf.getPaddedUserPassword(), + this->m->id1, // this->m->id1 == the other file's id1 + qpdf.getPaddedUserPassword(), encryption_key); } } @@ -789,41 +789,41 @@ QPDFWriter::disableIncompatibleEncryption(int major, int minor, { if (! this->m->encrypted) { - return; + return; } bool disable = false; if (compareVersions(major, minor, 1, 3) < 0) { - disable = true; + disable = true; } else { - int V = QUtil::string_to_int( + int V = QUtil::string_to_int( this->m->encryption_dictionary["/V"].c_str()); - int R = QUtil::string_to_int( + int R = QUtil::string_to_int( this->m->encryption_dictionary["/R"].c_str()); - if (compareVersions(major, minor, 1, 4) < 0) - { - if ((V > 1) || (R > 2)) - { - disable = true; - } - } - else if (compareVersions(major, minor, 1, 5) < 0) - { - if ((V > 2) || (R > 3)) - { - disable = true; - } - } - else if (compareVersions(major, minor, 1, 6) < 0) - { - if (this->m->encrypt_use_aes) - { - disable = true; - } - } + if (compareVersions(major, minor, 1, 4) < 0) + { + if ((V > 1) || (R > 2)) + { + disable = true; + } + } + else if (compareVersions(major, minor, 1, 5) < 0) + { + if ((V > 2) || (R > 3)) + { + disable = true; + } + } + else if (compareVersions(major, minor, 1, 6) < 0) + { + if (this->m->encrypt_use_aes) + { + disable = true; + } + } else if ((compareVersions(major, minor, 1, 7) < 0) || ((compareVersions(major, minor, 1, 7) == 0) && extension_level < 3)) @@ -836,24 +836,24 @@ QPDFWriter::disableIncompatibleEncryption(int major, int minor, } if (disable) { - QTC::TC("qpdf", "QPDFWriter forced version disabled encryption"); - this->m->encrypted = false; + QTC::TC("qpdf", "QPDFWriter forced version disabled encryption"); + this->m->encrypted = false; } } void QPDFWriter::parseVersion(std::string const& version, - int& major, int& minor) const + int& major, int& minor) const { major = QUtil::string_to_int(version.c_str()); minor = 0; size_t p = version.find('.'); if ((p != std::string::npos) && (version.length() > p)) { - minor = QUtil::string_to_int(version.substr(p + 1).c_str()); + minor = QUtil::string_to_int(version.substr(p + 1).c_str()); } std::string tmp = QUtil::int_to_string(major) + "." + - QUtil::int_to_string(minor); + QUtil::int_to_string(minor); if (tmp != version) { // The version number in the input is probably invalid. This @@ -866,27 +866,27 @@ QPDFWriter::parseVersion(std::string const& version, int QPDFWriter::compareVersions(int major1, int minor1, - int major2, int minor2) const + int major2, int minor2) const { if (major1 < major2) { - return -1; + return -1; } else if (major1 > major2) { - return 1; + return 1; } else if (minor1 < minor2) { - return -1; + return -1; } else if (minor1 > minor2) { - return 1; + return 1; } else { - return 0; + return 0; } } @@ -938,29 +938,29 @@ QPDFWriter::setEncryptionParametersInternal( if ((R >= 4) && (! this->m->encrypt_metadata)) { - this->m->encryption_dictionary["/EncryptMetadata"] = "false"; + this->m->encryption_dictionary["/EncryptMetadata"] = "false"; } if ((V == 4) || (V == 5)) { - // The spec says the value for the crypt filter key can be - // anything, and xpdf seems to agree. However, Adobe Reader - // won't open our files unless we use /StdCF. - this->m->encryption_dictionary["/StmF"] = "/StdCF"; - this->m->encryption_dictionary["/StrF"] = "/StdCF"; - std::string method = (this->m->encrypt_use_aes + // The spec says the value for the crypt filter key can be + // anything, and xpdf seems to agree. However, Adobe Reader + // won't open our files unless we use /StdCF. + this->m->encryption_dictionary["/StmF"] = "/StdCF"; + this->m->encryption_dictionary["/StrF"] = "/StdCF"; + std::string method = (this->m->encrypt_use_aes ? ((V < 5) ? "/AESV2" : "/AESV3") : "/V2"); // The PDF spec says the /Length key is optional, but the PDF // previewer on some versions of MacOS won't open encrypted // files without it. - this->m->encryption_dictionary["/CF"] = - "<< /StdCF << /AuthEvent /DocOpen /CFM " + method + + this->m->encryption_dictionary["/CF"] = + "<< /StdCF << /AuthEvent /DocOpen /CFM " + method + " /Length " + std::string((V < 5) ? "16" : "32") + " >> >>"; } this->m->encrypted = true; QPDF::EncryptionData encryption_data( - V, R, key_len, P, O, U, OE, UE, Perms, id1, this->m->encrypt_metadata); + V, R, key_len, P, O, U, OE, UE, Perms, id1, this->m->encrypt_metadata); if (V < 5) { this->m->encryption_key = QPDF::compute_encryption_key( @@ -976,7 +976,7 @@ void QPDFWriter::setDataKey(int objid) { this->m->cur_data_key = QPDF::compute_data_key( - this->m->encryption_key, objid, 0, + this->m->encryption_key, objid, 0, this->m->encrypt_use_aes, this->m->encryption_V, this->m->encryption_R); } @@ -986,8 +986,8 @@ QPDFWriter::bytesNeeded(long long n) unsigned int bytes = 0; while (n) { - ++bytes; - n >>= 8; + ++bytes; + n >>= 8; } return bytes; } @@ -1003,8 +1003,8 @@ QPDFWriter::writeBinary(unsigned long long val, unsigned int bytes) unsigned char data[sizeof(unsigned long long)]; for (unsigned int i = 0; i < bytes; ++i) { - data[bytes - i - 1] = static_cast(val & 0xff); - val >>= 8; + data[bytes - i - 1] = static_cast(val & 0xff); + val >>= 8; } this->m->pipeline->write(data, bytes); } @@ -1026,7 +1026,7 @@ QPDFWriter::writeStringQDF(std::string const& str) { if (this->m->qdf_mode) { - writeString(str); + writeString(str); } } @@ -1035,7 +1035,7 @@ QPDFWriter::writeStringNoQDF(std::string const& str) { if (! this->m->qdf_mode) { - writeString(str); + writeString(str); } } @@ -1044,7 +1044,7 @@ QPDFWriter::writePad(int nspaces) { for (int i = 0; i < nspaces; ++i) { - writeString(" "); + writeString(" "); } } @@ -1087,7 +1087,7 @@ QPDFWriter::PipelinePopper::~PipelinePopper() assert(qw->m->pipeline_stack.size() >= 2); qw->m->pipeline->finish(); assert(dynamic_cast(qw->m->pipeline_stack.back()) == - qw->m->pipeline); + qw->m->pipeline); // It might be possible for this assertion to fail if // writeLinearized exits by exception when deterministic ID, but I // don't think so. As of this writing, this is the only case in @@ -1099,18 +1099,18 @@ QPDFWriter::PipelinePopper::~PipelinePopper() qw->m->pipeline_stack.pop_back(); while (dynamic_cast(qw->m->pipeline_stack.back()) == 0) { - Pipeline* p = qw->m->pipeline_stack.back(); + Pipeline* p = qw->m->pipeline_stack.back(); if (dynamic_cast(p) == qw->m->md5_pipeline) { qw->m->md5_pipeline = 0; } - qw->m->pipeline_stack.pop_back(); - Pl_Buffer* buf = dynamic_cast(p); - if (bp && buf) - { - *bp = buf->getBufferSharedPointer(); - } - delete p; + qw->m->pipeline_stack.pop_back(); + Pl_Buffer* buf = dynamic_cast(p); + if (bp && buf) + { + *bp = buf->getBufferSharedPointer(); + } + delete p; } qw->m->pipeline = dynamic_cast(qw->m->pipeline_stack.back()); } @@ -1119,12 +1119,12 @@ void QPDFWriter::adjustAESStreamLength(size_t& length) { if (this->m->encrypted && (! this->m->cur_data_key.empty()) && - this->m->encrypt_use_aes) + this->m->encrypt_use_aes) { - // Stream length will be padded with 1 to 16 bytes to end up - // as a multiple of 16. It will also be prepended by 16 bits - // of random data. - length += 32 - (length & 0xf); + // Stream length will be padded with 1 to 16 bytes to end up + // as a multiple of 16. It will also be prepended by 16 bits + // of random data. + length += 32 - (length & 0xf); } } @@ -1133,21 +1133,21 @@ QPDFWriter::pushEncryptionFilter(PipelinePopper& pp) { if (this->m->encrypted && (! this->m->cur_data_key.empty())) { - Pipeline* p = 0; - if (this->m->encrypt_use_aes) - { - p = new Pl_AES_PDF( - "aes stream encryption", this->m->pipeline, true, - QUtil::unsigned_char_pointer(this->m->cur_data_key), + Pipeline* p = 0; + if (this->m->encrypt_use_aes) + { + p = new Pl_AES_PDF( + "aes stream encryption", this->m->pipeline, true, + QUtil::unsigned_char_pointer(this->m->cur_data_key), this->m->cur_data_key.length()); - } - else - { - p = new Pl_RC4("rc4 stream encryption", this->m->pipeline, - QUtil::unsigned_char_pointer(this->m->cur_data_key), - QIntC::to_int(this->m->cur_data_key.length())); - } - pushPipeline(p); + } + else + { + p = new Pl_RC4("rc4 stream encryption", this->m->pipeline, + QUtil::unsigned_char_pointer(this->m->cur_data_key), + QIntC::to_int(this->m->cur_data_key.length())); + } + pushPipeline(p); } // Must call this unconditionally so we can call popPipelineStack // to balance pushEncryptionFilter(). @@ -1196,7 +1196,7 @@ QPDFWriter::openObject(int objid) { if (objid == 0) { - objid = this->m->next_objid++; + objid = this->m->next_objid++; } this->m->xref[objid] = QPDFXRefEntry(1, this->m->pipeline->getCount(), 0); writeString(QUtil::int_to_string(objid)); @@ -1223,17 +1223,17 @@ QPDFWriter::assignCompressedObjectNumbers(QPDFObjGen const& og) (this->m->object_stream_to_objects.count(objid) == 0)) { // This is not an object stream. - return; + return; } // Reserve numbers for the objects that belong to this object // stream. for (std::set::iterator iter = - this->m->object_stream_to_objects[objid].begin(); - iter != this->m->object_stream_to_objects[objid].end(); - ++iter) + this->m->object_stream_to_objects[objid].begin(); + iter != this->m->object_stream_to_objects[objid].end(); + ++iter) { - this->m->obj_renumber[*iter] = this->m->next_objid++; + this->m->obj_renumber[*iter] = this->m->next_objid++; } } @@ -1264,45 +1264,45 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) return; } - QPDFObjGen og = object.getObjGen(); + QPDFObjGen og = object.getObjGen(); - if (this->m->obj_renumber.count(og) == 0) - { - if (this->m->object_to_object_stream.count(og)) - { - // This is in an object stream. Don't process it - // here. Instead, enqueue the object stream. Object - // streams always have generation 0. - int stream_id = this->m->object_to_object_stream[og]; + if (this->m->obj_renumber.count(og) == 0) + { + if (this->m->object_to_object_stream.count(og)) + { + // This is in an object stream. Don't process it + // here. Instead, enqueue the object stream. Object + // streams always have generation 0. + int stream_id = this->m->object_to_object_stream[og]; // Detect loops by storing invalid object ID 0, which // will get overwritten later. this->m->obj_renumber[og] = 0; - enqueueObject(this->m->pdf.getObjectByID(stream_id, 0)); - } - else - { - this->m->object_queue.push_back(object); - this->m->obj_renumber[og] = this->m->next_objid++; - - if ((og.getGen() == 0) && + enqueueObject(this->m->pdf.getObjectByID(stream_id, 0)); + } + else + { + this->m->object_queue.push_back(object); + this->m->obj_renumber[og] = this->m->next_objid++; + + if ((og.getGen() == 0) && this->m->object_stream_to_objects.count(og.getObj())) - { - // For linearized files, uncompressed objects go - // at end, and we take care of assigning numbers - // to them elsewhere. - if (! this->m->linearized) - { - assignCompressedObjectNumbers(og); - } - } - else if ((! this->m->direct_stream_lengths) && + { + // For linearized files, uncompressed objects go + // at end, and we take care of assigning numbers + // to them elsewhere. + if (! this->m->linearized) + { + assignCompressedObjectNumbers(og); + } + } + else if ((! this->m->direct_stream_lengths) && object.isStream()) - { - // reserve next object ID for length - ++this->m->next_objid; - } - } - } + { + // reserve next object ID for length + ++this->m->next_objid; + } + } + } else if (this->m->obj_renumber[og] == 0) { // This can happen if a specially constructed file @@ -1312,30 +1312,30 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) } else if (object.isArray()) { - int n = object.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - if (! this->m->linearized) - { - enqueueObject(object.getArrayItem(i)); - } - } + int n = object.getArrayNItems(); + for (int i = 0; i < n; ++i) + { + if (! this->m->linearized) + { + enqueueObject(object.getArrayItem(i)); + } + } } else if (object.isDictionary()) { - std::set keys = object.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - if (! this->m->linearized) - { - enqueueObject(object.getKey(*iter)); - } - } + std::set keys = object.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + if (! this->m->linearized) + { + enqueueObject(object.getKey(*iter)); + } + } } else { - // ignore + // ignore } } @@ -1344,18 +1344,18 @@ QPDFWriter::unparseChild(QPDFObjectHandle child, int level, int flags) { if (! this->m->linearized) { - enqueueObject(child); + enqueueObject(child); } if (child.isIndirect()) { - QPDFObjGen old_og = child.getObjGen(); - int new_id = this->m->obj_renumber[old_og]; - writeString(QUtil::int_to_string(new_id)); - writeString(" 0 R"); + QPDFObjGen old_og = child.getObjGen(); + int new_id = this->m->obj_renumber[old_og]; + writeString(QUtil::int_to_string(new_id)); + writeString(" 0 R"); } else { - unparseObject(child, level, flags); + unparseObject(child, level, flags); } } @@ -1370,49 +1370,49 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, } else { - writeString("trailer <<"); + writeString("trailer <<"); } writeStringQDF("\n"); if (which == t_lin_second) { - writeString(" /Size "); - writeString(QUtil::int_to_string(size)); + writeString(" /Size "); + writeString(QUtil::int_to_string(size)); } else { - std::set keys = trailer.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - std::string const& key = *iter; - writeStringQDF(" "); - writeStringNoQDF(" "); - writeString(QPDF_Name::normalizeName(key)); - writeString(" "); - if (key == "/Size") - { - writeString(QUtil::int_to_string(size)); - if (which == t_lin_first) - { - writeString(" /Prev "); - qpdf_offset_t pos = this->m->pipeline->getCount(); - writeString(QUtil::int_to_string(prev)); - int nspaces = + std::set keys = trailer.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + std::string const& key = *iter; + writeStringQDF(" "); + writeStringNoQDF(" "); + writeString(QPDF_Name::normalizeName(key)); + writeString(" "); + if (key == "/Size") + { + writeString(QUtil::int_to_string(size)); + if (which == t_lin_first) + { + writeString(" /Prev "); + qpdf_offset_t pos = this->m->pipeline->getCount(); + writeString(QUtil::int_to_string(prev)); + int nspaces = QIntC::to_int(pos - this->m->pipeline->getCount() + 21); - if (nspaces < 0) + if (nspaces < 0) { throw std::logic_error( "QPDFWriter: no padding required in trailer"); } - writePad(nspaces); - } - } - else - { - unparseChild(trailer.getKey(key), 1, 0); - } - writeStringQDF("\n"); - } + writePad(nspaces); + } + } + else + { + unparseChild(trailer.getKey(key), 1, 0); + } + writeStringQDF("\n"); + } } // Write ID @@ -1420,7 +1420,7 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, writeString(" /ID ["); if (linearization_pass == 1) { - std::string original_id1 = getOriginalID1(); + std::string original_id1 = getOriginalID1(); if (original_id1.empty()) { writeString("<00000000000000000000000000000000>"); @@ -1457,13 +1457,13 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, if (which != t_lin_second) { - // Write reference to encryption dictionary - if (this->m->encrypted) - { - writeString(" /Encrypt "); - writeString(QUtil::int_to_string(this->m->encryption_dict_objid)); - writeString(" 0 R"); - } + // Write reference to encryption dictionary + if (this->m->encrypted) + { + writeString(" /Encrypt "); + writeString(QUtil::int_to_string(this->m->encryption_dict_objid)); + writeString(" 0 R"); + } } writeStringQDF("\n"); @@ -1569,7 +1569,7 @@ QPDFWriter::willFilterStream(QPDFObjectHandle stream, void QPDFWriter::unparseObject(QPDFObjectHandle object, int level, - int flags, size_t stream_length, + int flags, size_t stream_length, bool compress) { QPDFObjGen old_og = object.getObjGen(); @@ -1578,30 +1578,30 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, std::string indent; for (int i = 0; i < level; ++i) { - indent += " "; + indent += " "; } if (object.isArray()) { - // Note: PDF spec 1.4 implementation note 121 states that - // Acrobat requires a space after the [ in the /H key of the - // linearization parameter dictionary. We'll do this - // unconditionally for all arrays because it looks nicer and - // doesn't make the files that much bigger. - writeString("["); - writeStringQDF("\n"); - int n = object.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - writeStringQDF(indent); - writeStringQDF(" "); - writeStringNoQDF(" "); - unparseChild(object.getArrayItem(i), level + 1, child_flags); - writeStringQDF("\n"); - } - writeStringQDF(indent); - writeStringNoQDF(" "); - writeString("]"); + // Note: PDF spec 1.4 implementation note 121 states that + // Acrobat requires a space after the [ in the /H key of the + // linearization parameter dictionary. We'll do this + // unconditionally for all arrays because it looks nicer and + // doesn't make the files that much bigger. + writeString("["); + writeStringQDF("\n"); + int n = object.getArrayNItems(); + for (int i = 0; i < n; ++i) + { + writeStringQDF(indent); + writeStringQDF(" "); + writeStringNoQDF(" "); + unparseChild(object.getArrayItem(i), level + 1, child_flags); + writeStringQDF("\n"); + } + writeStringQDF(indent); + writeStringNoQDF(" "); + writeString("]"); } else if (object.isDictionary()) { @@ -1742,7 +1742,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, object.removeKey("/DecodeParms"); } - if (flags & f_filtered) + if (flags & f_filtered) { // We will supply our own filter and decode // parameters. @@ -1791,96 +1791,96 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, } } - writeString("<<"); - writeStringQDF("\n"); - - std::set keys = object.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - std::string const& key = *iter; - - writeStringQDF(indent); - writeStringQDF(" "); - writeStringNoQDF(" "); - writeString(QPDF_Name::normalizeName(key)); - writeString(" "); - if (key == "/Contents" && - object.isDictionaryOfType("/Sig") && - object.hasKey("/ByteRange")) - { + writeString("<<"); + writeStringQDF("\n"); + + std::set keys = object.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + std::string const& key = *iter; + + writeStringQDF(indent); + writeStringQDF(" "); + writeStringNoQDF(" "); + writeString(QPDF_Name::normalizeName(key)); + writeString(" "); + if (key == "/Contents" && + object.isDictionaryOfType("/Sig") && + object.hasKey("/ByteRange")) + { QTC::TC("qpdf", "QPDFWriter no encryption sig contents"); - unparseChild(object.getKey(key), level + 1, - child_flags | f_hex_string | f_no_encryption); - } - else - { - unparseChild(object.getKey(key), level + 1, child_flags); - } - writeStringQDF("\n"); - } - - if (flags & f_stream) - { - writeStringQDF(indent); - writeStringQDF(" "); - writeString(" /Length "); - - if (this->m->direct_stream_lengths) - { - writeString(QUtil::uint_to_string(stream_length)); - } - else - { - writeString( - QUtil::int_to_string(this->m->cur_stream_length_id)); - writeString(" 0 R"); - } - writeStringQDF("\n"); - if (compress && (flags & f_filtered)) - { - writeStringQDF(indent); - writeStringQDF(" "); - writeString(" /Filter /FlateDecode"); - writeStringQDF("\n"); - } - } - - writeStringQDF(indent); - writeStringNoQDF(" "); - writeString(">>"); + unparseChild(object.getKey(key), level + 1, + child_flags | f_hex_string | f_no_encryption); + } + else + { + unparseChild(object.getKey(key), level + 1, child_flags); + } + writeStringQDF("\n"); + } + + if (flags & f_stream) + { + writeStringQDF(indent); + writeStringQDF(" "); + writeString(" /Length "); + + if (this->m->direct_stream_lengths) + { + writeString(QUtil::uint_to_string(stream_length)); + } + else + { + writeString( + QUtil::int_to_string(this->m->cur_stream_length_id)); + writeString(" 0 R"); + } + writeStringQDF("\n"); + if (compress && (flags & f_filtered)) + { + writeStringQDF(indent); + writeStringQDF(" "); + writeString(" /Filter /FlateDecode"); + writeStringQDF("\n"); + } + } + + writeStringQDF(indent); + writeStringNoQDF(" "); + writeString(">>"); } else if (object.isStream()) { - // Write stream data to a buffer. - int new_id = this->m->obj_renumber[old_og]; - if (! this->m->direct_stream_lengths) - { - this->m->cur_stream_length_id = new_id + 1; - } + // Write stream data to a buffer. + int new_id = this->m->obj_renumber[old_og]; + if (! this->m->direct_stream_lengths) + { + this->m->cur_stream_length_id = new_id + 1; + } - flags |= f_stream; - bool compress_stream = false; + flags |= f_stream; + bool compress_stream = false; bool is_metadata = false; PointerHolder stream_data; if (willFilterStream(object, compress_stream, is_metadata, &stream_data)) - { - flags |= f_filtered; - } + { + flags |= f_filtered; + } QPDFObjectHandle stream_dict = object.getDict(); - this->m->cur_stream_length = stream_data->getSize(); - if (is_metadata && this->m->encrypted && (! this->m->encrypt_metadata)) - { - // Don't encrypt stream data for the metadata stream - this->m->cur_data_key.clear(); - } - adjustAESStreamLength(this->m->cur_stream_length); - unparseObject(stream_dict, 0, flags, + this->m->cur_stream_length = stream_data->getSize(); + if (is_metadata && this->m->encrypted && (! this->m->encrypt_metadata)) + { + // Don't encrypt stream data for the metadata stream + this->m->cur_data_key.clear(); + } + adjustAESStreamLength(this->m->cur_stream_length); + unparseObject(stream_dict, 0, flags, this->m->cur_stream_length, compress_stream); - unsigned char last_char = '\0'; - writeString("\nstream\n"); + unsigned char last_char = '\0'; + writeString("\nstream\n"); { PipelinePopper pp_enc(this); pushEncryptionFilter(pp_enc); @@ -1898,72 +1898,72 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, { this->m->added_newline = false; } - writeString("endstream"); + writeString("endstream"); } else if (object.isString()) { - std::string val; - if (this->m->encrypted && - (! (flags & f_in_ostream)) && - (! (flags & f_no_encryption)) && - (! this->m->cur_data_key.empty())) - { - val = object.getStringValue(); - if (this->m->encrypt_use_aes) - { - Pl_Buffer bufpl("encrypted string"); - Pl_AES_PDF pl( + std::string val; + if (this->m->encrypted && + (! (flags & f_in_ostream)) && + (! (flags & f_no_encryption)) && + (! this->m->cur_data_key.empty())) + { + val = object.getStringValue(); + if (this->m->encrypt_use_aes) + { + Pl_Buffer bufpl("encrypted string"); + Pl_AES_PDF pl( "aes encrypt string", &bufpl, true, QUtil::unsigned_char_pointer(this->m->cur_data_key), this->m->cur_data_key.length()); - pl.write(QUtil::unsigned_char_pointer(val), val.length()); - pl.finish(); - auto buf = bufpl.getBufferSharedPointer(); - val = QPDF_String( - std::string(reinterpret_cast(buf->getBuffer()), - buf->getSize())).unparse(true); - } - else - { - auto tmp_ph = QUtil::make_unique_cstr(val); + pl.write(QUtil::unsigned_char_pointer(val), val.length()); + pl.finish(); + auto buf = bufpl.getBufferSharedPointer(); + val = QPDF_String( + std::string(reinterpret_cast(buf->getBuffer()), + buf->getSize())).unparse(true); + } + else + { + auto tmp_ph = QUtil::make_unique_cstr(val); char* tmp = tmp_ph.get(); - size_t vlen = val.length(); - RC4 rc4(QUtil::unsigned_char_pointer(this->m->cur_data_key), - 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(); - } - } - else if (flags & f_hex_string) - { - val = QPDF_String(object.getStringValue()).unparse(true); - } - else - { - val = object.unparseResolved(); - } - writeString(val); + size_t vlen = val.length(); + RC4 rc4(QUtil::unsigned_char_pointer(this->m->cur_data_key), + 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(); + } + } + else if (flags & f_hex_string) + { + val = QPDF_String(object.getStringValue()).unparse(true); + } + else + { + val = object.unparseResolved(); + } + writeString(val); } else { - writeString(object.unparseResolved()); + writeString(object.unparseResolved()); } } void QPDFWriter::writeObjectStreamOffsets(std::vector& offsets, - int first_obj) + int first_obj) { for (size_t i = 0; i < offsets.size(); ++i) { - if (i != 0) - { - writeStringQDF("\n"); - writeStringNoQDF(" "); - } - writeString(QUtil::uint_to_string(i + QIntC::to_size(first_obj))); - writeString(" "); - writeString(QUtil::int_to_string(offsets.at(i))); + if (i != 0) + { + writeStringQDF("\n"); + writeStringNoQDF(" "); + } + writeString(QUtil::uint_to_string(i + QIntC::to_size(first_obj))); + writeString(" "); + writeString(QUtil::int_to_string(offsets.at(i))); } writeString("\n"); } @@ -1989,25 +1989,25 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) bool compressed = false; for (int pass = 1; pass <= 2; ++pass) { - // stream_buffer will be initialized only for pass 2 + // stream_buffer will be initialized only for pass 2 PipelinePopper pp_ostream(this, &stream_buffer); - if (pass == 1) - { - pushDiscardFilter(pp_ostream); - } - else - { - // Adjust offsets to skip over comment before first object - - first = offsets.at(0); - for (std::vector::iterator iter = offsets.begin(); - iter != offsets.end(); ++iter) - { - *iter -= first; - } - - // Take one pass at writing pairs of numbers so we can get - // their size information + if (pass == 1) + { + pushDiscardFilter(pp_ostream); + } + else + { + // Adjust offsets to skip over comment before first object + + first = offsets.at(0); + for (std::vector::iterator iter = offsets.begin(); + iter != offsets.end(); ++iter) + { + *iter -= first; + } + + // Take one pass at writing pairs of numbers so we can get + // their size information { PipelinePopper pp_discard(this); pushDiscardFilter(pp_discard); @@ -2015,42 +2015,42 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) first += this->m->pipeline->getCount(); } - // Set up a stream to write the stream data into a buffer. - Pipeline* next = pushPipeline(new Pl_Buffer("object stream")); + // Set up a stream to write the stream data into a buffer. + Pipeline* next = pushPipeline(new Pl_Buffer("object stream")); if ((this->m->compress_streams || (this->m->stream_decode_level == qpdf_dl_none)) && (! this->m->qdf_mode)) - { - compressed = true; - next = pushPipeline( - new Pl_Flate("compress object stream", next, - Pl_Flate::a_deflate)); - } - activatePipelineStack(pp_ostream); - writeObjectStreamOffsets(offsets, first_obj); - } - - int count = 0; - for (std::set::iterator iter = - this->m->object_stream_to_objects[old_id].begin(); - iter != this->m->object_stream_to_objects[old_id].end(); - ++iter, ++count) - { - QPDFObjGen obj = *iter; - int new_obj = this->m->obj_renumber[obj]; - if (first_obj == -1) - { - first_obj = new_obj; - } - if (this->m->qdf_mode) - { - writeString("%% Object stream: object " + - QUtil::int_to_string(new_obj) + ", index " + - QUtil::int_to_string(count)); - if (! this->m->suppress_original_object_ids) - { - writeString("; original object ID: " + - QUtil::int_to_string(obj.getObj())); + { + compressed = true; + next = pushPipeline( + new Pl_Flate("compress object stream", next, + Pl_Flate::a_deflate)); + } + activatePipelineStack(pp_ostream); + writeObjectStreamOffsets(offsets, first_obj); + } + + int count = 0; + for (std::set::iterator iter = + this->m->object_stream_to_objects[old_id].begin(); + iter != this->m->object_stream_to_objects[old_id].end(); + ++iter, ++count) + { + QPDFObjGen obj = *iter; + int new_obj = this->m->obj_renumber[obj]; + if (first_obj == -1) + { + first_obj = new_obj; + } + if (this->m->qdf_mode) + { + writeString("%% Object stream: object " + + QUtil::int_to_string(new_obj) + ", index " + + QUtil::int_to_string(count)); + if (! this->m->suppress_original_object_ids) + { + writeString("; original object ID: " + + QUtil::int_to_string(obj.getObj())); // For compatibility, only write the generation if // non-zero. While object streams only allow // objects with generation 0, if we are generating @@ -2061,17 +2061,17 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) QTC::TC("qpdf", "QPDFWriter original obj non-zero gen"); writeString(" " + QUtil::int_to_string(obj.getGen())); } - } - writeString("\n"); - } - if (pass == 1) - { - offsets.push_back(this->m->pipeline->getCount()); + } + writeString("\n"); + } + if (pass == 1) + { + offsets.push_back(this->m->pipeline->getCount()); // To avoid double-counting objects being written in // object streams for progress reporting, decrement in // pass 1. indicateProgress(true, false); - } + } QPDFObjectHandle obj_to_write = this->m->pdf.getObjectByObjGen(obj); if (obj_to_write.isStream()) @@ -2084,10 +2084,10 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) "stream found inside object stream; treating as null"); obj_to_write = QPDFObjectHandle::newNull(); } - writeObject(obj_to_write, count); + writeObject(obj_to_write, count); - this->m->xref[new_obj] = QPDFXRefEntry(2, new_id, count); - } + this->m->xref[new_obj] = QPDFXRefEntry(2, new_id, count); + } } // Write the object @@ -2103,30 +2103,30 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) writeStringQDF("\n "); if (compressed) { - writeString(" /Filter /FlateDecode"); + writeString(" /Filter /FlateDecode"); } writeString(" /N " + QUtil::uint_to_string(offsets.size())); writeStringQDF("\n "); writeString(" /First " + QUtil::int_to_string(first)); if (! object.isNull()) { - // If the original object has an /Extends key, preserve it. - QPDFObjectHandle dict = object.getDict(); - QPDFObjectHandle extends = dict.getKey("/Extends"); - if (extends.isIndirect()) - { - QTC::TC("qpdf", "QPDFWriter copy Extends"); - writeStringQDF("\n "); - writeString(" /Extends "); - unparseChild(extends, 1, f_in_ostream); - } + // If the original object has an /Extends key, preserve it. + QPDFObjectHandle dict = object.getDict(); + QPDFObjectHandle extends = dict.getKey("/Extends"); + if (extends.isIndirect()) + { + QTC::TC("qpdf", "QPDFWriter copy Extends"); + writeStringQDF("\n "); + writeString(" /Extends "); + unparseChild(extends, 1, f_in_ostream); + } } writeStringQDF("\n"); writeStringNoQDF(" "); writeString(">>\nstream\n"); if (this->m->encrypted) { - QTC::TC("qpdf", "QPDFWriter encrypt object stream"); + QTC::TC("qpdf", "QPDFWriter encrypt object stream"); } { PipelinePopper pp_enc(this); @@ -2149,65 +2149,65 @@ QPDFWriter::writeObject(QPDFObjectHandle object, int object_stream_index) if ((object_stream_index == -1) && (old_og.getGen() == 0) && - (this->m->object_stream_to_objects.count(old_og.getObj()))) + (this->m->object_stream_to_objects.count(old_og.getObj()))) { - writeObjectStream(object); - return; + writeObjectStream(object); + return; } indicateProgress(false, false); int new_id = this->m->obj_renumber[old_og]; if (this->m->qdf_mode) { - if (this->m->page_object_to_seq.count(old_og)) - { - writeString("%% Page "); - writeString( - QUtil::int_to_string( - this->m->page_object_to_seq[old_og])); - writeString("\n"); - } - if (this->m->contents_to_page_seq.count(old_og)) - { - writeString("%% Contents for page "); - writeString( - QUtil::int_to_string( - this->m->contents_to_page_seq[old_og])); - writeString("\n"); - } + if (this->m->page_object_to_seq.count(old_og)) + { + writeString("%% Page "); + writeString( + QUtil::int_to_string( + this->m->page_object_to_seq[old_og])); + writeString("\n"); + } + if (this->m->contents_to_page_seq.count(old_og)) + { + writeString("%% Contents for page "); + writeString( + QUtil::int_to_string( + this->m->contents_to_page_seq[old_og])); + writeString("\n"); + } } if (object_stream_index == -1) { - if (this->m->qdf_mode && (! this->m->suppress_original_object_ids)) - { - writeString("%% Original object ID: " + - QUtil::int_to_string(object.getObjectID()) + " " + - QUtil::int_to_string(object.getGeneration()) + "\n"); - } - openObject(new_id); - setDataKey(new_id); - unparseObject(object, 0, 0); - this->m->cur_data_key.clear(); - closeObject(new_id); + if (this->m->qdf_mode && (! this->m->suppress_original_object_ids)) + { + writeString("%% Original object ID: " + + QUtil::int_to_string(object.getObjectID()) + " " + + QUtil::int_to_string(object.getGeneration()) + "\n"); + } + openObject(new_id); + setDataKey(new_id); + unparseObject(object, 0, 0); + this->m->cur_data_key.clear(); + closeObject(new_id); } else { - unparseObject(object, 0, f_in_ostream); - writeString("\n"); + unparseObject(object, 0, f_in_ostream); + writeString("\n"); } if ((! this->m->direct_stream_lengths) && object.isStream()) { - if (this->m->qdf_mode) - { - if (this->m->added_newline) - { - writeString("%QDF: ignore_newline\n"); - } - } - openObject(new_id + 1); - writeString(QUtil::uint_to_string(this->m->cur_stream_length)); - closeObject(new_id + 1); + if (this->m->qdf_mode) + { + if (this->m->added_newline) + { + writeString("%QDF: ignore_newline\n"); + } + } + openObject(new_id + 1); + writeString(QUtil::uint_to_string(this->m->cur_stream_length)); + closeObject(new_id + 1); } } @@ -2233,7 +2233,7 @@ QPDFWriter::generateID() if (! this->m->id2.empty()) { - return; + return; } QPDFObjectHandle trailer = this->m->pdf.getTrailer(); @@ -2242,30 +2242,30 @@ QPDFWriter::generateID() if (this->m->static_id) { - // For test suite use only... - static unsigned char tmp[] = {0x31, 0x41, 0x59, 0x26, + // For test suite use only... + static unsigned char tmp[] = {0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x00}; - result = reinterpret_cast(tmp); + result = reinterpret_cast(tmp); } else { - // The PDF specification has guidelines for creating IDs, but - // it states clearly that the only thing that's really - // important is that it is very likely to be unique. We can't - // really follow the guidelines in the spec exactly because we - // haven't written the file yet. This scheme should be fine - // though. The deterministic ID case uses a digest of a - // sufficient portion of the file's contents such no two - // non-matching files would match in the subsets used for this - // computation. Note that we explicitly omit the filename from - // the digest calculation for deterministic ID so that the same - // file converted with qpdf, in that case, would have the same - // ID regardless of the output file's name. - - std::string seed; + // The PDF specification has guidelines for creating IDs, but + // it states clearly that the only thing that's really + // important is that it is very likely to be unique. We can't + // really follow the guidelines in the spec exactly because we + // haven't written the file yet. This scheme should be fine + // though. The deterministic ID case uses a digest of a + // sufficient portion of the file's contents such no two + // non-matching files would match in the subsets used for this + // computation. Note that we explicitly omit the filename from + // the digest calculation for deterministic ID so that the same + // file converted with qpdf, in that case, would have the same + // ID regardless of the output file's name. + + std::string seed; if (this->m->deterministic_id) { if (this->m->deterministic_id_data.empty()) @@ -2285,28 +2285,28 @@ QPDFWriter::generateID() seed += this->m->filename; seed += " "; } - seed += " QPDF "; - if (trailer.hasKey("/Info")) - { + seed += " QPDF "; + if (trailer.hasKey("/Info")) + { QPDFObjectHandle info = trailer.getKey("/Info"); - std::set keys = info.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - QPDFObjectHandle obj = info.getKey(*iter); - if (obj.isString()) - { - seed += " "; - seed += obj.getStringValue(); - } - } - } - - MD5 m; - m.encodeString(seed.c_str()); - MD5::Digest digest; - m.digest(digest); - result = std::string(reinterpret_cast(digest), + std::set keys = info.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + QPDFObjectHandle obj = info.getKey(*iter); + if (obj.isString()) + { + seed += " "; + seed += obj.getStringValue(); + } + } + } + + MD5 m; + m.encodeString(seed.c_str()); + MD5::Digest digest; + m.digest(digest); + result = std::string(reinterpret_cast(digest), sizeof(MD5::Digest)); } @@ -2319,7 +2319,7 @@ QPDFWriter::generateID() this->m->id1 = getOriginalID1(); if (this->m->id1.empty()) { - this->m->id1 = this->m->id2; + this->m->id1 = this->m->id2; } } @@ -2331,31 +2331,31 @@ QPDFWriter::initializeSpecialStreams() std::vector pages = this->m->pdf.getAllPages(); int num = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { - QPDFObjectHandle& page = *iter; - this->m->page_object_to_seq[page.getObjGen()] = ++num; - QPDFObjectHandle contents = page.getKey("/Contents"); - std::vector contents_objects; - if (contents.isArray()) - { - int n = contents.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - contents_objects.push_back( - contents.getArrayItem(i).getObjGen()); - } - } - else if (contents.isStream()) - { - contents_objects.push_back(contents.getObjGen()); - } - - for (auto const& c: contents_objects) - { - this->m->contents_to_page_seq[c] = num; - this->m->normalized_streams.insert(c); - } + iter != pages.end(); ++iter) + { + QPDFObjectHandle& page = *iter; + this->m->page_object_to_seq[page.getObjGen()] = ++num; + QPDFObjectHandle contents = page.getKey("/Contents"); + std::vector contents_objects; + if (contents.isArray()) + { + int n = contents.getArrayNItems(); + for (int i = 0; i < n; ++i) + { + contents_objects.push_back( + contents.getArrayItem(i).getObjGen()); + } + } + else if (contents.isStream()) + { + contents_objects.push_back(contents.getObjGen()); + } + + for (auto const& c: contents_objects) + { + this->m->contents_to_page_seq[c] = num; + this->m->normalized_streams.insert(c); + } } } @@ -2424,31 +2424,31 @@ QPDFWriter::generateObjectStreams() size_t n_per = eligible.size() / n_object_streams; if (n_per * n_object_streams < eligible.size()) { - ++n_per; + ++n_per; } unsigned int n = 0; int cur_ostream = 0; for (std::vector::const_iterator iter = eligible.begin(); - iter != eligible.end(); ++iter) - { - if ((n % n_per) == 0) - { - if (n > 0) - { - QTC::TC("qpdf", "QPDFWriter generate >1 ostream"); - } - n = 0; - } - if (n == 0) - { - // Construct a new null object as the "original" object - // stream. The rest of the code knows that this means - // we're creating the object stream from scratch. - cur_ostream = this->m->pdf.makeIndirectObject( - QPDFObjectHandle::newNull()).getObjectID(); - } - this->m->object_to_object_stream[*iter] = cur_ostream; - ++n; + iter != eligible.end(); ++iter) + { + if ((n % n_per) == 0) + { + if (n > 0) + { + QTC::TC("qpdf", "QPDFWriter generate >1 ostream"); + } + n = 0; + } + if (n == 0) + { + // Construct a new null object as the "original" object + // stream. The rest of the code knows that this means + // we're creating the object stream from scratch. + cur_ostream = this->m->pdf.makeIndirectObject( + QPDFObjectHandle::newNull()).getObjectID(); + } + this->m->object_to_object_stream[*iter] = cur_ostream; + ++n; } } @@ -2529,7 +2529,7 @@ QPDFWriter::doWriteSetup() if (this->m->linearized) { - this->m->qdf_mode = false; + this->m->qdf_mode = false; } if (this->m->pclm) @@ -2541,14 +2541,14 @@ QPDFWriter::doWriteSetup() if (this->m->qdf_mode) { - if (! this->m->normalize_content_set) - { - this->m->normalize_content = true; - } - if (! this->m->compress_streams_set) - { - this->m->compress_streams = false; - } + if (! this->m->normalize_content_set) + { + this->m->normalize_content = true; + } + if (! this->m->compress_streams_set) + { + this->m->compress_streams = false; + } if (! this->m->stream_decode_level_set) { this->m->stream_decode_level = qpdf_dl_generalized; @@ -2557,119 +2557,119 @@ QPDFWriter::doWriteSetup() if (this->m->encrypted) { - // Encryption has been explicitly set - this->m->preserve_encryption = false; + // Encryption has been explicitly set + this->m->preserve_encryption = false; } else if (this->m->normalize_content || - this->m->stream_decode_level || + this->m->stream_decode_level || this->m->pclm || - this->m->qdf_mode) + this->m->qdf_mode) { - // Encryption makes looking at contents pretty useless. If - // the user explicitly encrypted though, we still obey that. - this->m->preserve_encryption = false; + // Encryption makes looking at contents pretty useless. If + // the user explicitly encrypted though, we still obey that. + this->m->preserve_encryption = false; } if (this->m->preserve_encryption) { - copyEncryptionParameters(this->m->pdf); + copyEncryptionParameters(this->m->pdf); } if (! this->m->forced_pdf_version.empty()) { - int major = 0; - int minor = 0; - parseVersion(this->m->forced_pdf_version, major, minor); - disableIncompatibleEncryption(major, minor, + int major = 0; + int minor = 0; + parseVersion(this->m->forced_pdf_version, major, minor); + disableIncompatibleEncryption(major, minor, this->m->forced_extension_level); - if (compareVersions(major, minor, 1, 5) < 0) - { - QTC::TC("qpdf", "QPDFWriter forcing object stream disable"); - this->m->object_stream_mode = qpdf_o_disable; - } + if (compareVersions(major, minor, 1, 5) < 0) + { + QTC::TC("qpdf", "QPDFWriter forcing object stream disable"); + this->m->object_stream_mode = qpdf_o_disable; + } } if (this->m->qdf_mode || this->m->normalize_content || this->m->stream_decode_level) { - initializeSpecialStreams(); + initializeSpecialStreams(); } if (this->m->qdf_mode) { - // Generate indirect stream lengths for qdf mode since fix-qdf - // uses them for storing recomputed stream length data. - // Certain streams such as object streams, xref streams, and - // hint streams always get direct stream lengths. - this->m->direct_stream_lengths = false; + // Generate indirect stream lengths for qdf mode since fix-qdf + // uses them for storing recomputed stream length data. + // Certain streams such as object streams, xref streams, and + // hint streams always get direct stream lengths. + this->m->direct_stream_lengths = false; } switch (this->m->object_stream_mode) { case qpdf_o_disable: - // no action required - break; + // no action required + break; case qpdf_o_preserve: - preserveObjectStreams(); - break; + preserveObjectStreams(); + break; case qpdf_o_generate: - generateObjectStreams(); - break; + generateObjectStreams(); + break; - // no default so gcc will warn for missing case tag + // no default so gcc will warn for missing case tag } if (this->m->linearized) { - // Page dictionaries are not allowed to be compressed objects. - std::vector pages = this->m->pdf.getAllPages(); - for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { - QPDFObjectHandle& page = *iter; - QPDFObjGen og = page.getObjGen(); - if (this->m->object_to_object_stream.count(og)) - { - QTC::TC("qpdf", "QPDFWriter uncompressing page dictionary"); - this->m->object_to_object_stream.erase(og); - } - } + // Page dictionaries are not allowed to be compressed objects. + std::vector pages = this->m->pdf.getAllPages(); + for (std::vector::iterator iter = pages.begin(); + iter != pages.end(); ++iter) + { + QPDFObjectHandle& page = *iter; + QPDFObjGen og = page.getObjGen(); + if (this->m->object_to_object_stream.count(og)) + { + QTC::TC("qpdf", "QPDFWriter uncompressing page dictionary"); + this->m->object_to_object_stream.erase(og); + } + } } if (this->m->linearized || this->m->encrypted) { - // The document catalog is not allowed to be compressed in - // linearized files either. It also appears that Adobe Reader - // 8.0.0 has a bug that prevents it from being able to handle - // encrypted files with compressed document catalogs, so we - // disable them in that case as well. - QPDFObjGen og = this->m->pdf.getRoot().getObjGen(); - if (this->m->object_to_object_stream.count(og)) - { - QTC::TC("qpdf", "QPDFWriter uncompressing root"); - this->m->object_to_object_stream.erase(og); - } + // The document catalog is not allowed to be compressed in + // linearized files either. It also appears that Adobe Reader + // 8.0.0 has a bug that prevents it from being able to handle + // encrypted files with compressed document catalogs, so we + // disable them in that case as well. + QPDFObjGen og = this->m->pdf.getRoot().getObjGen(); + if (this->m->object_to_object_stream.count(og)) + { + QTC::TC("qpdf", "QPDFWriter uncompressing root"); + this->m->object_to_object_stream.erase(og); + } } // Generate reverse mapping from object stream to objects for (std::map::iterator iter = - this->m->object_to_object_stream.begin(); - iter != this->m->object_to_object_stream.end(); ++iter) - { - QPDFObjGen obj = (*iter).first; - int stream = (*iter).second; - this->m->object_stream_to_objects[stream].insert(obj); - this->m->max_ostream_index = - std::max(this->m->max_ostream_index, - QIntC::to_int( + this->m->object_to_object_stream.begin(); + iter != this->m->object_to_object_stream.end(); ++iter) + { + QPDFObjGen obj = (*iter).first; + int stream = (*iter).second; + this->m->object_stream_to_objects[stream].insert(obj); + this->m->max_ostream_index = + std::max(this->m->max_ostream_index, + QIntC::to_int( this->m->object_stream_to_objects[stream].size()) - 1); } if (! this->m->object_stream_to_objects.empty()) { - setMinimumPDFVersion("1.5"); + setMinimumPDFVersion("1.5"); } setMinimumPDFVersion(this->m->pdf.getPDFVersion(), @@ -2678,8 +2678,8 @@ QPDFWriter::doWriteSetup() this->m->final_extension_level = this->m->min_extension_level; if (! this->m->forced_pdf_version.empty()) { - QTC::TC("qpdf", "QPDFWriter using forced PDF version"); - this->m->final_pdf_version = this->m->forced_pdf_version; + QTC::TC("qpdf", "QPDFWriter using forced PDF version"); + this->m->final_pdf_version = this->m->forced_pdf_version; this->m->final_extension_level = this->m->forced_extension_level; } } @@ -2699,23 +2699,23 @@ QPDFWriter::write() if (this->m->linearized) { - writeLinearized(); + writeLinearized(); } else { - writeStandard(); + writeStandard(); } this->m->pipeline->finish(); if (this->m->close_file) { - fclose(this->m->file); + fclose(this->m->file); } this->m->file = 0; if (this->m->buffer_pipeline) { - this->m->output_buffer = this->m->buffer_pipeline->getBuffer(); - this->m->buffer_pipeline = 0; + this->m->output_buffer = this->m->buffer_pipeline->getBuffer(); + this->m->buffer_pipeline = 0; } indicateProgress(false, true); } @@ -2747,9 +2747,9 @@ void QPDFWriter::enqueuePart(std::vector& part) { for (std::vector::iterator iter = part.begin(); - iter != part.end(); ++iter) + iter != part.end(); ++iter) { - enqueueObject(*iter); + enqueueObject(*iter); } } @@ -2759,13 +2759,13 @@ QPDFWriter::writeEncryptionDictionary() this->m->encryption_dict_objid = openObject(this->m->encryption_dict_objid); writeString("<<"); for (std::map::iterator iter = - this->m->encryption_dictionary.begin(); - iter != this->m->encryption_dictionary.end(); ++iter) + this->m->encryption_dictionary.begin(); + iter != this->m->encryption_dictionary.end(); ++iter) { - writeString(" "); - writeString((*iter).first); - writeString(" "); - writeString((*iter).second); + writeString(" "); + writeString((*iter).first); + writeString(" "); + writeString((*iter).second); } writeString(" >>"); closeObject(this->m->encryption_dict_objid); @@ -2823,8 +2823,8 @@ QPDFWriter::writeHintStream(int hint_id) writeString(QUtil::int_to_string(S)); if (O) { - writeString(" /O "); - writeString(QUtil::int_to_string(O)); + writeString(" /O "); + writeString(QUtil::int_to_string(O)); } writeString(" /Length "); adjustAESStreamLength(hlen); @@ -2833,7 +2833,7 @@ QPDFWriter::writeHintStream(int hint_id) if (this->m->encrypted) { - QTC::TC("qpdf", "QPDFWriter encrypted hint stream"); + QTC::TC("qpdf", "QPDFWriter encrypted hint stream"); } unsigned char last_char = '\0'; { @@ -2845,7 +2845,7 @@ QPDFWriter::writeHintStream(int hint_id) if (last_char != '\n') { - writeString("\n"); + writeString("\n"); } writeString("endstream"); closeObject(hint_id); @@ -2862,8 +2862,8 @@ QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size) qpdf_offset_t QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size, - qpdf_offset_t prev, bool suppress_offsets, - int hint_id, qpdf_offset_t hint_offset, + qpdf_offset_t prev, bool suppress_offsets, + int hint_id, qpdf_offset_t hint_offset, qpdf_offset_t hint_length, int linearization_pass) { writeString("xref\n"); @@ -2874,26 +2874,26 @@ QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size, writeString("\n"); for (int i = first; i <= last; ++i) { - if (i == 0) - { - writeString("0000000000 65535 f \n"); - } - else - { - qpdf_offset_t offset = 0; - if (! suppress_offsets) - { - offset = this->m->xref[i].getOffset(); - if ((hint_id != 0) && - (i != hint_id) && - (offset >= hint_offset)) - { - offset += hint_length; - } - } - writeString(QUtil::int_to_string(offset, 10)); - writeString(" 00000 n \n"); - } + if (i == 0) + { + writeString("0000000000 65535 f \n"); + } + else + { + qpdf_offset_t offset = 0; + if (! suppress_offsets) + { + offset = this->m->xref[i].getOffset(); + if ((hint_id != 0) && + (i != hint_id) && + (offset >= hint_offset)) + { + offset += hint_length; + } + } + writeString(QUtil::int_to_string(offset, 10)); + writeString(" 00000 n \n"); + } } writeTrailer(which, size, false, prev, linearization_pass); writeString("\n"); @@ -2902,22 +2902,22 @@ QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size, qpdf_offset_t QPDFWriter::writeXRefStream(int objid, int max_id, qpdf_offset_t max_offset, - trailer_e which, int first, int last, int size) + trailer_e which, int first, int last, int size) { // There are too many extra arguments to replace overloaded // function with defaults in the header file...too much risk of // leaving something off. return writeXRefStream(objid, max_id, max_offset, - which, first, last, size, 0, 0, 0, 0, false, 0); + which, first, last, size, 0, 0, 0, 0, false, 0); } qpdf_offset_t QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, - trailer_e which, int first, int last, int size, - qpdf_offset_t prev, int hint_id, - qpdf_offset_t hint_offset, + trailer_e which, int first, int last, int size, + qpdf_offset_t prev, int hint_id, + qpdf_offset_t hint_offset, qpdf_offset_t hint_length, - bool skip_compression, + bool skip_compression, int linearization_pass) { qpdf_offset_t xref_offset = this->m->pipeline->getCount(); @@ -2942,18 +2942,18 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, (this->m->stream_decode_level == qpdf_dl_none)) && (! this->m->qdf_mode)) { - compressed = true; - if (! skip_compression) - { - // Write the stream dictionary for compression but don't - // actually compress. This helps us with computation of - // padding for pass 1 of linearization. - p = pushPipeline( - new Pl_Flate("compress xref", p, Pl_Flate::a_deflate)); - } - p = pushPipeline( - new Pl_PNGFilter( - "pngify xref", p, Pl_PNGFilter::a_encode, esize)); + compressed = true; + if (! skip_compression) + { + // Write the stream dictionary for compression but don't + // actually compress. This helps us with computation of + // padding for pass 1 of linearization. + p = pushPipeline( + new Pl_Flate("compress xref", p, Pl_Flate::a_deflate)); + } + p = pushPipeline( + new Pl_PNGFilter( + "pngify xref", p, Pl_PNGFilter::a_encode, esize)); } PointerHolder xref_data; { @@ -3006,21 +3006,21 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, writeString(" /Length " + QUtil::uint_to_string(xref_data->getSize())); if (compressed) { - writeStringQDF("\n "); - writeString(" /Filter /FlateDecode"); - writeStringQDF("\n "); - writeString(" /DecodeParms << /Columns " + - QUtil::int_to_string(esize) + " /Predictor 12 >>"); + writeStringQDF("\n "); + writeString(" /Filter /FlateDecode"); + writeStringQDF("\n "); + writeString(" /DecodeParms << /Columns " + + QUtil::int_to_string(esize) + " /Predictor 12 >>"); } writeStringQDF("\n "); writeString(" /W [ 1 " + - QUtil::int_to_string(f1_size) + " " + - QUtil::int_to_string(f2_size) + " ]"); + QUtil::int_to_string(f1_size) + " " + + QUtil::int_to_string(f2_size) + " ]"); if (! ((first == 0) && (last == size - 1))) { - writeString(" /Index [ " + - QUtil::int_to_string(first) + " " + - QUtil::int_to_string(last - first + 1) + " ]"); + writeString(" /Index [ " + + QUtil::int_to_string(first) + " " + + QUtil::int_to_string(last - first + 1) + " ]"); } writeTrailer(which, size, true, prev, linearization_pass); writeString("\nstream\n"); @@ -3138,17 +3138,17 @@ QPDFWriter::writeLinearized() bool need_xref_stream = (! this->m->object_to_object_stream.empty()); if (need_xref_stream) { - second_half_xref = this->m->next_objid++; + second_half_xref = this->m->next_objid++; } // Assign numbers to all compressed objects in the second half. std::vector* vecs2[] = {&part7, &part8, &part9}; for (int i = 0; i < 3; ++i) { - for (std::vector::iterator iter = (*vecs2[i]).begin(); - iter != (*vecs2[i]).end(); ++iter) - { - assignCompressedObjectNumbers((*iter).getObjGen()); - } + for (std::vector::iterator iter = (*vecs2[i]).begin(); + iter != (*vecs2[i]).end(); ++iter) + { + assignCompressedObjectNumbers((*iter).getObjGen()); + } } int second_half_end = this->m->next_objid - 1; int second_trailer_size = this->m->next_objid; @@ -3159,14 +3159,14 @@ QPDFWriter::writeLinearized() int first_half_xref = 0; if (need_xref_stream) { - first_half_xref = this->m->next_objid++; + first_half_xref = this->m->next_objid++; } int part4_first_obj = this->m->next_objid; this->m->next_objid += QIntC::to_int(part4.size()); int after_part4 = this->m->next_objid; if (this->m->encrypted) { - this->m->encryption_dict_objid = this->m->next_objid++; + this->m->encryption_dict_objid = this->m->next_objid++; } int hint_id = this->m->next_objid++; int part6_first_obj = this->m->next_objid; @@ -3176,11 +3176,11 @@ QPDFWriter::writeLinearized() std::vector* vecs1[] = {&part4, &part6}; for (int i = 0; i < 2; ++i) { - for (std::vector::iterator iter = (*vecs1[i]).begin(); - iter != (*vecs1[i]).end(); ++iter) - { - assignCompressedObjectNumbers((*iter).getObjGen()); - } + for (std::vector::iterator iter = (*vecs1[i]).begin(); + iter != (*vecs1[i]).end(); ++iter) + { + assignCompressedObjectNumbers((*iter).getObjGen()); + } } int first_half_end = this->m->next_objid - 1; int first_trailer_size = this->m->next_objid; @@ -3235,8 +3235,8 @@ QPDFWriter::writeLinearized() auto pp_md5 = make_pointer_holder(this); for (int pass = 1; pass <= 2; ++pass) { - if (pass == 1) - { + if (pass == 1) + { if (! this->m->lin_pass1_filename.empty()) { lin_pass1_file = @@ -3254,107 +3254,107 @@ QPDFWriter::writeLinearized() { pushMD5Pipeline(*pp_md5); } - } - - // Part 1: header - - writeHeader(); - - // Part 2: linearization parameter dictionary. Save enough - // space to write real dictionary. 200 characters is enough - // space if all numerical values in the parameter dictionary - // that contain offsets are 20 digits long plus a few extra - // characters for safety. The entire linearization parameter - // dictionary must appear within the first 1024 characters of - // the file. - - qpdf_offset_t pos = this->m->pipeline->getCount(); - openObject(lindict_id); - writeString("<<"); - if (pass == 2) - { - std::vector const& pages = + } + + // Part 1: header + + writeHeader(); + + // Part 2: linearization parameter dictionary. Save enough + // space to write real dictionary. 200 characters is enough + // space if all numerical values in the parameter dictionary + // that contain offsets are 20 digits long plus a few extra + // characters for safety. The entire linearization parameter + // dictionary must appear within the first 1024 characters of + // the file. + + qpdf_offset_t pos = this->m->pipeline->getCount(); + openObject(lindict_id); + writeString("<<"); + if (pass == 2) + { + std::vector const& pages = this->m->pdf.getAllPages(); - int first_page_object = + int first_page_object = this->m->obj_renumber[pages.at(0).getObjGen()]; - int npages = QIntC::to_int(pages.size()); - - writeString(" /Linearized 1 /L "); - writeString(QUtil::int_to_string(file_size + hint_length)); - // Implementation note 121 states that a space is - // mandatory after this open bracket. - writeString(" /H [ "); - writeString(QUtil::int_to_string( + int npages = QIntC::to_int(pages.size()); + + writeString(" /Linearized 1 /L "); + writeString(QUtil::int_to_string(file_size + hint_length)); + // Implementation note 121 states that a space is + // mandatory after this open bracket. + writeString(" /H [ "); + writeString(QUtil::int_to_string( this->m->xref[hint_id].getOffset())); - writeString(" "); - writeString(QUtil::int_to_string(hint_length)); - writeString(" ] /O "); - writeString(QUtil::int_to_string(first_page_object)); - writeString(" /E "); - writeString(QUtil::int_to_string(part6_end_offset + hint_length)); - writeString(" /N "); - writeString(QUtil::int_to_string(npages)); - writeString(" /T "); - writeString(QUtil::int_to_string(space_before_zero + hint_length)); - } - writeString(" >>"); - closeObject(lindict_id); - static int const pad = 200; - int spaces = QIntC::to_int(pos - this->m->pipeline->getCount() + pad); - assert(spaces >= 0); - writePad(spaces); - writeString("\n"); + writeString(" "); + writeString(QUtil::int_to_string(hint_length)); + writeString(" ] /O "); + writeString(QUtil::int_to_string(first_page_object)); + writeString(" /E "); + writeString(QUtil::int_to_string(part6_end_offset + hint_length)); + writeString(" /N "); + writeString(QUtil::int_to_string(npages)); + writeString(" /T "); + writeString(QUtil::int_to_string(space_before_zero + hint_length)); + } + writeString(" >>"); + closeObject(lindict_id); + static int const pad = 200; + int spaces = QIntC::to_int(pos - this->m->pipeline->getCount() + pad); + assert(spaces >= 0); + writePad(spaces); + writeString("\n"); // If the user supplied any additional header text, write it // here after the linearization parameter dictionary. writeString(this->m->extra_header_text); - // Part 3: first page cross reference table and trailer. - - qpdf_offset_t first_xref_offset = this->m->pipeline->getCount(); - qpdf_offset_t hint_offset = 0; - if (pass == 2) - { - hint_offset = this->m->xref[hint_id].getOffset(); - } - if (need_xref_stream) - { - // Must pad here too. - if (pass == 1) - { - // Set first_half_max_obj_offset to a value large - // enough to force four bytes to be reserved for each - // file offset. This would provide adequate space for - // the xref stream as long as the last object in page - // 1 starts with in the first 4 GB of the file, which - // is extremely likely. In the second pass, we will - // know the actual value for this, but it's okay if - // it's smaller. - first_half_max_obj_offset = 1 << 25; - } - pos = this->m->pipeline->getCount(); - writeXRefStream(first_half_xref, first_half_end, - first_half_max_obj_offset, - t_lin_first, first_half_start, first_half_end, - first_trailer_size, - hint_length + second_xref_offset, - hint_id, hint_offset, hint_length, - (pass == 1), pass); - qpdf_offset_t endpos = this->m->pipeline->getCount(); - if (pass == 1) - { - // Pad so we have enough room for the real xref - // stream. - writePad(calculateXrefStreamPadding(endpos - pos)); - first_xref_end = this->m->pipeline->getCount(); - } - else - { - // Pad so that the next object starts at the same - // place as in pass 1. - writePad(QIntC::to_int(first_xref_end - endpos)); - - if (this->m->pipeline->getCount() != first_xref_end) + // Part 3: first page cross reference table and trailer. + + qpdf_offset_t first_xref_offset = this->m->pipeline->getCount(); + qpdf_offset_t hint_offset = 0; + if (pass == 2) + { + hint_offset = this->m->xref[hint_id].getOffset(); + } + if (need_xref_stream) + { + // Must pad here too. + if (pass == 1) + { + // Set first_half_max_obj_offset to a value large + // enough to force four bytes to be reserved for each + // file offset. This would provide adequate space for + // the xref stream as long as the last object in page + // 1 starts with in the first 4 GB of the file, which + // is extremely likely. In the second pass, we will + // know the actual value for this, but it's okay if + // it's smaller. + first_half_max_obj_offset = 1 << 25; + } + pos = this->m->pipeline->getCount(); + writeXRefStream(first_half_xref, first_half_end, + first_half_max_obj_offset, + t_lin_first, first_half_start, first_half_end, + first_trailer_size, + hint_length + second_xref_offset, + hint_id, hint_offset, hint_length, + (pass == 1), pass); + qpdf_offset_t endpos = this->m->pipeline->getCount(); + if (pass == 1) + { + // Pad so we have enough room for the real xref + // stream. + writePad(calculateXrefStreamPadding(endpos - pos)); + first_xref_end = this->m->pipeline->getCount(); + } + else + { + // Pad so that the next object starts at the same + // place as in pass 1. + writePad(QIntC::to_int(first_xref_end - endpos)); + + if (this->m->pipeline->getCount() != first_xref_end) { throw std::logic_error( "insufficient padding for first pass xref stream; " @@ -3362,111 +3362,111 @@ QPDFWriter::writeLinearized() QUtil::int_to_string(first_xref_end) + "; endpos=" + QUtil::int_to_string(endpos)); } - } - writeString("\n"); - } - else - { - writeXRefTable(t_lin_first, first_half_start, first_half_end, - first_trailer_size, hint_length + second_xref_offset, - (pass == 1), hint_id, hint_offset, hint_length, + } + writeString("\n"); + } + else + { + writeXRefTable(t_lin_first, first_half_start, first_half_end, + first_trailer_size, hint_length + second_xref_offset, + (pass == 1), hint_id, hint_offset, hint_length, pass); - writeString("startxref\n0\n%%EOF\n"); - } - - // Parts 4 through 9 - - for (std::list::iterator iter = - this->m->object_queue.begin(); - iter != this->m->object_queue.end(); ++iter) - { - QPDFObjectHandle cur_object = (*iter); - if (cur_object.getObjectID() == part6_end_marker) - { - first_half_max_obj_offset = this->m->pipeline->getCount(); - } - writeObject(cur_object); - if (cur_object.getObjectID() == part4_end_marker) - { - if (this->m->encrypted) - { - writeEncryptionDictionary(); - } - if (pass == 1) - { - this->m->xref[hint_id] = - QPDFXRefEntry(1, this->m->pipeline->getCount(), 0); - } - else - { - // Part 5: hint stream - writeBuffer(hint_buffer); - } - } - if (cur_object.getObjectID() == part6_end_marker) - { - part6_end_offset = this->m->pipeline->getCount(); - } - } - - // Part 10: overflow hint stream -- not used - - // Part 11: main cross reference table and trailer - - second_xref_offset = this->m->pipeline->getCount(); - if (need_xref_stream) - { - pos = this->m->pipeline->getCount(); - space_before_zero = - writeXRefStream(second_half_xref, - second_half_end, second_xref_offset, - t_lin_second, 0, second_half_end, - second_trailer_size, - 0, 0, 0, 0, (pass == 1), pass); - qpdf_offset_t endpos = this->m->pipeline->getCount(); - - if (pass == 1) - { - // Pad so we have enough room for the real xref - // stream. See comments for previous xref stream on - // how we calculate the padding. - writePad(calculateXrefStreamPadding(endpos - pos)); - writeString("\n"); - second_xref_end = this->m->pipeline->getCount(); - } - else - { - // Make the file size the same. - writePad( + writeString("startxref\n0\n%%EOF\n"); + } + + // Parts 4 through 9 + + for (std::list::iterator iter = + this->m->object_queue.begin(); + iter != this->m->object_queue.end(); ++iter) + { + QPDFObjectHandle cur_object = (*iter); + if (cur_object.getObjectID() == part6_end_marker) + { + first_half_max_obj_offset = this->m->pipeline->getCount(); + } + writeObject(cur_object); + if (cur_object.getObjectID() == part4_end_marker) + { + if (this->m->encrypted) + { + writeEncryptionDictionary(); + } + if (pass == 1) + { + this->m->xref[hint_id] = + QPDFXRefEntry(1, this->m->pipeline->getCount(), 0); + } + else + { + // Part 5: hint stream + writeBuffer(hint_buffer); + } + } + if (cur_object.getObjectID() == part6_end_marker) + { + part6_end_offset = this->m->pipeline->getCount(); + } + } + + // Part 10: overflow hint stream -- not used + + // Part 11: main cross reference table and trailer + + second_xref_offset = this->m->pipeline->getCount(); + if (need_xref_stream) + { + pos = this->m->pipeline->getCount(); + space_before_zero = + writeXRefStream(second_half_xref, + second_half_end, second_xref_offset, + t_lin_second, 0, second_half_end, + second_trailer_size, + 0, 0, 0, 0, (pass == 1), pass); + qpdf_offset_t endpos = this->m->pipeline->getCount(); + + if (pass == 1) + { + // Pad so we have enough room for the real xref + // stream. See comments for previous xref stream on + // how we calculate the padding. + writePad(calculateXrefStreamPadding(endpos - pos)); + writeString("\n"); + second_xref_end = this->m->pipeline->getCount(); + } + else + { + // Make the file size the same. + writePad( QIntC::to_int(second_xref_end + hint_length - 1 - this->m->pipeline->getCount())); - writeString("\n"); + writeString("\n"); - // If this assertion fails, maybe we didn't have - // enough padding above. - if (this->m->pipeline->getCount() != + // If this assertion fails, maybe we didn't have + // enough padding above. + if (this->m->pipeline->getCount() != second_xref_end + hint_length) { throw std::logic_error( "count mismatch after xref stream;" " possible insufficient padding?"); } - } - } - else - { - space_before_zero = - writeXRefTable(t_lin_second, 0, second_half_end, - second_trailer_size, 0, false, 0, 0, 0, pass); - } - writeString("startxref\n"); - writeString(QUtil::int_to_string(first_xref_offset)); - writeString("\n%%EOF\n"); + } + } + else + { + space_before_zero = + writeXRefTable(t_lin_second, 0, second_half_end, + second_trailer_size, 0, false, 0, 0, 0, pass); + } + writeString("startxref\n"); + writeString(QUtil::int_to_string(first_xref_offset)); + writeString("\n%%EOF\n"); discardGeneration(this->m->obj_renumber, this->m->obj_renumber_no_gen); - if (pass == 1) - { + if (pass == 1) + { if (this->m->deterministic_id) { QTC::TC("qpdf", "QPDFWriter linearized deterministic ID", @@ -3476,25 +3476,25 @@ QPDFWriter::writeLinearized() assert(this->m->md5_pipeline == 0); } - // Close first pass pipeline - file_size = this->m->pipeline->getCount(); - pp_pass1 = 0; + // Close first pass pipeline + file_size = this->m->pipeline->getCount(); + pp_pass1 = 0; - // Save hint offset since it will be set to zero by - // calling openObject. - qpdf_offset_t hint_offset1 = this->m->xref[hint_id].getOffset(); + // Save hint offset since it will be set to zero by + // calling openObject. + qpdf_offset_t hint_offset1 = this->m->xref[hint_id].getOffset(); - // Write hint stream to a buffer + // Write hint stream to a buffer { pushPipeline(new Pl_Buffer("hint buffer")); PipelinePopper pp_hint(this, &hint_buffer); activatePipelineStack(pp_hint); writeHintStream(hint_id); } - hint_length = QIntC::to_offset(hint_buffer->getSize()); + hint_length = QIntC::to_offset(hint_buffer->getSize()); - // Restore hint offset - this->m->xref[hint_id] = QPDFXRefEntry(1, hint_offset1, 0); + // Restore hint offset + this->m->xref[hint_id] = QPDFXRefEntry(1, hint_offset1, 0); if (lin_pass1_file) { // Write some debugging information @@ -3509,7 +3509,7 @@ QPDFWriter::writeLinearized() fclose(lin_pass1_file); lin_pass1_file = 0; } - } + } } } @@ -3537,9 +3537,9 @@ QPDFWriter::enqueueObjectsStandard() // no-op. std::set keys = trailer.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) + iter != keys.end(); ++iter) { - enqueueObject(trailer.getKey(*iter)); + enqueueObject(trailer.getKey(*iter)); } } @@ -3646,31 +3646,31 @@ QPDFWriter::writeStandard() // Now start walking queue, outputting each object. while (this->m->object_queue.size()) { - QPDFObjectHandle cur_object = this->m->object_queue.front(); - this->m->object_queue.pop_front(); - writeObject(cur_object); + QPDFObjectHandle cur_object = this->m->object_queue.front(); + this->m->object_queue.pop_front(); + writeObject(cur_object); } // Write out the encryption dictionary, if any if (this->m->encrypted) { - writeEncryptionDictionary(); + writeEncryptionDictionary(); } // Now write out xref. next_objid is now the number of objects. qpdf_offset_t xref_offset = this->m->pipeline->getCount(); if (this->m->object_stream_to_objects.empty()) { - // Write regular cross-reference table - writeXRefTable(t_normal, 0, this->m->next_objid - 1, + // Write regular cross-reference table + writeXRefTable(t_normal, 0, this->m->next_objid - 1, this->m->next_objid); } else { - // Write cross-reference stream. - int xref_id = this->m->next_objid++; - writeXRefStream(xref_id, xref_id, xref_offset, t_normal, - 0, this->m->next_objid - 1, this->m->next_objid); + // Write cross-reference stream. + int xref_id = this->m->next_objid++; + writeXRefStream(xref_id, xref_id, xref_offset, t_normal, + 0, this->m->next_objid - 1, this->m->next_objid); } writeString("startxref\n"); writeString(QUtil::int_to_string(xref_offset)); @@ -3678,7 +3678,7 @@ QPDFWriter::writeStandard() if (this->m->deterministic_id) { - QTC::TC("qpdf", "QPDFWriter standard deterministic ID", + QTC::TC("qpdf", "QPDFWriter standard deterministic ID", this->m->object_stream_to_objects.empty() ? 0 : 1); pp_md5 = 0; assert(this->m->md5_pipeline == 0); diff --git a/libqpdf/QPDFXRefEntry.cc b/libqpdf/QPDFXRefEntry.cc index aaab09d0..8eb2ee1e 100644 --- a/libqpdf/QPDFXRefEntry.cc +++ b/libqpdf/QPDFXRefEntry.cc @@ -18,8 +18,8 @@ QPDFXRefEntry::QPDFXRefEntry(int type, qpdf_offset_t field1, int field2) : { if ((type < 1) || (type > 2)) { - throw std::logic_error( - "invalid xref type " + QUtil::int_to_string(type)); + throw std::logic_error( + "invalid xref type " + QUtil::int_to_string(type)); } } @@ -34,8 +34,8 @@ QPDFXRefEntry::getOffset() const { if (this->type != 1) { - throw std::logic_error( - "getOffset called for xref entry of type != 1"); + throw std::logic_error( + "getOffset called for xref entry of type != 1"); } return this->field1; } @@ -45,8 +45,8 @@ QPDFXRefEntry::getObjStreamNumber() const { if (this->type != 2) { - throw std::logic_error( - "getObjStreamNumber called for xref entry of type != 2"); + throw std::logic_error( + "getObjStreamNumber called for xref entry of type != 2"); } return QIntC::to_int(this->field1); } @@ -56,8 +56,8 @@ QPDFXRefEntry::getObjStreamIndex() const { if (this->type != 2) { - throw std::logic_error( - "getObjStreamIndex called for xref entry of type != 2"); + throw std::logic_error( + "getObjStreamIndex called for xref entry of type != 2"); } return this->field2; } diff --git a/libqpdf/QPDF_Array.cc b/libqpdf/QPDF_Array.cc index 40a58a0c..bc6496f3 100644 --- a/libqpdf/QPDF_Array.cc +++ b/libqpdf/QPDF_Array.cc @@ -31,8 +31,8 @@ QPDF_Array::unparse() size_t size = this->elements.size(); for (size_t i = 0; i < size; ++i) { - result += this->elements.at(i).unparse(); - result += " "; + result += this->elements.at(i).unparse(); + result += " "; } result += "]"; return result; @@ -81,8 +81,8 @@ QPDF_Array::getItem(int n) const { if ((n < 0) || (n >= QIntC::to_int(elements.size()))) { - throw std::logic_error( - "INTERNAL ERROR: bounds error accessing QPDF_Array element"); + throw std::logic_error( + "INTERNAL ERROR: bounds error accessing QPDF_Array element"); } return this->elements.at(QIntC::to_size(n)); } @@ -120,8 +120,8 @@ QPDF_Array::insertItem(int at, QPDFObjectHandle const& item) // As special case, also allow insert beyond the end if ((at < 0) || (at > QIntC::to_int(this->elements.size()))) { - throw std::logic_error( - "INTERNAL ERROR: bounds error accessing QPDF_Array element"); + throw std::logic_error( + "INTERNAL ERROR: bounds error accessing QPDF_Array element"); } this->elements.insert(QIntC::to_size(at), item); } diff --git a/libqpdf/QPDF_Dictionary.cc b/libqpdf/QPDF_Dictionary.cc index 1301d46f..918b46b4 100644 --- a/libqpdf/QPDF_Dictionary.cc +++ b/libqpdf/QPDF_Dictionary.cc @@ -17,10 +17,10 @@ void QPDF_Dictionary::releaseResolved() { for (std::map::iterator iter = - this->items.begin(); - iter != this->items.end(); ++iter) + this->items.begin(); + iter != this->items.end(); ++iter) { - QPDFObjectHandle::ReleaseResolver::releaseResolved((*iter).second); + QPDFObjectHandle::ReleaseResolver::releaseResolved((*iter).second); } } @@ -29,11 +29,11 @@ QPDF_Dictionary::unparse() { std::string result = "<< "; for (std::map::iterator iter = - this->items.begin(); - iter != this->items.end(); ++iter) + this->items.begin(); + iter != this->items.end(); ++iter) { - result += QPDF_Name::normalizeName((*iter).first) + - " " + (*iter).second.unparse() + " "; + result += QPDF_Name::normalizeName((*iter).first) + + " " + (*iter).second.unparse() + " "; } result += ">>"; return result; @@ -44,8 +44,8 @@ QPDF_Dictionary::getJSON() { JSON j = JSON::makeDictionary(); for (std::map::iterator iter = - this->items.begin(); - iter != this->items.end(); ++iter) + this->items.begin(); + iter != this->items.end(); ++iter) { j.addDictionaryMember(QPDF_Name::normalizeName((*iter).first), (*iter).second.getJSON()); @@ -75,7 +75,7 @@ bool QPDF_Dictionary::hasKey(std::string const& key) { return ((this->items.count(key) > 0) && - (! this->items[key].isNull())); + (! this->items[key].isNull())); } QPDFObjectHandle @@ -85,8 +85,8 @@ QPDF_Dictionary::getKey(std::string const& key) // returns the null object. if (this->items.count(key)) { - // May be a null object - return (*(this->items.find(key))).second; + // May be a null object + return (*(this->items.find(key))).second; } else { @@ -98,7 +98,7 @@ QPDF_Dictionary::getKey(std::string const& key) null.setObjectDescription( qpdf, description + " -> dictionary key " + key); } - return null; + return null; } } @@ -107,13 +107,13 @@ QPDF_Dictionary::getKeys() { std::set result; for (std::map::const_iterator iter = - this->items.begin(); - iter != this->items.end(); ++iter) + this->items.begin(); + iter != this->items.end(); ++iter) { - if (hasKey((*iter).first)) - { - result.insert((*iter).first); - } + if (hasKey((*iter).first)) + { + result.insert((*iter).first); + } } return result; } @@ -126,7 +126,7 @@ QPDF_Dictionary::getAsMap() const void QPDF_Dictionary::replaceKey(std::string const& key, - QPDFObjectHandle value) + QPDFObjectHandle value) { // add or replace value this->items[key] = value; @@ -141,14 +141,14 @@ QPDF_Dictionary::removeKey(std::string const& key) void QPDF_Dictionary::replaceOrRemoveKey(std::string const& key, - QPDFObjectHandle value) + QPDFObjectHandle value) { if (value.isNull()) { - removeKey(key); + removeKey(key); } else { - replaceKey(key, value); + replaceKey(key, value); } } diff --git a/libqpdf/QPDF_Name.cc b/libqpdf/QPDF_Name.cc index ffd21af2..7972210c 100644 --- a/libqpdf/QPDF_Name.cc +++ b/libqpdf/QPDF_Name.cc @@ -18,28 +18,28 @@ QPDF_Name::normalizeName(std::string const& name) { if (name.empty()) { - return name; + return name; } std::string result; result += name.at(0); for (size_t i = 1; i < name.length(); ++i) { - char ch = name.at(i); - // Don't use locale/ctype here; follow PDF spec guidelines. + char ch = name.at(i); + // Don't use locale/ctype here; follow PDF spec guidelines. if (ch == '\0') { // QPDFTokenizer embeds a null character to encode an // invalid #. result += "#"; } - else if (strchr("#()<>[]{}/%", ch) || (ch < 33) || (ch > 126)) - { + else if (strchr("#()<>[]{}/%", ch) || (ch < 33) || (ch > 126)) + { result += "#" + QUtil::hex_encode(std::string(&ch, 1)); - } - else - { - result += ch; - } + } + else + { + result += ch; + } } return result; } diff --git a/libqpdf/QPDF_Stream.cc b/libqpdf/QPDF_Stream.cc index ca7fb41e..9e995e1f 100644 --- a/libqpdf/QPDF_Stream.cc +++ b/libqpdf/QPDF_Stream.cc @@ -83,8 +83,8 @@ QPDF_Stream::filter_factories = { }; QPDF_Stream::QPDF_Stream(QPDF* qpdf, int objid, int generation, - QPDFObjectHandle stream_dict, - qpdf_offset_t offset, size_t length) : + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, size_t length) : qpdf(qpdf), objid(objid), generation(generation), @@ -95,9 +95,9 @@ QPDF_Stream::QPDF_Stream(QPDF* qpdf, int objid, int generation, { if (! stream_dict.isDictionary()) { - throw std::logic_error( - "stream object instantiated with non-dictionary " - "object for dictionary"); + throw std::logic_error( + "stream object instantiated with non-dictionary " + "object for dictionary"); } setStreamDescription(); } @@ -138,9 +138,9 @@ QPDF_Stream::setObjGen(int objid, int generation) { if (! ((this->objid == 0) && (this->generation == 0))) { - throw std::logic_error( - "attempt to set object ID and generation of a stream" - " that already has them"); + throw std::logic_error( + "attempt to set object ID and generation of a stream" + " that already has them"); } this->objid = objid; this->generation = generation; @@ -151,7 +151,7 @@ QPDF_Stream::unparse() { // Unparse stream objects as indirect references return QUtil::int_to_string(this->objid) + " " + - QUtil::int_to_string(this->generation) + " R"; + QUtil::int_to_string(this->generation) + " R"; } JSON @@ -246,7 +246,7 @@ QPDF_Stream::getStreamData(qpdf_stream_decode_level_e decode_level) pipeStreamData(&buf, &filtered, 0, decode_level, false, false); if (! filtered) { - throw QPDFExc(qpdf_e_unsupported, qpdf->getFilename(), + throw QPDFExc(qpdf_e_unsupported, qpdf->getFilename(), "", this->offset, "getStreamData called on unfilterable stream"); } @@ -260,7 +260,7 @@ QPDF_Stream::getRawStreamData() Pl_Buffer buf("stream data buffer"); if (! pipeStreamData(&buf, nullptr, 0, qpdf_dl_none, false, false)) { - throw QPDFExc(qpdf_e_unsupported, qpdf->getFilename(), + throw QPDFExc(qpdf_e_unsupported, qpdf->getFilename(), "", this->offset, "error getting raw stream data"); } @@ -283,39 +283,39 @@ QPDF_Stream::filterable( if (filter_obj.isNull()) { - // No filters + // No filters } else if (filter_obj.isName()) { - // One filter - filter_names.push_back(filter_obj.getName()); + // One filter + filter_names.push_back(filter_obj.getName()); } else if (filter_obj.isArray()) { - // Potentially multiple filters - int n = filter_obj.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - QPDFObjectHandle item = filter_obj.getArrayItem(i); - if (item.isName()) - { - filter_names.push_back(item.getName()); - } - else - { - filters_okay = false; - } - } + // Potentially multiple filters + int n = filter_obj.getArrayNItems(); + for (int i = 0; i < n; ++i) + { + QPDFObjectHandle item = filter_obj.getArrayItem(i); + if (item.isName()) + { + filter_names.push_back(item.getName()); + } + else + { + filters_okay = false; + } + } } else { - filters_okay = false; + filters_okay = false; } if (! filters_okay) { - QTC::TC("qpdf", "QPDF_Stream invalid filter"); - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), + QTC::TC("qpdf", "QPDF_Stream invalid filter"); + warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), "", this->offset, "stream filter type is not name or array")); return false; @@ -325,11 +325,11 @@ QPDF_Stream::filterable( for (auto& filter_name: filter_names) { - if (filter_abbreviations.count(filter_name)) - { - QTC::TC("qpdf", "QPDF_Stream expand filter abbreviation"); - filter_name = filter_abbreviations[filter_name]; - } + if (filter_abbreviations.count(filter_name)) + { + QTC::TC("qpdf", "QPDF_Stream expand filter abbreviation"); + filter_name = filter_abbreviations[filter_name]; + } auto ff = filter_factories.find(filter_name); if (ff == filter_factories.end()) @@ -435,7 +435,7 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, bool success = true; if (filter) { - filter = filterable( + filter = filterable( filters, specialized_compression, lossy_compression); if ((decode_level < qpdf_dl_all) && lossy_compression) { @@ -454,9 +454,9 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, if (pipeline == 0) { - QTC::TC("qpdf", "QPDF_Stream pipeStreamData with null pipeline"); + QTC::TC("qpdf", "QPDF_Stream pipeStreamData with null pipeline"); // Return value is whether we can filter in this case. - return filter; + return filter; } // Construct the pipeline in reverse order. Force pipelines we @@ -469,22 +469,22 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, std::shared_ptr new_pipeline; if (filter) { - if (encode_flags & qpdf_ef_compress) - { - new_pipeline = std::make_shared( + if (encode_flags & qpdf_ef_compress) + { + new_pipeline = std::make_shared( "compress stream", pipeline, Pl_Flate::a_deflate); - to_delete.push_back(new_pipeline); + to_delete.push_back(new_pipeline); pipeline = new_pipeline.get(); - } + } - if (encode_flags & qpdf_ef_normalize) - { + if (encode_flags & qpdf_ef_normalize) + { normalizer = make_pointer_holder(); - new_pipeline = std::make_shared( + new_pipeline = std::make_shared( "normalizer", normalizer.get(), pipeline); - to_delete.push_back(new_pipeline); + to_delete.push_back(new_pipeline); pipeline = new_pipeline.get(); - } + } for (auto iter = this->token_filters.rbegin(); iter != this->token_filters.rend(); ++iter) @@ -495,9 +495,9 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, pipeline = new_pipeline.get(); } - for (auto f_iter = filters.rbegin(); + for (auto f_iter = filters.rbegin(); f_iter != filters.rend(); ++f_iter) - { + { auto decode_pipeline = (*f_iter)->getDecodePipeline(pipeline); if (decode_pipeline) { @@ -511,19 +511,19 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, "", this->offset, msg)); }); } - } + } } if (this->stream_data.get()) { - QTC::TC("qpdf", "QPDF_Stream pipe replaced stream data"); - pipeline->write(this->stream_data->getBuffer(), - this->stream_data->getSize()); - pipeline->finish(); + QTC::TC("qpdf", "QPDF_Stream pipe replaced stream data"); + pipeline->write(this->stream_data->getBuffer(), + this->stream_data->getSize()); + pipeline->finish(); } else if (this->stream_provider.get()) { - Pl_Count count("stream provider count", pipeline); + Pl_Count count("stream provider count", pipeline); if (this->stream_provider->supportsRetry()) { if (! this->stream_provider->provideStreamData( @@ -539,11 +539,11 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, this->stream_provider->provideStreamData( this->objid, this->generation, &count); } - qpdf_offset_t actual_length = count.getCount(); - qpdf_offset_t desired_length = 0; + qpdf_offset_t actual_length = count.getCount(); + qpdf_offset_t desired_length = 0; if (success && this->stream_dict.hasKey("/Length")) { - desired_length = this->stream_dict.getKey("/Length").getIntValue(); + desired_length = this->stream_dict.getKey("/Length").getIntValue(); if (actual_length == desired_length) { QTC::TC("qpdf", "QPDF_Stream pipe use stream provider"); @@ -572,14 +572,14 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, } else if (this->offset == 0) { - QTC::TC("qpdf", "QPDF_Stream pipe no stream data"); - throw std::logic_error( - "pipeStreamData called for stream with no data"); + QTC::TC("qpdf", "QPDF_Stream pipe no stream data"); + throw std::logic_error( + "pipeStreamData called for stream with no data"); } else { - QTC::TC("qpdf", "QPDF_Stream pipe original stream data"); - if (! QPDF::Pipe::pipeStreamData(this->qpdf, this->objid, this->generation, + QTC::TC("qpdf", "QPDF_Stream pipe original stream data"); + if (! QPDF::Pipe::pipeStreamData(this->qpdf, this->objid, this->generation, this->offset, this->length, this->stream_dict, pipeline, suppress_warnings, @@ -622,8 +622,8 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, void QPDF_Stream::replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { this->stream_data = data; this->stream_provider = 0; @@ -650,8 +650,8 @@ QPDF_Stream::addTokenFilter( void QPDF_Stream::replaceFilterData(QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms, - size_t length) + QPDFObjectHandle const& decode_parms, + size_t length) { this->stream_dict.replaceOrRemoveKey("/Filter", filter); this->stream_dict.replaceOrRemoveKey("/DecodeParms", decode_parms); diff --git a/libqpdf/QPDF_String.cc b/libqpdf/QPDF_String.cc index 8f10b977..0fcec2d3 100644 --- a/libqpdf/QPDF_String.cc +++ b/libqpdf/QPDF_String.cc @@ -70,102 +70,102 @@ QPDF_String::unparse(bool force_binary) bool use_hexstring = force_binary; if (! use_hexstring) { - unsigned int nonprintable = 0; - int consecutive_printable = 0; - for (unsigned int i = 0; i < this->val.length(); ++i) - { - char ch = this->val.at(i); - // Note: do not use locale to determine printability. The - // PDF specification accepts arbitrary binary data. Some - // locales imply multibyte characters. We'll consider - // something printable if it is printable in 7-bit ASCII. - // We'll code this manually rather than being rude and - // setting locale. - if ((ch == 0) || (! (is_ascii_printable(ch) || - strchr("\n\r\t\b\f", ch)))) - { - ++nonprintable; - consecutive_printable = 0; - } - else - { - if (++consecutive_printable > 5) - { - // If there are more than 5 consecutive printable - // characters, I want to see them as such. - nonprintable = 0; - break; - } - } - } - - // Use hex notation if more than 20% of the characters are not - // printable in plain ASCII. - if (5 * nonprintable > val.length()) - { - use_hexstring = true; - } + unsigned int nonprintable = 0; + int consecutive_printable = 0; + for (unsigned int i = 0; i < this->val.length(); ++i) + { + char ch = this->val.at(i); + // Note: do not use locale to determine printability. The + // PDF specification accepts arbitrary binary data. Some + // locales imply multibyte characters. We'll consider + // something printable if it is printable in 7-bit ASCII. + // We'll code this manually rather than being rude and + // setting locale. + if ((ch == 0) || (! (is_ascii_printable(ch) || + strchr("\n\r\t\b\f", ch)))) + { + ++nonprintable; + consecutive_printable = 0; + } + else + { + if (++consecutive_printable > 5) + { + // If there are more than 5 consecutive printable + // characters, I want to see them as such. + nonprintable = 0; + break; + } + } + } + + // Use hex notation if more than 20% of the characters are not + // printable in plain ASCII. + if (5 * nonprintable > val.length()) + { + use_hexstring = true; + } } std::string result; if (use_hexstring) { - result += "<" + QUtil::hex_encode(this->val) + ">"; + result += "<" + QUtil::hex_encode(this->val) + ">"; } else { - result += "("; - for (unsigned int i = 0; i < this->val.length(); ++i) - { - char ch = this->val.at(i); - switch (ch) - { - case '\n': - result += "\\n"; - break; - - case '\r': - result += "\\r"; - break; - - case '\t': - result += "\\t"; - break; - - case '\b': - result += "\\b"; - break; - - case '\f': - result += "\\f"; - break; - - case '(': - result += "\\("; - break; - - case ')': - result += "\\)"; - break; - - case '\\': - result += "\\\\"; - break; - - default: - if (is_iso_latin1_printable(ch)) - { - result += this->val.at(i); - } - else - { - result += "\\" + QUtil::int_to_string_base( + result += "("; + for (unsigned int i = 0; i < this->val.length(); ++i) + { + char ch = this->val.at(i); + switch (ch) + { + case '\n': + result += "\\n"; + break; + + case '\r': + result += "\\r"; + break; + + case '\t': + result += "\\t"; + break; + + case '\b': + result += "\\b"; + break; + + case '\f': + result += "\\f"; + break; + + case '(': + result += "\\("; + break; + + case ')': + result += "\\)"; + break; + + case '\\': + result += "\\\\"; + break; + + default: + if (is_iso_latin1_printable(ch)) + { + result += this->val.at(i); + } + else + { + result += "\\" + QUtil::int_to_string_base( static_cast(static_cast(ch)), 8, 3); - } - break; - } - } - result += ")"; + } + break; + } + } + result += ")"; } return result; diff --git a/libqpdf/QPDF_encryption.cc b/libqpdf/QPDF_encryption.cc index c97c578d..75b45aef 100644 --- a/libqpdf/QPDF_encryption.cc +++ b/libqpdf/QPDF_encryption.cc @@ -147,7 +147,7 @@ QPDF::trim_user_password(std::string& user_password) size_t len = user_password.length(); if (len < key_bytes) { - return; + return; } char const* p1 = cstr; @@ -155,11 +155,11 @@ QPDF::trim_user_password(std::string& user_password) while ((p2 = strchr(p1, '\x28')) != 0) { size_t idx = toS(p2 - cstr); - if (memcmp(p2, padding_string, len - idx) == 0) - { - user_password = user_password.substr(0, idx); - return; - } + if (memcmp(p2, padding_string, len - idx) == 0) + { + user_password = user_password.substr(0, idx); + return; + } else { QTC::TC("qpdf", "QPDF_encryption skip 0x28"); @@ -191,30 +191,30 @@ iterate_md5_digest(MD5& md5, MD5::Digest& digest, for (int i = 0; i < iterations; ++i) { - MD5 m; - m.encodeDataIncrementally(reinterpret_cast(digest), + MD5 m; + m.encodeDataIncrementally(reinterpret_cast(digest), QIntC::to_size(key_len)); - m.digest(digest); + m.digest(digest); } } static void iterate_rc4(unsigned char* data, size_t data_len, - unsigned char* okey, int key_len, - int iterations, bool reverse) + unsigned char* okey, int key_len, + int iterations, bool reverse) { auto key_ph = std::make_unique(QIntC::to_size(key_len)); unsigned char* key = key_ph.get(); 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] = static_cast(okey[j] ^ xor_value); - } - RC4 rc4(key, QIntC::to_int(key_len)); - rc4.process(data, data_len); + int const xor_value = (reverse ? iterations - 1 - i : i); + for (int j = 0; j < key_len; ++j) + { + key[j] = static_cast(okey[j] ^ xor_value); + } + RC4 rc4(key, QIntC::to_int(key_len)); + rc4.process(data, data_len); } } @@ -354,7 +354,7 @@ void pad_short_parameter(std::string& param, size_t max_len) std::string QPDF::compute_data_key(std::string const& encryption_key, - int objid, int generation, bool use_aes, + int objid, int generation, bool use_aes, int encryption_V, int encryption_R) { // Algorithm 3.1 from the PDF 1.7 Reference Manual @@ -376,7 +376,7 @@ QPDF::compute_data_key(std::string const& encryption_key, result.append(1, static_cast((generation >> 8) & 0xff)); if (use_aes) { - result += "sAlT"; + result += "sAlT"; } MD5 md5; @@ -384,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(), toS(16))); + std::min(result.length(), toS(16))); } std::string @@ -421,7 +421,7 @@ QPDF::compute_encryption_key_from_password( MD5 md5; md5.encodeDataIncrementally( - pad_or_truncate_password_V4(password).c_str(), key_bytes); + pad_or_truncate_password_V4(password).c_str(), key_bytes); md5.encodeDataIncrementally(data.getO().c_str(), key_bytes); char pbytes[4]; int P = data.getP(); @@ -434,9 +434,9 @@ QPDF::compute_encryption_key_from_password( data.getId1().length()); if ((data.getR() >= 4) && (! data.getEncryptMetadata())) { - char bytes[4]; - memset(bytes, 0xff, 4); - md5.encodeDataIncrementally(bytes, 4); + char bytes[4]; + memset(bytes, 0xff, 4); + md5.encodeDataIncrementally(bytes, 4); } MD5::Digest digest; int key_len = @@ -448,23 +448,23 @@ QPDF::compute_encryption_key_from_password( static void compute_O_rc4_key(std::string const& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data, - unsigned char key[OU_key_bytes_V4]) + std::string const& owner_password, + QPDF::EncryptionData const& data, + unsigned char key[OU_key_bytes_V4]) { if (data.getV() >= 5) { - throw std::logic_error( - "compute_O_rc4_key called for file with V >= 5"); + throw std::logic_error( + "compute_O_rc4_key called for file with V >= 5"); } std::string password = owner_password; if (password.empty()) { - password = user_password; + password = user_password; } MD5 md5; md5.encodeDataIncrementally( - pad_or_truncate_password_V4(password).c_str(), key_bytes); + pad_or_truncate_password_V4(password).c_str(), key_bytes); MD5::Digest digest; int key_len = std::min(QIntC::to_int(sizeof(digest)), data.getLengthBytes()); @@ -474,8 +474,8 @@ compute_O_rc4_key(std::string const& user_password, static std::string compute_O_value(std::string const& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data) + std::string const& owner_password, + QPDF::EncryptionData const& data) { // Algorithm 3.3 from the PDF 1.7 Reference Manual @@ -487,7 +487,7 @@ compute_O_value(std::string const& user_password, std::string k1(reinterpret_cast(O_key), OU_key_bytes_V4); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes, - O_key, data.getLengthBytes(), + O_key, data.getLengthBytes(), (data.getR() >= 3) ? 20 : 1, false); return std::string(upass, key_bytes); } @@ -495,7 +495,7 @@ compute_O_value(std::string const& user_password, static std::string compute_U_value_R2(std::string const& user_password, - QPDF::EncryptionData const& data) + QPDF::EncryptionData const& data) { // Algorithm 3.4 from the PDF 1.7 Reference Manual @@ -504,7 +504,7 @@ compute_U_value_R2(std::string const& user_password, pad_or_truncate_password_V4("", udata); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); iterate_rc4(QUtil::unsigned_char_pointer(udata), key_bytes, - QUtil::unsigned_char_pointer(k1), + QUtil::unsigned_char_pointer(k1), data.getLengthBytes(), 1, false); return std::string(udata, key_bytes); } @@ -512,21 +512,21 @@ compute_U_value_R2(std::string const& user_password, static std::string compute_U_value_R3(std::string const& user_password, - QPDF::EncryptionData const& data) + QPDF::EncryptionData const& data) { // Algorithm 3.5 from the PDF 1.7 Reference Manual std::string k1 = QPDF::compute_encryption_key(user_password, data); MD5 md5; md5.encodeDataIncrementally( - pad_or_truncate_password_V4("").c_str(), key_bytes); + pad_or_truncate_password_V4("").c_str(), key_bytes); md5.encodeDataIncrementally(data.getId1().c_str(), data.getId1().length()); MD5::Digest digest; md5.digest(digest); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); iterate_rc4(digest, sizeof(MD5::Digest), - QUtil::unsigned_char_pointer(k1), + QUtil::unsigned_char_pointer(k1), data.getLengthBytes(), 20, false); char result[key_bytes]; memcpy(result, digest, sizeof(MD5::Digest)); @@ -534,18 +534,18 @@ compute_U_value_R3(std::string const& user_password, // testing for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i) { - result[i] = static_cast((i * i) % 0xff); + result[i] = static_cast((i * i) % 0xff); } return std::string(result, key_bytes); } static std::string compute_U_value(std::string const& user_password, - QPDF::EncryptionData const& data) + QPDF::EncryptionData const& data) { if (data.getR() >= 3) { - return compute_U_value_R3(user_password, data); + return compute_U_value_R3(user_password, data); } return compute_U_value_R2(user_password, data); @@ -577,7 +577,7 @@ check_user_password_V5(std::string const& user_password, static bool check_user_password(std::string const& user_password, - QPDF::EncryptionData const& data) + QPDF::EncryptionData const& data) { if (data.getV() < 5) { @@ -632,8 +632,8 @@ check_owner_password_V5(std::string const& owner_password, static bool check_owner_password(std::string& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data) + std::string const& owner_password, + QPDF::EncryptionData const& data) { if (data.getV() < 5) { @@ -773,24 +773,24 @@ QPDF::interpretCF( { if (cf.isName()) { - std::string filter = cf.getName(); - if (encp->crypt_filters.count(filter) != 0) - { - return encp->crypt_filters[filter]; - } - else if (filter == "/Identity") - { - return e_none; - } - else - { - return e_unknown; - } + std::string filter = cf.getName(); + if (encp->crypt_filters.count(filter) != 0) + { + return encp->crypt_filters[filter]; + } + else if (filter == "/Identity") + { + return e_none; + } + else + { + return e_unknown; + } } else { - // Default: /Identity - return e_none; + // Default: /Identity + return e_none; } } @@ -799,7 +799,7 @@ QPDF::initializeEncryption() { if (this->m->encp->encryption_initialized) { - return; + return; } this->m->encp->encryption_initialized = true; @@ -810,7 +810,7 @@ QPDF::initializeEncryption() if (! this->m->trailer.hasKey("/Encrypt")) { - return; + return; } // Go ahead and set this->m->encrypted here. That way, isEncrypted @@ -831,7 +831,7 @@ QPDF::initializeEncryption() // Treating a missing ID as the empty string enables qpdf to // decrypt some invalid encrypted files with no /ID that // poppler can read but Adobe Reader can't. - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "trailer", this->m->file->getLastOffset(), "invalid /ID in trailer dictionary")); } @@ -839,37 +839,37 @@ QPDF::initializeEncryption() QPDFObjectHandle encryption_dict = this->m->trailer.getKey("/Encrypt"); if (! encryption_dict.isDictionary()) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "/Encrypt in trailer dictionary is not a dictionary"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "/Encrypt in trailer dictionary is not a dictionary"); } if (! (encryption_dict.getKey("/Filter").isName() && - (encryption_dict.getKey("/Filter").getName() == "/Standard"))) + (encryption_dict.getKey("/Filter").getName() == "/Standard"))) { throw QPDFExc(qpdf_e_unsupported, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "unsupported encryption filter"); + "encryption dictionary", this->m->file->getLastOffset(), + "unsupported encryption filter"); } if (! encryption_dict.getKey("/SubFilter").isNull()) { - warn(QPDFExc(qpdf_e_unsupported, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "file uses encryption SubFilters," - " which qpdf does not support")); + warn(QPDFExc(qpdf_e_unsupported, this->m->file->getName(), + "encryption dictionary", this->m->file->getLastOffset(), + "file uses encryption SubFilters," + " which qpdf does not support")); } if (! (encryption_dict.getKey("/V").isInteger() && - encryption_dict.getKey("/R").isInteger() && - encryption_dict.getKey("/O").isString() && - encryption_dict.getKey("/U").isString() && - encryption_dict.getKey("/P").isInteger())) + encryption_dict.getKey("/R").isInteger() && + encryption_dict.getKey("/O").isString() && + encryption_dict.getKey("/U").isString() && + encryption_dict.getKey("/P").isInteger())) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "some encryption dictionary parameters are missing " - "or the wrong type"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "encryption dictionary", this->m->file->getLastOffset(), + "some encryption dictionary parameters are missing " + "or the wrong type"); } int V = encryption_dict.getKey("/V").getIntValueAsInt(); @@ -881,11 +881,11 @@ QPDF::initializeEncryption() // If supporting new encryption R/V values, remember to update // error message inside this if statement. if (! (((R >= 2) && (R <= 6)) && - ((V == 1) || (V == 2) || (V == 4) || (V == 5)))) + ((V == 1) || (V == 2) || (V == 4) || (V == 5)))) { - throw QPDFExc(qpdf_e_unsupported, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "Unsupported /R or /V in encryption dictionary; R = " + + throw QPDFExc(qpdf_e_unsupported, this->m->file->getName(), + "encryption dictionary", this->m->file->getLastOffset(), + "Unsupported /R or /V in encryption dictionary; R = " + QUtil::int_to_string(R) + " (max 6), V = " + QUtil::int_to_string(V) + " (max 5)"); } @@ -969,58 +969,58 @@ QPDF::initializeEncryption() this->m->encp->encrypt_metadata = true; if ((V >= 4) && (encryption_dict.getKey("/EncryptMetadata").isBool())) { - this->m->encp->encrypt_metadata = - encryption_dict.getKey("/EncryptMetadata").getBoolValue(); + this->m->encp->encrypt_metadata = + encryption_dict.getKey("/EncryptMetadata").getBoolValue(); } if ((V == 4) || (V == 5)) { - QPDFObjectHandle CF = encryption_dict.getKey("/CF"); - std::set keys = CF.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - std::string const& filter = *iter; - QPDFObjectHandle cdict = CF.getKey(filter); - if (cdict.isDictionary()) - { - encryption_method_e method = e_none; - if (cdict.getKey("/CFM").isName()) - { - std::string method_name = cdict.getKey("/CFM").getName(); - if (method_name == "/V2") - { - QTC::TC("qpdf", "QPDF_encryption CFM V2"); - method = e_rc4; - } - else if (method_name == "/AESV2") - { - QTC::TC("qpdf", "QPDF_encryption CFM AESV2"); - method = e_aes; - } - else if (method_name == "/AESV3") - { - QTC::TC("qpdf", "QPDF_encryption CFM AESV3"); - method = e_aesv3; - } - else - { - // Don't complain now -- maybe we won't need - // to reference this type. - method = e_unknown; - } - } - this->m->encp->crypt_filters[filter] = method; - } - } - - QPDFObjectHandle StmF = encryption_dict.getKey("/StmF"); - QPDFObjectHandle StrF = encryption_dict.getKey("/StrF"); - QPDFObjectHandle EFF = encryption_dict.getKey("/EFF"); - this->m->encp->cf_stream = interpretCF(this->m->encp, StmF); - this->m->encp->cf_string = interpretCF(this->m->encp, StrF); - if (EFF.isName()) - { + QPDFObjectHandle CF = encryption_dict.getKey("/CF"); + std::set keys = CF.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + std::string const& filter = *iter; + QPDFObjectHandle cdict = CF.getKey(filter); + if (cdict.isDictionary()) + { + encryption_method_e method = e_none; + if (cdict.getKey("/CFM").isName()) + { + std::string method_name = cdict.getKey("/CFM").getName(); + if (method_name == "/V2") + { + QTC::TC("qpdf", "QPDF_encryption CFM V2"); + method = e_rc4; + } + else if (method_name == "/AESV2") + { + QTC::TC("qpdf", "QPDF_encryption CFM AESV2"); + method = e_aes; + } + else if (method_name == "/AESV3") + { + QTC::TC("qpdf", "QPDF_encryption CFM AESV3"); + method = e_aesv3; + } + else + { + // Don't complain now -- maybe we won't need + // to reference this type. + method = e_unknown; + } + } + this->m->encp->crypt_filters[filter] = method; + } + } + + QPDFObjectHandle StmF = encryption_dict.getKey("/StmF"); + QPDFObjectHandle StrF = encryption_dict.getKey("/StrF"); + QPDFObjectHandle EFF = encryption_dict.getKey("/EFF"); + this->m->encp->cf_stream = interpretCF(this->m->encp, StmF); + this->m->encp->cf_string = interpretCF(this->m->encp, StrF); + if (EFF.isName()) + { // qpdf does not use this for anything other than // informational purposes. This is intended to instruct // conforming writers on which crypt filter should be used @@ -1035,12 +1035,12 @@ QPDF::initializeEncryption() // at a file generated by something else, such as Acrobat // when specifying that only attachments should be // encrypted. - this->m->encp->cf_file = interpretCF(this->m->encp, EFF); - } - else - { - this->m->encp->cf_file = this->m->encp->cf_stream; - } + this->m->encp->cf_file = interpretCF(this->m->encp, EFF); + } + else + { + this->m->encp->cf_file = this->m->encp->cf_stream; + } } EncryptionData data(V, R, Length / 8, @@ -1128,19 +1128,19 @@ QPDF::getKeyForObject( { if (! encp->encrypted) { - throw std::logic_error( - "request for encryption key in non-encrypted PDF"); + throw std::logic_error( + "request for encryption key in non-encrypted PDF"); } if (! ((objid == encp->cached_key_objid) && - (generation == encp->cached_key_generation))) + (generation == encp->cached_key_generation))) { - encp->cached_object_encryption_key = - compute_data_key(encp->encryption_key, objid, generation, + encp->cached_object_encryption_key = + compute_data_key(encp->encryption_key, objid, generation, use_aes, encp->encryption_V, encp->encryption_R); - encp->cached_key_objid = objid; - encp->cached_key_generation = generation; + encp->cached_key_objid = objid; + encp->cached_key_generation = generation; } return encp->cached_object_encryption_key; @@ -1151,83 +1151,83 @@ QPDF::decryptString(std::string& str, int objid, int generation) { if (objid == 0) { - return; + return; } bool use_aes = false; if (this->m->encp->encryption_V >= 4) { - switch (this->m->encp->cf_string) - { - case e_none: - return; - - case e_aes: - use_aes = true; - break; - - case e_aesv3: - use_aes = true; - break; - - case e_rc4: - break; - - default: - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "unknown encryption filter for strings" - " (check /StrF in /Encrypt dictionary);" - " strings may be decrypted improperly")); - // To avoid repeated warnings, reset cf_string. Assume - // we'd want to use AES if V == 4. - this->m->encp->cf_string = e_aes; + switch (this->m->encp->cf_string) + { + case e_none: + return; + + case e_aes: + use_aes = true; + break; + + case e_aesv3: + use_aes = true; + break; + + case e_rc4: + break; + + default: + warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "unknown encryption filter for strings" + " (check /StrF in /Encrypt dictionary);" + " strings may be decrypted improperly")); + // To avoid repeated warnings, reset cf_string. Assume + // we'd want to use AES if V == 4. + this->m->encp->cf_string = e_aes; use_aes = true; - break; - } + break; + } } std::string key = getKeyForObject( this->m->encp, objid, generation, use_aes); try { - if (use_aes) - { - QTC::TC("qpdf", "QPDF_encryption aes decode string"); - Pl_Buffer bufpl("decrypted string"); - Pl_AES_PDF pl("aes decrypt string", &bufpl, false, - QUtil::unsigned_char_pointer(key), + if (use_aes) + { + QTC::TC("qpdf", "QPDF_encryption aes decode string"); + Pl_Buffer bufpl("decrypted string"); + Pl_AES_PDF pl("aes decrypt string", &bufpl, false, + QUtil::unsigned_char_pointer(key), key.length()); - pl.write(QUtil::unsigned_char_pointer(str), str.length()); - pl.finish(); - auto buf = bufpl.getBufferSharedPointer(); - str = std::string(reinterpret_cast(buf->getBuffer()), + pl.write(QUtil::unsigned_char_pointer(str), str.length()); + pl.finish(); + auto buf = bufpl.getBufferSharedPointer(); + str = std::string(reinterpret_cast(buf->getBuffer()), buf->getSize()); - } - else - { - QTC::TC("qpdf", "QPDF_encryption rc4 decode string"); - size_t vlen = str.length(); - // Using PointerHolder guarantees that tmp will - // be freed even if rc4.process throws an exception. - auto tmp = QUtil::make_unique_cstr(str); - RC4 rc4(QUtil::unsigned_char_pointer(key), toI(key.length())); - rc4.process(QUtil::unsigned_char_pointer(tmp.get()), vlen); - str = std::string(tmp.get(), vlen); - } + } + else + { + QTC::TC("qpdf", "QPDF_encryption rc4 decode string"); + size_t vlen = str.length(); + // Using PointerHolder guarantees that tmp will + // be freed even if rc4.process throws an exception. + auto tmp = QUtil::make_unique_cstr(str); + RC4 rc4(QUtil::unsigned_char_pointer(key), toI(key.length())); + rc4.process(QUtil::unsigned_char_pointer(tmp.get()), vlen); + str = std::string(tmp.get(), vlen); + } } catch (QPDFExc&) { - throw; + throw; } catch (std::runtime_error& e) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "error decrypting string for object " + - QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation) + ": " + e.what()); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "error decrypting string for object " + + QUtil::int_to_string(objid) + " " + + QUtil::int_to_string(generation) + ": " + e.what()); } } @@ -1236,26 +1236,26 @@ QPDF::decryptStream(PointerHolder encp, PointerHolder file, QPDF& qpdf_for_warning, Pipeline*& pipeline, int objid, int generation, - QPDFObjectHandle& stream_dict, - std::vector>& heap) + QPDFObjectHandle& stream_dict, + std::vector>& heap) { std::string type; if (stream_dict.getKey("/Type").isName()) { - type = stream_dict.getKey("/Type").getName(); + type = stream_dict.getKey("/Type").getName(); } if (type == "/XRef") { - QTC::TC("qpdf", "QPDF_encryption xref stream from encrypted file"); - return; + QTC::TC("qpdf", "QPDF_encryption xref stream from encrypted file"); + return; } bool use_aes = false; if (encp->encryption_V >= 4) { - encryption_method_e method = e_unknown; - std::string method_source = "/StmF from /Encrypt dictionary"; + encryption_method_e method = e_unknown; + std::string method_source = "/StmF from /Encrypt dictionary"; - if (stream_dict.getKey("/Filter").isOrHasName("/Crypt")) + if (stream_dict.getKey("/Filter").isOrHasName("/Crypt")) { if (stream_dict.getKey("/DecodeParms").isDictionary()) { @@ -1294,67 +1294,67 @@ QPDF::decryptStream(PointerHolder encp, } } } - } - - if (method == e_unknown) - { - if ((! encp->encrypt_metadata) && (type == "/Metadata")) - { - QTC::TC("qpdf", "QPDF_encryption cleartext metadata"); - method = e_none; - } - else - { + } + + if (method == e_unknown) + { + if ((! encp->encrypt_metadata) && (type == "/Metadata")) + { + QTC::TC("qpdf", "QPDF_encryption cleartext metadata"); + method = e_none; + } + else + { method = encp->cf_stream; - } - } - use_aes = false; - switch (method) - { - case e_none: - return; - break; - - case e_aes: - use_aes = true; - break; - - case e_aesv3: - use_aes = true; - break; - - case e_rc4: - break; - - default: - // filter local to this stream. - qpdf_for_warning.warn( + } + } + use_aes = false; + switch (method) + { + case e_none: + return; + break; + + case e_aes: + use_aes = true; + break; + + case e_aesv3: + use_aes = true; + break; + + case e_rc4: + break; + + default: + // filter local to this stream. + qpdf_for_warning.warn( QPDFExc(qpdf_e_damaged_pdf, file->getName(), "", file->getLastOffset(), "unknown encryption filter for streams" " (check " + method_source + ");" " streams may be decrypted improperly")); - // To avoid repeated warnings, reset cf_stream. Assume - // we'd want to use AES if V == 4. - encp->cf_stream = e_aes; + // To avoid repeated warnings, reset cf_stream. Assume + // we'd want to use AES if V == 4. + encp->cf_stream = e_aes; use_aes = true; - break; - } + break; + } } std::string key = getKeyForObject(encp, objid, generation, use_aes); std::shared_ptr new_pipeline; if (use_aes) { - QTC::TC("qpdf", "QPDF_encryption aes decode stream"); - new_pipeline = std::make_shared( + QTC::TC("qpdf", "QPDF_encryption aes decode stream"); + new_pipeline = std::make_shared( "AES stream decryption", pipeline, false, QUtil::unsigned_char_pointer(key), key.length()); } else { - QTC::TC("qpdf", "QPDF_encryption rc4 decode stream"); - new_pipeline = std::make_shared( + QTC::TC("qpdf", "QPDF_encryption rc4 decode stream"); + new_pipeline = std::make_shared( "RC4 stream decryption", pipeline, QUtil::unsigned_char_pointer(key), toI(key.length())); @@ -1371,8 +1371,8 @@ QPDF::compute_encryption_O_U( { if (V >= 5) { - throw std::logic_error( - "compute_encryption_O_U called for file with V >= 5"); + throw std::logic_error( + "compute_encryption_O_U called for file with V >= 5"); } EncryptionData data(V, R, key_len, P, "", "", "", "", "", id1, encrypt_metadata); @@ -1444,22 +1444,22 @@ QPDF::isEncrypted(int& R, int& P, int& V, { if (this->m->encp->encrypted) { - QPDFObjectHandle trailer = getTrailer(); - QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); - QPDFObjectHandle Pkey = encrypt.getKey("/P"); - QPDFObjectHandle Rkey = encrypt.getKey("/R"); + QPDFObjectHandle trailer = getTrailer(); + QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); + QPDFObjectHandle Pkey = encrypt.getKey("/P"); + QPDFObjectHandle Rkey = encrypt.getKey("/R"); QPDFObjectHandle Vkey = encrypt.getKey("/V"); - P = static_cast(Pkey.getIntValue()); - R = Rkey.getIntValueAsInt(); + P = static_cast(Pkey.getIntValue()); + 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; - return true; + return true; } else { - return false; + return false; } } @@ -1490,14 +1490,14 @@ QPDF::allowAccessibility() bool status = true; if (isEncrypted(R, P)) { - if (R < 3) - { - status = is_bit_set(P, 5); - } - else - { - status = is_bit_set(P, 10); - } + if (R < 3) + { + status = is_bit_set(P, 5); + } + else + { + status = is_bit_set(P, 10); + } } return status; } @@ -1510,7 +1510,7 @@ QPDF::allowExtractAll() bool status = true; if (isEncrypted(R, P)) { - status = is_bit_set(P, 5); + status = is_bit_set(P, 5); } return status; } @@ -1523,7 +1523,7 @@ QPDF::allowPrintLowRes() bool status = true; if (isEncrypted(R, P)) { - status = is_bit_set(P, 3); + status = is_bit_set(P, 3); } return status; } @@ -1536,11 +1536,11 @@ QPDF::allowPrintHighRes() bool status = true; if (isEncrypted(R, P)) { - status = is_bit_set(P, 3); - if ((R >= 3) && (! is_bit_set(P, 12))) - { - status = false; - } + status = is_bit_set(P, 3); + if ((R >= 3) && (! is_bit_set(P, 12))) + { + status = false; + } } return status; } @@ -1553,14 +1553,14 @@ QPDF::allowModifyAssembly() bool status = true; if (isEncrypted(R, P)) { - if (R < 3) - { - status = is_bit_set(P, 4); - } - else - { - status = is_bit_set(P, 11); - } + if (R < 3) + { + status = is_bit_set(P, 4); + } + else + { + status = is_bit_set(P, 11); + } } return status; } @@ -1573,14 +1573,14 @@ QPDF::allowModifyForm() bool status = true; if (isEncrypted(R, P)) { - if (R < 3) - { - status = is_bit_set(P, 6); - } - else - { - status = is_bit_set(P, 9); - } + if (R < 3) + { + status = is_bit_set(P, 6); + } + else + { + status = is_bit_set(P, 9); + } } return status; } @@ -1593,7 +1593,7 @@ QPDF::allowModifyAnnotation() bool status = true; if (isEncrypted(R, P)) { - status = is_bit_set(P, 6); + status = is_bit_set(P, 6); } return status; } @@ -1606,7 +1606,7 @@ QPDF::allowModifyOther() bool status = true; if (isEncrypted(R, P)) { - status = is_bit_set(P, 4); + status = is_bit_set(P, 4); } return status; } @@ -1619,11 +1619,11 @@ QPDF::allowModifyAll() bool status = true; if (isEncrypted(R, P)) { - status = (is_bit_set(P, 4) && is_bit_set(P, 6)); - if (R >= 3) - { - status = status && (is_bit_set(P, 9) && is_bit_set(P, 11)); - } + status = (is_bit_set(P, 4) && is_bit_set(P, 6)); + if (R >= 3) + { + status = status && (is_bit_set(P, 9) && is_bit_set(P, 11)); + } } return status; } diff --git a/libqpdf/QPDF_linearization.cc b/libqpdf/QPDF_linearization.cc index a107ced7..443ae662 100644 --- a/libqpdf/QPDF_linearization.cc +++ b/libqpdf/QPDF_linearization.cc @@ -20,7 +20,7 @@ template static void load_vector_int(BitStream& bit_stream, int nitems, std::vector& vec, - int bits_wanted, int_type T::*field) + int bits_wanted, int_type T::*field) { bool append = vec.empty(); // nitems times, read bits_wanted from the given bit stream, @@ -32,7 +32,7 @@ load_vector_int(BitStream& bit_stream, int nitems, std::vector& vec, { vec.push_back(T()); } - vec.at(i).*field = bit_stream.getBitsInt(QIntC::to_size(bits_wanted)); + vec.at(i).*field = bit_stream.getBitsInt(QIntC::to_size(bits_wanted)); } if (QIntC::to_int(vec.size()) != nitems) { @@ -46,18 +46,18 @@ load_vector_int(BitStream& bit_stream, int nitems, std::vector& vec, template static void load_vector_vector(BitStream& bit_stream, - int nitems1, std::vector& vec1, int T::*nitems2, - int bits_wanted, std::vector T::*vec2) + int nitems1, std::vector& vec1, int T::*nitems2, + int bits_wanted, std::vector T::*vec2) { // nitems1 times, read nitems2 (from the ith element of vec1) items // into the vec2 vector field of the ith item of vec1. 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( + for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) + { + (vec1.at(i1).*vec2).push_back( bit_stream.getBitsInt(QIntC::to_size(bits_wanted))); - } + } } bit_stream.skipToNextByte(); } @@ -68,12 +68,12 @@ QPDF::checkLinearization() bool result = false; try { - readLinearizationData(); - result = checkLinearizationInternal(); + readLinearizationData(); + result = checkLinearizationInternal(); } catch (std::runtime_error& e) { - *this->m->err_stream + *this->m->err_stream << "WARNING: error encountered while checking linearization data: " << e.what() << std::endl; } @@ -133,44 +133,44 @@ QPDF::isLinearized() (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj")) && (t4.getType() == QPDFTokenizer::tt_dict_open)) { - lindict_obj = + lindict_obj = QIntC::to_int(QUtil::string_to_ll(t1.getValue().c_str())); - } + } } if (lindict_obj <= 0) { - return false; + return false; } QPDFObjectHandle candidate = QPDFObjectHandle::Factory::newIndirect( - this, lindict_obj, 0); + this, lindict_obj, 0); if (! candidate.isDictionary()) { - return false; + return false; } QPDFObjectHandle linkey = candidate.getKey("/Linearized"); if (! (linkey.isNumber() && (QIntC::to_int(floor(linkey.getNumericValue())) == 1))) { - return false; + return false; } QPDFObjectHandle L = candidate.getKey("/L"); if (L.isInteger()) { - qpdf_offset_t Li = L.getIntValue(); - this->m->file->seek(0, SEEK_END); - if (Li != this->m->file->tell()) - { - QTC::TC("qpdf", "QPDF /L mismatch"); - return false; - } - else - { - this->m->linp.file_size = Li; - } + qpdf_offset_t Li = L.getIntValue(); + this->m->file->seek(0, SEEK_END); + if (Li != this->m->file->tell()) + { + QTC::TC("qpdf", "QPDF /L mismatch"); + return false; + } + else + { + this->m->linp.file_size = Li; + } } this->m->lindict = candidate; @@ -189,8 +189,8 @@ QPDF::readLinearizationData() if (! isLinearized()) { - throw std::logic_error("called readLinearizationData for file" - " that is not linearized"); + throw std::logic_error("called readLinearizationData for file" + " that is not linearized"); } // /L is read and stored in linp by isLinearized() @@ -202,44 +202,44 @@ QPDF::readLinearizationData() QPDFObjectHandle P = this->m->lindict.getKey("/P"); if (! (H.isArray() && - O.isInteger() && - E.isInteger() && - N.isInteger() && - T.isInteger() && - (P.isInteger() || P.isNull()))) + O.isInteger() && + E.isInteger() && + N.isInteger() && + T.isInteger() && + (P.isInteger() || P.isNull()))) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "some keys in linearization dictionary are of " - "the wrong type"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "some keys in linearization dictionary are of " + "the wrong type"); } // Hint table array: offset length [ offset length ] 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(), - "linearization dictionary", - this->m->file->getLastOffset(), - "H has the wrong number of items"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "H has the wrong number of items"); } std::vector H_items; for (size_t i = 0; i < n_H_items; ++i) { - QPDFObjectHandle oh(H.getArrayItem(toI(i))); - if (oh.isInteger()) - { - H_items.push_back(oh.getIntValueAsInt()); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "some H items are of the wrong type"); - } + QPDFObjectHandle oh(H.getArrayItem(toI(i))); + if (oh.isInteger()) + { + H_items.push_back(oh.getIntValueAsInt()); + } + else + { + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "some H items are of the wrong type"); + } } // H: hint table offset/length for primary and overflow hint tables @@ -249,23 +249,23 @@ QPDF::readLinearizationData() int H1_length = 0; if (H_items.size() == 4) { - // Acrobat doesn't read or write these (as PDF 1.4), so we - // don't have a way to generate a test case. - // QTC::TC("qpdf", "QPDF overflow hint table"); - H1_offset = H_items.at(2); - H1_length = H_items.at(3); + // Acrobat doesn't read or write these (as PDF 1.4), so we + // don't have a way to generate a test case. + // QTC::TC("qpdf", "QPDF overflow hint table"); + H1_offset = H_items.at(2); + H1_length = H_items.at(3); } // P: first page number int first_page = 0; if (P.isInteger()) { - QTC::TC("qpdf", "QPDF P present in lindict"); - first_page = P.getIntValueAsInt(); + QTC::TC("qpdf", "QPDF P present in lindict"); + first_page = P.getIntValueAsInt(); } else { - QTC::TC("qpdf", "QPDF P absent in lindict"); + QTC::TC("qpdf", "QPDF P absent in lindict"); } // Store linearization parameter data @@ -296,7 +296,7 @@ QPDF::readLinearizationData() QPDFObjectHandle H0 = readHintStream(pb, H0_offset, toS(H0_length)); if (H1_offset) { - (void) readHintStream(pb, H1_offset, toS(H1_length)); + (void) readHintStream(pb, H1_offset, toS(H1_length)); } // PDF 1.4 hint tables that we ignore: @@ -332,7 +332,7 @@ QPDF::readLinearizationData() if (HO.isInteger()) { - int HOi = HO.getIntValueAsInt(); + int HOi = HO.getIntValueAsInt(); if ((HOi < 0) || (toS(HOi) >= h_size)) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), @@ -340,8 +340,8 @@ QPDF::readLinearizationData() this->m->file->getLastOffset(), "/O (outline) offset is out of bounds"); } - readHGeneric(BitStream(h_buf + HOi, h_size - toS(HOi)), - this->m->outline_hints); + readHGeneric(BitStream(h_buf + HOi, h_size - toS(HOi)), + this->m->outline_hints); } } @@ -351,16 +351,16 @@ QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length) int obj; int gen; QPDFObjectHandle H = readObjectAtOffset( - false, offset, "linearization hint stream", -1, 0, obj, gen); + false, offset, "linearization hint stream", -1, 0, obj, gen); ObjCache& oc = this->m->obj_cache[QPDFObjGen(obj, gen)]; qpdf_offset_t min_end_offset = oc.end_before_space; qpdf_offset_t max_end_offset = oc.end_after_space; if (! H.isStream()) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "hint table is not a stream"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "hint table is not a stream"); } QPDFObjectHandle Hdict = H.getDict(); @@ -373,28 +373,28 @@ QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length) QPDFObjectHandle length_obj = Hdict.getKey("/Length"); if (length_obj.isIndirect()) { - QTC::TC("qpdf", "QPDF hint table length indirect"); - // Force resolution - (void) length_obj.getIntValue(); - ObjCache& oc2 = this->m->obj_cache[length_obj.getObjGen()]; - min_end_offset = oc2.end_before_space; - max_end_offset = oc2.end_after_space; + QTC::TC("qpdf", "QPDF hint table length indirect"); + // Force resolution + (void) length_obj.getIntValue(); + ObjCache& oc2 = this->m->obj_cache[length_obj.getObjGen()]; + min_end_offset = oc2.end_before_space; + max_end_offset = oc2.end_after_space; } else { - QTC::TC("qpdf", "QPDF hint table length direct"); + QTC::TC("qpdf", "QPDF hint table length direct"); } qpdf_offset_t computed_end = offset + toO(length); if ((computed_end < min_end_offset) || - (computed_end > max_end_offset)) + (computed_end > max_end_offset)) { - *this->m->err_stream << "expected = " << computed_end + *this->m->err_stream << "expected = " << computed_end << "; actual = " << min_end_offset << ".." << max_end_offset << std::endl; - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "hint table length mismatch"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "hint table length mismatch"); } H.pipeStreamData(&pl, 0, qpdf_dl_specialized); return Hdict; @@ -426,28 +426,28 @@ QPDF::readHPageOffset(BitStream h) entries.clear(); int nitems = this->m->linp.npages; load_vector_int(h, nitems, entries, - t.nbits_delta_nobjects, - &HPageOffsetEntry::delta_nobjects); + t.nbits_delta_nobjects, + &HPageOffsetEntry::delta_nobjects); load_vector_int(h, nitems, entries, - t.nbits_delta_page_length, - &HPageOffsetEntry::delta_page_length); + t.nbits_delta_page_length, + &HPageOffsetEntry::delta_page_length); load_vector_int(h, nitems, entries, - t.nbits_nshared_objects, - &HPageOffsetEntry::nshared_objects); + t.nbits_nshared_objects, + &HPageOffsetEntry::nshared_objects); load_vector_vector(h, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_identifier, - &HPageOffsetEntry::shared_identifiers); + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_identifier, + &HPageOffsetEntry::shared_identifiers); load_vector_vector(h, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_numerator, - &HPageOffsetEntry::shared_numerators); + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_numerator, + &HPageOffsetEntry::shared_numerators); load_vector_int(h, nitems, entries, - t.nbits_delta_content_offset, - &HPageOffsetEntry::delta_content_offset); + t.nbits_delta_content_offset, + &HPageOffsetEntry::delta_content_offset); load_vector_int(h, nitems, entries, - t.nbits_delta_content_length, - &HPageOffsetEntry::delta_content_length); + t.nbits_delta_content_length, + &HPageOffsetEntry::delta_content_length); } void @@ -464,32 +464,32 @@ QPDF::readHSharedObject(BitStream h) 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); + (t.nshared_total > t.nshared_first_page) ? 1 : 0); std::vector& entries = t.entries; entries.clear(); int nitems = t.nshared_total; load_vector_int(h, nitems, entries, - t.nbits_delta_group_length, - &HSharedObjectEntry::delta_group_length); + t.nbits_delta_group_length, + &HSharedObjectEntry::delta_group_length); load_vector_int(h, nitems, entries, - 1, &HSharedObjectEntry::signature_present); + 1, &HSharedObjectEntry::signature_present); for (size_t i = 0; i < toS(nitems); ++i) { - if (entries.at(i).signature_present) - { - // Skip 128-bit MD5 hash. These are not supported by - // acrobat, so they should probably never be there. We - // have no test case for this. - for (int j = 0; j < 4; ++j) - { - (void) h.getBits(32); - } - } + if (entries.at(i).signature_present) + { + // Skip 128-bit MD5 hash. These are not supported by + // acrobat, so they should probably never be there. We + // have no test case for this. + for (int j = 0; j < 4; ++j) + { + (void) h.getBits(32); + } + } } load_vector_int(h, nitems, entries, - t.nbits_nobjects, - &HSharedObjectEntry::nobjects_minus_one); + t.nbits_nobjects, + &HSharedObjectEntry::nobjects_minus_one); } void @@ -520,49 +520,49 @@ QPDF::checkLinearizationInternal() std::vector const& pages = getAllPages(); if (p.first_page_object != pages.at(0).getObjectID()) { - QTC::TC("qpdf", "QPDF err /O mismatch"); - errors.push_back("first page object (/O) mismatch"); + QTC::TC("qpdf", "QPDF err /O mismatch"); + errors.push_back("first page object (/O) mismatch"); } // N: number of pages int npages = toI(pages.size()); if (p.npages != npages) { - // Not tested in the test suite - errors.push_back("page count (/N) mismatch"); + // Not tested in the test suite + errors.push_back("page count (/N) mismatch"); } 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::uint_to_string(i) + " is compressed"); - } + 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::uint_to_string(i) + " is compressed"); + } } // T: offset of whitespace character preceding xref entry for object 0 this->m->file->seek(p.xref_zero_offset, SEEK_SET); while (1) { - char ch; - this->m->file->read(&ch, 1); - if (! ((ch == ' ') || (ch == '\r') || (ch == '\n'))) - { - this->m->file->seek(-1, SEEK_CUR); - break; - } + char ch; + this->m->file->read(&ch, 1); + if (! ((ch == ' ') || (ch == '\r') || (ch == '\n'))) + { + this->m->file->seek(-1, SEEK_CUR); + break; + } } if (this->m->file->tell() != this->m->first_xref_item_offset) { - QTC::TC("qpdf", "QPDF err /T mismatch"); - errors.push_back("space before first xref item (/T) mismatch " - "(computed = " + - QUtil::int_to_string(this->m->first_xref_item_offset) + - "; file = " + - QUtil::int_to_string(this->m->file->tell())); + QTC::TC("qpdf", "QPDF err /T mismatch"); + errors.push_back("space before first xref item (/T) mismatch " + "(computed = " + + QUtil::int_to_string(this->m->first_xref_item_offset) + + "; file = " + + QUtil::int_to_string(this->m->file->tell())); } // P: first page number -- Implementation note 124 says Acrobat @@ -575,8 +575,8 @@ QPDF::checkLinearizationInternal() if (this->m->uncompressed_after_compressed) { - errors.push_back("linearized file contains an uncompressed object" - " after a compressed one in a cross-reference stream"); + errors.push_back("linearized file contains an uncompressed object" + " after a compressed one in a cross-reference stream"); } // Further checking requires optimization and order calculation. @@ -585,20 +585,20 @@ QPDF::checkLinearizationInternal() // figure out which objects are compressed and which are // uncompressed. { // local scope - std::map object_stream_data; - for (std::map::const_iterator iter = - this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { - QPDFObjGen const& og = (*iter).first; - QPDFXRefEntry const& entry = (*iter).second; - if (entry.getType() == 2) - { - object_stream_data[og.getObj()] = entry.getObjStreamNumber(); - } - } - optimize(object_stream_data, false); - calculateLinearizationData(object_stream_data); + std::map object_stream_data; + for (std::map::const_iterator iter = + this->m->xref_table.begin(); + iter != this->m->xref_table.end(); ++iter) + { + QPDFObjGen const& og = (*iter).first; + QPDFXRefEntry const& entry = (*iter).second; + if (entry.getType() == 2) + { + object_stream_data[og.getObj()] = entry.getObjStreamNumber(); + } + } + optimize(object_stream_data, false); + calculateLinearizationData(object_stream_data); } // E: offset of end of first page -- Implementation note 123 says @@ -619,26 +619,26 @@ QPDF::checkLinearizationInternal() qpdf_offset_t min_E = -1; qpdf_offset_t max_E = -1; for (std::vector::iterator iter = this->m->part6.begin(); - iter != this->m->part6.end(); ++iter) + iter != this->m->part6.end(); ++iter) { - QPDFObjGen og((*iter).getObjGen()); - if (this->m->obj_cache.count(og) == 0) + QPDFObjGen og((*iter).getObjGen()); + if (this->m->obj_cache.count(og) == 0) { // All objects have to have been dereferenced to be classified. throw std::logic_error("linearization part6 object not in cache"); } - ObjCache const& oc = this->m->obj_cache[og]; - min_E = std::max(min_E, oc.end_before_space); - max_E = std::max(max_E, oc.end_after_space); + ObjCache const& oc = this->m->obj_cache[og]; + min_E = std::max(min_E, oc.end_before_space); + max_E = std::max(max_E, oc.end_after_space); } if ((p.first_page_end < min_E) || (p.first_page_end > max_E)) { - QTC::TC("qpdf", "QPDF warn /E mismatch"); - warnings.push_back("end of first page section (/E) mismatch: /E = " + - QUtil::int_to_string(p.first_page_end) + - "; computed = " + - QUtil::int_to_string(min_E) + ".." + - QUtil::int_to_string(max_E)); + QTC::TC("qpdf", "QPDF warn /E mismatch"); + warnings.push_back("end of first page section (/E) mismatch: /E = " + + QUtil::int_to_string(p.first_page_end) + + "; computed = " + + QUtil::int_to_string(min_E) + ".." + + QUtil::int_to_string(max_E)); } // Check hint tables @@ -659,22 +659,22 @@ QPDF::checkLinearizationInternal() // code. if (! errors.empty()) { - result = false; - for (std::list::iterator iter = errors.begin(); - iter != errors.end(); ++iter) - { - *this->m->err_stream << "WARNING: " << (*iter) << std::endl; - } + result = false; + for (std::list::iterator iter = errors.begin(); + iter != errors.end(); ++iter) + { + *this->m->err_stream << "WARNING: " << (*iter) << std::endl; + } } if (! warnings.empty()) { - result = false; - for (std::list::iterator iter = warnings.begin(); - iter != warnings.end(); ++iter) - { - *this->m->err_stream << "WARNING: " << (*iter) << std::endl; - } + result = false; + for (std::list::iterator iter = warnings.begin(); + iter != warnings.end(); ++iter) + { + *this->m->err_stream << "WARNING: " << (*iter) << std::endl; + } } return result; @@ -690,14 +690,14 @@ QPDF::maxEnd(ObjUser const& ou) std::set const& ogs = this->m->obj_user_to_objects[ou]; qpdf_offset_t end = 0; for (std::set::const_iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) + iter != ogs.end(); ++iter) { - QPDFObjGen const& og = *iter; - if (this->m->obj_cache.count(og) == 0) + QPDFObjGen const& og = *iter; + if (this->m->obj_cache.count(og) == 0) { stopOnError("unknown object referenced in object user table"); } - end = std::max(end, this->m->obj_cache[og].end_after_space); + end = std::max(end, this->m->obj_cache[og].end_after_space); } return end; } @@ -710,72 +710,72 @@ QPDF::getLinearizationOffset(QPDFObjGen const& og) switch (entry.getType()) { case 1: - result = entry.getOffset(); - break; + result = entry.getOffset(); + break; case 2: - // For compressed objects, return the offset of the object - // stream that contains them. - result = getLinearizationOffset( + // For compressed objects, return the offset of the object + // stream that contains them. + result = getLinearizationOffset( QPDFObjGen(entry.getObjStreamNumber(), 0)); - break; + break; default: - stopOnError( - "getLinearizationOffset called for xref entry not of type 1 or 2"); - break; + stopOnError( + "getLinearizationOffset called for xref entry not of type 1 or 2"); + break; } return result; } QPDFObjectHandle QPDF::getUncompressedObject(QPDFObjectHandle& obj, - std::map const& object_stream_data) + std::map const& object_stream_data) { if (obj.isNull() || (object_stream_data.count(obj.getObjectID()) == 0)) { - return obj; + return obj; } else { - int repl = (*(object_stream_data.find(obj.getObjectID()))).second; - return objGenToIndirect(QPDFObjGen(repl, 0)); + int repl = (*(object_stream_data.find(obj.getObjectID()))).second; + return objGenToIndirect(QPDFObjGen(repl, 0)); } } int QPDF::lengthNextN(int first_object, int n, - std::list& errors) + std::list& errors) { int length = 0; for (int i = 0; i < n; ++i) { - QPDFObjGen og(first_object + i, 0); - if (this->m->xref_table.count(og) == 0) - { - errors.push_back( - "no xref table entry for " + - QUtil::int_to_string(first_object + i) + " 0"); - } - else - { - if (this->m->obj_cache.count(og) == 0) + QPDFObjGen og(first_object + i, 0); + if (this->m->xref_table.count(og) == 0) + { + errors.push_back( + "no xref table entry for " + + QUtil::int_to_string(first_object + i) + " 0"); + } + else + { + if (this->m->obj_cache.count(og) == 0) { stopOnError("found unknown object while" " calculating length for linearization data"); } - length += toI(this->m->obj_cache[og].end_after_space - + length += toI(this->m->obj_cache[og].end_after_space - getLinearizationOffset(og)); - } + } } return length; } void QPDF::checkHPageOffset(std::list& errors, - std::list& warnings, - std::vector const& pages, - std::map& shared_idx_to_obj) + std::list& warnings, + std::vector const& pages, + std::map& shared_idx_to_obj) { // Implementation note 126 says Acrobat always sets // delta_content_offset and delta_content_length in the page @@ -796,7 +796,7 @@ QPDF::checkHPageOffset(std::list& errors, int npages = toI(pages.size()); qpdf_offset_t table_offset = adjusted_offset( - this->m->page_offset_hints.first_page_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) { @@ -805,124 +805,124 @@ QPDF::checkHPageOffset(std::list& errors, qpdf_offset_t offset = getLinearizationOffset(first_page_og); if (table_offset != offset) { - warnings.push_back("first page object offset mismatch"); + warnings.push_back("first page object offset mismatch"); } for (int pageno = 0; pageno < npages; ++pageno) { - QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen()); - int first_object = page_og.getObj(); - if (this->m->xref_table.count(page_og) == 0) + QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen()); + int first_object = page_og.getObj(); + if (this->m->xref_table.count(page_og) == 0) { stopOnError("unknown object in page offset hint table"); } - offset = getLinearizationOffset(page_og); + offset = getLinearizationOffset(page_og); - HPageOffsetEntry& he = + HPageOffsetEntry& he = this->m->page_offset_hints.entries.at(toS(pageno)); - CHPageOffsetEntry& ce = + 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) - { - // This happens with pdlin when there are thumbnails. - warnings.push_back( - "object count mismatch for page " + - QUtil::int_to_string(pageno) + ": hint table = " + - QUtil::int_to_string(h_nobjects) + "; computed = " + - QUtil::int_to_string(ce.nobjects)); - } - - // 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 = toI(he.delta_page_length + + int h_nobjects = he.delta_nobjects + + this->m->page_offset_hints.min_nobjects; + if (h_nobjects != ce.nobjects) + { + // This happens with pdlin when there are thumbnails. + warnings.push_back( + "object count mismatch for page " + + QUtil::int_to_string(pageno) + ": hint table = " + + QUtil::int_to_string(h_nobjects) + "; computed = " + + QUtil::int_to_string(ce.nobjects)); + } + + // 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 = 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 - // table or a bug in this code. - errors.push_back( - "page length mismatch for page " + - QUtil::int_to_string(pageno) + ": hint table = " + - QUtil::int_to_string(h_length) + "; computed length = " + - QUtil::int_to_string(length) + " (offset = " + - QUtil::int_to_string(offset) + ")"); - } - - offset += h_length; - - // Translate shared object indexes to object numbers. - std::set hint_shared; - std::set computed_shared; - - if ((pageno == 0) && (he.nshared_objects > 0)) - { - // pdlin and Acrobat both do this even though the spec - // states clearly and unambiguously that they should not. - warnings.push_back("page 0 has shared identifier entries"); - } - - 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) + if (length != h_length) + { + // This condition almost certainly indicates a bad hint + // table or a bug in this code. + errors.push_back( + "page length mismatch for page " + + QUtil::int_to_string(pageno) + ": hint table = " + + QUtil::int_to_string(h_length) + "; computed length = " + + QUtil::int_to_string(length) + " (offset = " + + QUtil::int_to_string(offset) + ")"); + } + + offset += h_length; + + // Translate shared object indexes to object numbers. + std::set hint_shared; + std::set computed_shared; + + if ((pageno == 0) && (he.nshared_objects > 0)) + { + // pdlin and Acrobat both do this even though the spec + // states clearly and unambiguously that they should not. + warnings.push_back("page 0 has shared identifier entries"); + } + + 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) { stopOnError( "unable to get object for item in" " shared objects hint table"); } - hint_shared.insert(shared_idx_to_obj[idx]); - } + hint_shared.insert(shared_idx_to_obj[idx]); + } - 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) + 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) { stopOnError( "index out of bounds for shared object hint table"); } - int obj = this->m->c_shared_object_data.entries.at(toS(idx)).object; - computed_shared.insert(obj); - } - - for (std::set::iterator iter = hint_shared.begin(); - iter != hint_shared.end(); ++iter) - { - if (! computed_shared.count(*iter)) - { - // pdlin puts thumbnails here even though it shouldn't - warnings.push_back( - "page " + QUtil::int_to_string(pageno) + - ": shared object " + QUtil::int_to_string(*iter) + - ": in hint table but not computed list"); - } - } - - for (std::set::iterator iter = computed_shared.begin(); - iter != computed_shared.end(); ++iter) - { - if (! hint_shared.count(*iter)) - { - // Acrobat does not put some things including at least - // built-in fonts and procsets here, at least in some - // cases. - warnings.push_back( - "page " + QUtil::int_to_string(pageno) + - ": shared object " + QUtil::int_to_string(*iter) + - ": in computed list but not hint table"); - } - } + int obj = this->m->c_shared_object_data.entries.at(toS(idx)).object; + computed_shared.insert(obj); + } + + for (std::set::iterator iter = hint_shared.begin(); + iter != hint_shared.end(); ++iter) + { + if (! computed_shared.count(*iter)) + { + // pdlin puts thumbnails here even though it shouldn't + warnings.push_back( + "page " + QUtil::int_to_string(pageno) + + ": shared object " + QUtil::int_to_string(*iter) + + ": in hint table but not computed list"); + } + } + + for (std::set::iterator iter = computed_shared.begin(); + iter != computed_shared.end(); ++iter) + { + if (! hint_shared.count(*iter)) + { + // Acrobat does not put some things including at least + // built-in fonts and procsets here, at least in some + // cases. + warnings.push_back( + "page " + QUtil::int_to_string(pageno) + + ": shared object " + QUtil::int_to_string(*iter) + + ": in computed list but not hint table"); + } + } } } void QPDF::checkHSharedObject(std::list& errors, - std::list& warnings, - std::vector const& pages, - std::map& idx_to_obj) + std::list& warnings, + std::vector const& pages, + std::map& idx_to_obj) { // Implementation note 125 says shared object groups always // contain only one object. Implementation note 128 says that @@ -945,73 +945,73 @@ QPDF::checkHSharedObject(std::list& errors, HSharedObject& so = this->m->shared_object_hints; if (so.nshared_total < so.nshared_first_page) { - errors.push_back("shared object hint table: ntotal < nfirst_page"); + errors.push_back("shared object hint table: ntotal < nfirst_page"); } else { - // The first nshared_first_page objects are consecutive - // objects starting with the first page object. The rest are - // consecutive starting from the first_shared_obj object. - int cur_object = pages.at(0).getObjectID(); - for (int i = 0; i < so.nshared_total; ++i) - { - if (i == so.nshared_first_page) - { - QTC::TC("qpdf", "QPDF lin check shared past first page"); - if (this->m->part8.empty()) - { - errors.push_back( - "part 8 is empty but nshared_total > " - "nshared_first_page"); - } - else - { - int obj = this->m->part8.at(0).getObjectID(); - if (obj != so.first_shared_obj) - { - errors.push_back( - "first shared object number mismatch: " - "hint table = " + - QUtil::int_to_string(so.first_shared_obj) + - "; computed = " + - QUtil::int_to_string(obj)); - } - } - - cur_object = so.first_shared_obj; - - QPDFObjGen og(cur_object, 0); - if (this->m->xref_table.count(og) == 0) + // The first nshared_first_page objects are consecutive + // objects starting with the first page object. The rest are + // consecutive starting from the first_shared_obj object. + int cur_object = pages.at(0).getObjectID(); + for (int i = 0; i < so.nshared_total; ++i) + { + if (i == so.nshared_first_page) + { + QTC::TC("qpdf", "QPDF lin check shared past first page"); + if (this->m->part8.empty()) + { + errors.push_back( + "part 8 is empty but nshared_total > " + "nshared_first_page"); + } + else + { + int obj = this->m->part8.at(0).getObjectID(); + if (obj != so.first_shared_obj) + { + errors.push_back( + "first shared object number mismatch: " + "hint table = " + + QUtil::int_to_string(so.first_shared_obj) + + "; computed = " + + QUtil::int_to_string(obj)); + } + } + + cur_object = so.first_shared_obj; + + QPDFObjGen og(cur_object, 0); + if (this->m->xref_table.count(og) == 0) { stopOnError("unknown object in shared object hint table"); } - qpdf_offset_t offset = getLinearizationOffset(og); - qpdf_offset_t h_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( - "first shared object offset mismatch: hint table = " + - QUtil::int_to_string(h_offset) + "; computed = " + - QUtil::int_to_string(offset)); - } - } - - idx_to_obj[i] = cur_object; - 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; - if (length != h_length) - { - errors.push_back( - "shared object " + QUtil::int_to_string(i) + - " length mismatch: hint table = " + - QUtil::int_to_string(h_length) + "; computed = " + - QUtil::int_to_string(length)); - } - cur_object += nobjects; - } + if (offset != h_offset) + { + errors.push_back( + "first shared object offset mismatch: hint table = " + + QUtil::int_to_string(h_offset) + "; computed = " + + QUtil::int_to_string(offset)); + } + } + + idx_to_obj[i] = cur_object; + 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; + if (length != h_length) + { + errors.push_back( + "shared object " + QUtil::int_to_string(i) + + " length mismatch: hint table = " + + QUtil::int_to_string(h_length) + "; computed = " + + QUtil::int_to_string(length)); + } + cur_object += nobjects; + } } } @@ -1028,60 +1028,60 @@ QPDF::checkHOutlines(std::list& warnings) if (this->m->c_outline_data.nobjects == this->m->outline_hints.nobjects) { - if (this->m->c_outline_data.nobjects == 0) - { - return; - } + if (this->m->c_outline_data.nobjects == 0) + { + return; + } - if (this->m->c_outline_data.first_object == - this->m->outline_hints.first_object) - { - // Check length and offset. Acrobat gets these wrong. - QPDFObjectHandle outlines = getRoot().getKey("/Outlines"); + if (this->m->c_outline_data.first_object == + this->m->outline_hints.first_object) + { + // Check length and offset. Acrobat gets these wrong. + QPDFObjectHandle outlines = getRoot().getKey("/Outlines"); if (! outlines.isIndirect()) { // This case is not exercised in test suite since not // permitted by the spec, but if this does occur, the // code below would fail. - warnings.push_back( - "/Outlines key of root dictionary is not indirect"); + warnings.push_back( + "/Outlines key of root dictionary is not indirect"); return; } - QPDFObjGen og(outlines.getObjGen()); - if (this->m->xref_table.count(og) == 0) + QPDFObjGen og(outlines.getObjGen()); + if (this->m->xref_table.count(og) == 0) { stopOnError("unknown object in outlines hint table"); } - qpdf_offset_t offset = getLinearizationOffset(og); - ObjUser ou(ObjUser::ou_root_key, "/Outlines"); - int length = toI(maxEnd(ou) - offset); - qpdf_offset_t table_offset = - adjusted_offset(this->m->outline_hints.first_object_offset); - if (offset != table_offset) - { - warnings.push_back( - "incorrect offset in outlines table: hint table = " + - QUtil::int_to_string(table_offset) + - "; computed = " + QUtil::int_to_string(offset)); - } - int table_length = this->m->outline_hints.group_length; - if (length != table_length) - { - warnings.push_back( - "incorrect length in outlines table: hint table = " + - QUtil::int_to_string(table_length) + - "; computed = " + QUtil::int_to_string(length)); - } - } - else - { - warnings.push_back("incorrect first object number in outline " - "hints table."); - } + qpdf_offset_t offset = getLinearizationOffset(og); + ObjUser ou(ObjUser::ou_root_key, "/Outlines"); + int length = toI(maxEnd(ou) - offset); + qpdf_offset_t table_offset = + adjusted_offset(this->m->outline_hints.first_object_offset); + if (offset != table_offset) + { + warnings.push_back( + "incorrect offset in outlines table: hint table = " + + QUtil::int_to_string(table_offset) + + "; computed = " + QUtil::int_to_string(offset)); + } + int table_length = this->m->outline_hints.group_length; + if (length != table_length) + { + warnings.push_back( + "incorrect length in outlines table: hint table = " + + QUtil::int_to_string(table_length) + + "; computed = " + QUtil::int_to_string(length)); + } + } + else + { + warnings.push_back("incorrect first object number in outline " + "hints table."); + } } else { - warnings.push_back("incorrect object count in outline hint table"); + warnings.push_back("incorrect object count in outline hint table"); } } @@ -1090,13 +1090,13 @@ QPDF::showLinearizationData() { try { - readLinearizationData(); - checkLinearizationInternal(); - dumpLinearizationDataInternal(); + readLinearizationData(); + checkLinearizationInternal(); + dumpLinearizationDataInternal(); } catch (QPDFExc& e) { - *this->m->err_stream << e.what() << std::endl; + *this->m->err_stream << e.what() << std::endl; } } @@ -1108,15 +1108,15 @@ QPDF::dumpLinearizationDataInternal() << std::endl; *this->m->out_stream - << "file_size: " << this->m->linp.file_size << std::endl - << "first_page_object: " << this->m->linp.first_page_object << std::endl - << "first_page_end: " << this->m->linp.first_page_end << std::endl - << "npages: " << this->m->linp.npages << std::endl - << "xref_zero_offset: " << this->m->linp.xref_zero_offset << std::endl - << "first_page: " << this->m->linp.first_page << std::endl - << "H_offset: " << this->m->linp.H_offset << std::endl - << "H_length: " << this->m->linp.H_length << std::endl - << std::endl; + << "file_size: " << this->m->linp.file_size << std::endl + << "first_page_object: " << this->m->linp.first_page_object << std::endl + << "first_page_end: " << this->m->linp.first_page_end << std::endl + << "npages: " << this->m->linp.npages << std::endl + << "xref_zero_offset: " << this->m->linp.xref_zero_offset << std::endl + << "first_page: " << this->m->linp.first_page << std::endl + << "H_offset: " << this->m->linp.H_offset << std::endl + << "H_length: " << this->m->linp.H_length << std::endl + << std::endl; *this->m->out_stream << "Page Offsets Hint Table" << std::endl << std::endl; @@ -1128,10 +1128,10 @@ QPDF::dumpLinearizationDataInternal() if (this->m->outline_hints.nobjects > 0) { - *this->m->out_stream << std::endl + *this->m->out_stream << std::endl << "Outlines Hint Table" << std::endl << std::endl; - dumpHGeneric(this->m->outline_hints); + dumpHGeneric(this->m->outline_hints); } } @@ -1143,7 +1143,7 @@ QPDF::adjusted_offset(qpdf_offset_t offset) // itself. if (offset >= this->m->linp.H_offset) { - return offset + this->m->linp.H_length; + return offset + this->m->linp.H_length; } return offset; } @@ -1154,55 +1154,55 @@ QPDF::dumpHPageOffset() { HPageOffset& t = this->m->page_offset_hints; *this->m->out_stream - << "min_nobjects: " << t.min_nobjects - << std::endl - << "first_page_offset: " << adjusted_offset(t.first_page_offset) - << std::endl - << "nbits_delta_nobjects: " << t.nbits_delta_nobjects - << std::endl - << "min_page_length: " << t.min_page_length - << std::endl - << "nbits_delta_page_length: " << t.nbits_delta_page_length - << std::endl - << "min_content_offset: " << t.min_content_offset - << std::endl - << "nbits_delta_content_offset: " << t.nbits_delta_content_offset - << std::endl - << "min_content_length: " << t.min_content_length - << std::endl - << "nbits_delta_content_length: " << t.nbits_delta_content_length - << std::endl - << "nbits_nshared_objects: " << t.nbits_nshared_objects - << std::endl - << "nbits_shared_identifier: " << t.nbits_shared_identifier - << std::endl - << "nbits_shared_numerator: " << t.nbits_shared_numerator - << std::endl - << "shared_denominator: " << t.shared_denominator - << std::endl; + << "min_nobjects: " << t.min_nobjects + << std::endl + << "first_page_offset: " << adjusted_offset(t.first_page_offset) + << std::endl + << "nbits_delta_nobjects: " << t.nbits_delta_nobjects + << std::endl + << "min_page_length: " << t.min_page_length + << std::endl + << "nbits_delta_page_length: " << t.nbits_delta_page_length + << std::endl + << "min_content_offset: " << t.min_content_offset + << std::endl + << "nbits_delta_content_offset: " << t.nbits_delta_content_offset + << std::endl + << "min_content_length: " << t.min_content_length + << std::endl + << "nbits_delta_content_length: " << t.nbits_delta_content_length + << std::endl + << "nbits_nshared_objects: " << t.nbits_nshared_objects + << std::endl + << "nbits_shared_identifier: " << t.nbits_shared_identifier + << std::endl + << "nbits_shared_numerator: " << t.nbits_shared_numerator + << std::endl + << "shared_denominator: " << t.shared_denominator + << std::endl; for (size_t i1 = 0; i1 < toS(this->m->linp.npages); ++i1) { - HPageOffsetEntry& pe = t.entries.at(i1); - *this->m->out_stream - << "Page " << i1 << ":" << std::endl - << " nobjects: " << pe.delta_nobjects + t.min_nobjects - << std::endl - << " length: " << pe.delta_page_length + t.min_page_length - << std::endl - // content offset is relative to page, not file - << " content_offset: " - << pe.delta_content_offset + t.min_content_offset << std::endl - << " content_length: " - << pe.delta_content_length + t.min_content_length << std::endl - << " nshared_objects: " << pe.nshared_objects << std::endl; - for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2) - { - *this->m->out_stream << " identifier " << i2 << ": " + HPageOffsetEntry& pe = t.entries.at(i1); + *this->m->out_stream + << "Page " << i1 << ":" << std::endl + << " nobjects: " << pe.delta_nobjects + t.min_nobjects + << std::endl + << " length: " << pe.delta_page_length + t.min_page_length + << std::endl + // content offset is relative to page, not file + << " content_offset: " + << pe.delta_content_offset + t.min_content_offset << std::endl + << " content_length: " + << pe.delta_content_length + t.min_content_length << std::endl + << " nshared_objects: " << pe.nshared_objects << std::endl; + for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2) + { + *this->m->out_stream << " identifier " << i2 << ": " << pe.shared_identifiers.at(i2) << std::endl; - *this->m->out_stream << " numerator " << i2 << ": " + *this->m->out_stream << " numerator " << i2 << ": " << pe.shared_numerators.at(i2) << std::endl; - } + } } } @@ -1211,39 +1211,39 @@ QPDF::dumpHSharedObject() { HSharedObject& t = this->m->shared_object_hints; *this->m->out_stream - << "first_shared_obj: " << t.first_shared_obj - << std::endl - << "first_shared_offset: " << adjusted_offset(t.first_shared_offset) - << std::endl - << "nshared_first_page: " << t.nshared_first_page - << std::endl - << "nshared_total: " << t.nshared_total - << std::endl - << "nbits_nobjects: " << t.nbits_nobjects - << std::endl - << "min_group_length: " << t.min_group_length - << std::endl - << "nbits_delta_group_length: " << t.nbits_delta_group_length - << std::endl; + << "first_shared_obj: " << t.first_shared_obj + << std::endl + << "first_shared_offset: " << adjusted_offset(t.first_shared_offset) + << std::endl + << "nshared_first_page: " << t.nshared_first_page + << std::endl + << "nshared_total: " << t.nshared_total + << std::endl + << "nbits_nobjects: " << t.nbits_nobjects + << std::endl + << "min_group_length: " << t.min_group_length + << std::endl + << "nbits_delta_group_length: " << t.nbits_delta_group_length + << std::endl; for (size_t i = 0; i < toS(t.nshared_total); ++i) { - HSharedObjectEntry& se = t.entries.at(i); - *this->m->out_stream + HSharedObjectEntry& se = t.entries.at(i); + *this->m->out_stream << "Shared Object " << i << ":" << std::endl << " group length: " << se.delta_group_length + t.min_group_length << std::endl; - // PDF spec says signature present nobjects_minus_one are - // always 0, so print them only if they have a non-zero value. - if (se.signature_present) - { - *this->m->out_stream << " signature present" << std::endl; - } - if (se.nobjects_minus_one != 0) - { - *this->m->out_stream << " nobjects: " + // PDF spec says signature present nobjects_minus_one are + // always 0, so print them only if they have a non-zero value. + if (se.signature_present) + { + *this->m->out_stream << " signature present" << std::endl; + } + if (se.nobjects_minus_one != 0) + { + *this->m->out_stream << " nobjects: " << se.nobjects_minus_one + 1 << std::endl; - } + } } } @@ -1251,14 +1251,14 @@ void QPDF::dumpHGeneric(HGeneric& t) { *this->m->out_stream - << "first_object: " << t.first_object - << std::endl - << "first_object_offset: " << adjusted_offset(t.first_object_offset) - << std::endl - << "nobjects: " << t.nobjects - << std::endl - << "group_length: " << t.group_length - << std::endl; + << "first_object: " << t.first_object + << std::endl + << "first_object_offset: " << adjusted_offset(t.first_object_offset) + << std::endl + << "nobjects: " << t.nobjects + << std::endl + << "group_length: " << t.group_length + << std::endl; } QPDFObjectHandle @@ -1279,11 +1279,11 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) if (this->m->object_to_obj_users.empty()) { - // Note that we can't call optimize here because we don't know - // whether it should be called with or without allow changes. - throw std::logic_error( - "INTERNAL ERROR: QPDF::calculateLinearizationData " - "called before optimize()"); + // Note that we can't call optimize here because we don't know + // whether it should be called with or without allow changes. + throw std::logic_error( + "INTERNAL ERROR: QPDF::calculateLinearizationData " + "called before optimize()"); } // Separate objects into the categories sufficient for us to @@ -1347,22 +1347,22 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) bool outlines_in_first_page = false; QPDFObjectHandle pagemode = root.getKey("/PageMode"); QTC::TC("qpdf", "QPDF categorize pagemode present", - pagemode.isName() ? 1 : 0); + pagemode.isName() ? 1 : 0); if (pagemode.isName()) { - if (pagemode.getName() == "/UseOutlines") - { - if (root.hasKey("/Outlines")) - { - outlines_in_first_page = true; - } - else - { - QTC::TC("qpdf", "QPDF UseOutlines but no Outlines"); - } - } - QTC::TC("qpdf", "QPDF categorize pagemode outlines", - outlines_in_first_page ? 1 : 0); + if (pagemode.getName() == "/UseOutlines") + { + if (root.hasKey("/Outlines")) + { + outlines_in_first_page = true; + } + else + { + QTC::TC("qpdf", "QPDF UseOutlines but no Outlines"); + } + } + QTC::TC("qpdf", "QPDF categorize pagemode outlines", + outlines_in_first_page ? 1 : 0); } std::set open_document_keys; @@ -1384,121 +1384,121 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) std::set lc_root; for (std::map >::iterator oiter = - this->m->object_to_obj_users.begin(); - oiter != this->m->object_to_obj_users.end(); ++oiter) - { - QPDFObjGen const& og = (*oiter).first; - - std::set& ous = (*oiter).second; - - bool in_open_document = false; - bool in_first_page = false; - int other_pages = 0; - int thumbs = 0; - int others = 0; - bool in_outlines = false; - bool is_root = false; - - for (std::set::iterator uiter = ous.begin(); - uiter != ous.end(); ++uiter) - { - ObjUser const& ou = *uiter; - switch (ou.ou_type) - { - case ObjUser::ou_trailer_key: - if (ou.key == "/Encrypt") - { - in_open_document = true; - } - else - { - ++others; - } - break; - - case ObjUser::ou_thumb: - ++thumbs; - break; - - case ObjUser::ou_root_key: - if (open_document_keys.count(ou.key) > 0) - { - in_open_document = true; - } - else if (ou.key == "/Outlines") - { - in_outlines = true; - } - else - { - ++others; - } - break; - - case ObjUser::ou_page: - if (ou.pageno == 0) - { - in_first_page = true; - } - else - { - ++other_pages; - } - break; - - case ObjUser::ou_root: - is_root = true; - break; - - case ObjUser::ou_bad: - stopOnError( - "INTERNAL ERROR: QPDF::calculateLinearizationData: " - "invalid user type"); - break; - } - } - - if (is_root) - { - lc_root.insert(og); - } - else if (in_outlines) - { - lc_outlines.insert(og); - } - else if (in_open_document) - { - lc_open_document.insert(og); - } - else if ((in_first_page) && - (others == 0) && (other_pages == 0) && (thumbs == 0)) - { - lc_first_page_private.insert(og); - } - else if (in_first_page) - { - lc_first_page_shared.insert(og); - } - else if ((other_pages == 1) && (others == 0) && (thumbs == 0)) - { - lc_other_page_private.insert(og); - } - else if (other_pages > 1) - { - lc_other_page_shared.insert(og); - } - else if ((thumbs == 1) && (others == 0)) - { - lc_thumbnail_private.insert(og); - } - else if (thumbs > 1) - { - lc_thumbnail_shared.insert(og); - } - else - { - lc_other.insert(og); - } + this->m->object_to_obj_users.begin(); + oiter != this->m->object_to_obj_users.end(); ++oiter) + { + QPDFObjGen const& og = (*oiter).first; + + std::set& ous = (*oiter).second; + + bool in_open_document = false; + bool in_first_page = false; + int other_pages = 0; + int thumbs = 0; + int others = 0; + bool in_outlines = false; + bool is_root = false; + + for (std::set::iterator uiter = ous.begin(); + uiter != ous.end(); ++uiter) + { + ObjUser const& ou = *uiter; + switch (ou.ou_type) + { + case ObjUser::ou_trailer_key: + if (ou.key == "/Encrypt") + { + in_open_document = true; + } + else + { + ++others; + } + break; + + case ObjUser::ou_thumb: + ++thumbs; + break; + + case ObjUser::ou_root_key: + if (open_document_keys.count(ou.key) > 0) + { + in_open_document = true; + } + else if (ou.key == "/Outlines") + { + in_outlines = true; + } + else + { + ++others; + } + break; + + case ObjUser::ou_page: + if (ou.pageno == 0) + { + in_first_page = true; + } + else + { + ++other_pages; + } + break; + + case ObjUser::ou_root: + is_root = true; + break; + + case ObjUser::ou_bad: + stopOnError( + "INTERNAL ERROR: QPDF::calculateLinearizationData: " + "invalid user type"); + break; + } + } + + if (is_root) + { + lc_root.insert(og); + } + else if (in_outlines) + { + lc_outlines.insert(og); + } + else if (in_open_document) + { + lc_open_document.insert(og); + } + else if ((in_first_page) && + (others == 0) && (other_pages == 0) && (thumbs == 0)) + { + lc_first_page_private.insert(og); + } + else if (in_first_page) + { + lc_first_page_shared.insert(og); + } + else if ((other_pages == 1) && (others == 0) && (thumbs == 0)) + { + lc_other_page_private.insert(og); + } + else if (other_pages > 1) + { + lc_other_page_shared.insert(og); + } + else if ((thumbs == 1) && (others == 0)) + { + lc_thumbnail_private.insert(og); + } + else if (thumbs > 1) + { + lc_thumbnail_shared.insert(og); + } + else + { + lc_other.insert(og); + } } // Generate ordering for objects in the output file. Sometimes we @@ -1518,14 +1518,14 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Premature optimization is the root of all evil. std::vector pages; { // local scope - // Map all page objects to the containing object stream. This - // should be a no-op in a properly linearized file. - std::vector t = getAllPages(); - for (std::vector::iterator iter = t.begin(); - iter != t.end(); ++iter) - { - pages.push_back(getUncompressedObject(*iter, object_stream_data)); - } + // Map all page objects to the containing object stream. This + // should be a no-op in a properly linearized file. + std::vector t = getAllPages(); + for (std::vector::iterator iter = t.begin(); + iter != t.end(); ++iter) + { + pages.push_back(getUncompressedObject(*iter, object_stream_data)); + } } int npages = toI(pages.size()); @@ -1553,9 +1553,9 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) } this->m->part4.push_back(objGenToIndirect(*(lc_root.begin()))); for (std::set::iterator iter = lc_open_document.begin(); - iter != lc_open_document.end(); ++iter) + iter != lc_open_document.end(); ++iter) { - this->m->part4.push_back(objGenToIndirect(*iter)); + this->m->part4.push_back(objGenToIndirect(*iter)); } // Part 6: first page objects. Note: implementation note 124 @@ -1572,9 +1572,9 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) QPDFObjGen first_page_og(pages.at(0).getObjGen()); if (! lc_first_page_private.count(first_page_og)) { - stopOnError( - "INTERNAL ERROR: QPDF::calculateLinearizationData: first page " - "object not in lc_first_page_private"); + stopOnError( + "INTERNAL ERROR: QPDF::calculateLinearizationData: first page " + "object not in lc_first_page_private"); } lc_first_page_private.erase(first_page_og); this->m->c_linp.first_page_object = pages.at(0).getObjectID(); @@ -1586,21 +1586,21 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // hint tables. for (std::set::iterator iter = lc_first_page_private.begin(); - iter != lc_first_page_private.end(); ++iter) + iter != lc_first_page_private.end(); ++iter) { - this->m->part6.push_back(objGenToIndirect(*iter)); + this->m->part6.push_back(objGenToIndirect(*iter)); } for (std::set::iterator iter = lc_first_page_shared.begin(); - iter != lc_first_page_shared.end(); ++iter) + iter != lc_first_page_shared.end(); ++iter) { - this->m->part6.push_back(objGenToIndirect(*iter)); + this->m->part6.push_back(objGenToIndirect(*iter)); } // Place the outline dictionary if it goes in the first page section. if (outlines_in_first_page) { - pushOutlinesToPart(this->m->part6, lc_outlines, object_stream_data); + pushOutlinesToPart(this->m->part6, lc_outlines, object_stream_data); } // Fill in page offset hint table information for the first page. @@ -1617,59 +1617,59 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // For each page in order: for (size_t i = 1; i < toS(npages); ++i) { - // Place this page's page object + // Place this page's page object - QPDFObjGen page_og(pages.at(i).getObjGen()); - if (! lc_other_page_private.count(page_og)) - { - stopOnError( - "INTERNAL ERROR: " - "QPDF::calculateLinearizationData: page object for page " + - 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)); + QPDFObjGen page_og(pages.at(i).getObjGen()); + if (! lc_other_page_private.count(page_og)) + { + stopOnError( + "INTERNAL ERROR: " + "QPDF::calculateLinearizationData: page object for page " + + 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)); - // Place all non-shared objects referenced by this page, - // updating the page object count for the hint table. + // Place all non-shared objects referenced by this page, + // updating the page object count for the hint table. - this->m->c_page_offset_data.entries.at(i).nobjects = 1; + this->m->c_page_offset_data.entries.at(i).nobjects = 1; - ObjUser ou(ObjUser::ou_page, toI(i)); - if (this->m->obj_user_to_objects.count(ou) == 0) + ObjUser ou(ObjUser::ou_page, toI(i)); + if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" " calculating linearization data"); } - std::set ogs = this->m->obj_user_to_objects[ou]; - for (std::set::iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { - QPDFObjGen const& og = (*iter); - if (lc_other_page_private.count(og)) - { - lc_other_page_private.erase(og); - this->m->part7.push_back(objGenToIndirect(og)); - ++this->m->c_page_offset_data.entries.at(i).nobjects; - } - } + std::set ogs = this->m->obj_user_to_objects[ou]; + for (std::set::iterator iter = ogs.begin(); + iter != ogs.end(); ++iter) + { + QPDFObjGen const& og = (*iter); + if (lc_other_page_private.count(og)) + { + lc_other_page_private.erase(og); + this->m->part7.push_back(objGenToIndirect(og)); + ++this->m->c_page_offset_data.entries.at(i).nobjects; + } + } } // That should have covered all part7 objects. if (! lc_other_page_private.empty()) { - stopOnError( - "INTERNAL ERROR:" - " QPDF::calculateLinearizationData: lc_other_page_private is " - "not empty after generation of part7"); + stopOnError( + "INTERNAL ERROR:" + " QPDF::calculateLinearizationData: lc_other_page_private is " + "not empty after generation of part7"); } // Part 8: other pages' shared objects // Order is unimportant. for (std::set::iterator iter = lc_other_page_shared.begin(); - iter != lc_other_page_shared.end(); ++iter) + iter != lc_other_page_shared.end(); ++iter) { - this->m->part8.push_back(objGenToIndirect(*iter)); + this->m->part8.push_back(objGenToIndirect(*iter)); } // Part 9: other objects @@ -1683,21 +1683,21 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Place the pages tree. std::set pages_ogs = - this->m->obj_user_to_objects[ObjUser(ObjUser::ou_root_key, "/Pages")]; + this->m->obj_user_to_objects[ObjUser(ObjUser::ou_root_key, "/Pages")]; if (pages_ogs.empty()) { stopOnError("found empty pages tree while" " calculating linearization data"); } for (std::set::iterator iter = pages_ogs.begin(); - iter != pages_ogs.end(); ++iter) + iter != pages_ogs.end(); ++iter) { - QPDFObjGen const& og = *iter; - if (lc_other.count(og)) - { - lc_other.erase(og); - this->m->part9.push_back(objGenToIndirect(og)); - } + QPDFObjGen const& og = *iter; + if (lc_other.count(og)) + { + lc_other.erase(og); + this->m->part9.push_back(objGenToIndirect(og)); + } } // Place private thumbnail images in page order. Slightly more @@ -1705,67 +1705,67 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // thumbnail hint tables. for (size_t i = 0; i < toS(npages); ++i) { - QPDFObjectHandle thumb = pages.at(i).getKey("/Thumb"); - thumb = getUncompressedObject(thumb, object_stream_data); - if (! thumb.isNull()) - { - // Output the thumbnail itself - QPDFObjGen thumb_og(thumb.getObjGen()); - if (lc_thumbnail_private.count(thumb_og)) - { - lc_thumbnail_private.erase(thumb_og); - this->m->part9.push_back(thumb); - } - else - { - // No internal error this time...there's nothing to - // stop this object from having been referred to - // somewhere else outside of a page's /Thumb, and if - // it had been, there's nothing to prevent it from - // having been in some set other than - // lc_thumbnail_private. - } - std::set& ogs = - this->m->obj_user_to_objects[ + QPDFObjectHandle thumb = pages.at(i).getKey("/Thumb"); + thumb = getUncompressedObject(thumb, object_stream_data); + if (! thumb.isNull()) + { + // Output the thumbnail itself + QPDFObjGen thumb_og(thumb.getObjGen()); + if (lc_thumbnail_private.count(thumb_og)) + { + lc_thumbnail_private.erase(thumb_og); + this->m->part9.push_back(thumb); + } + else + { + // No internal error this time...there's nothing to + // stop this object from having been referred to + // somewhere else outside of a page's /Thumb, and if + // it had been, there's nothing to prevent it from + // having been in some set other than + // lc_thumbnail_private. + } + std::set& ogs = + this->m->obj_user_to_objects[ ObjUser(ObjUser::ou_thumb, toI(i))]; - for (std::set::iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { - QPDFObjGen const& og = *iter; - if (lc_thumbnail_private.count(og)) - { - lc_thumbnail_private.erase(og); - this->m->part9.push_back(objGenToIndirect(og)); - } - } - } + for (std::set::iterator iter = ogs.begin(); + iter != ogs.end(); ++iter) + { + QPDFObjGen const& og = *iter; + if (lc_thumbnail_private.count(og)) + { + lc_thumbnail_private.erase(og); + this->m->part9.push_back(objGenToIndirect(og)); + } + } + } } if (! lc_thumbnail_private.empty()) { - stopOnError( - "INTERNAL ERROR: " - "QPDF::calculateLinearizationData: lc_thumbnail_private " - "not empty after placing thumbnails"); + stopOnError( + "INTERNAL ERROR: " + "QPDF::calculateLinearizationData: lc_thumbnail_private " + "not empty after placing thumbnails"); } // Place shared thumbnail objects for (std::set::iterator iter = lc_thumbnail_shared.begin(); - iter != lc_thumbnail_shared.end(); ++iter) + iter != lc_thumbnail_shared.end(); ++iter) { - this->m->part9.push_back(objGenToIndirect(*iter)); + this->m->part9.push_back(objGenToIndirect(*iter)); } // Place outlines unless in first page if (! outlines_in_first_page) { - pushOutlinesToPart(this->m->part9, lc_outlines, object_stream_data); + pushOutlinesToPart(this->m->part9, lc_outlines, object_stream_data); } // Place all remaining objects for (std::set::iterator iter = lc_other.begin(); - iter != lc_other.end(); ++iter) + iter != lc_other.end(); ++iter) { - this->m->part9.push_back(objGenToIndirect(*iter)); + this->m->part9.push_back(objGenToIndirect(*iter)); } // Make sure we got everything exactly once. @@ -1776,12 +1776,12 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) size_t num_wanted = this->m->object_to_obj_users.size(); if (num_placed != num_wanted) { - stopOnError( - "INTERNAL ERROR: QPDF::calculateLinearizationData: wrong " - "number of objects placed (num_placed = " + - QUtil::uint_to_string(num_placed) + - "; number of objects: " + - QUtil::uint_to_string(num_wanted)); + stopOnError( + "INTERNAL ERROR: QPDF::calculateLinearizationData: wrong " + "number of objects placed (num_placed = " + + QUtil::uint_to_string(num_placed) + + "; number of objects: " + + QUtil::uint_to_string(num_wanted)); } // Calculate shared object hint table information including @@ -1800,33 +1800,33 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) 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->c_shared_object_data.nshared_first_page + toI(this->m->part8.size()); std::vector& shared = - this->m->c_shared_object_data.entries; + this->m->c_shared_object_data.entries; for (std::vector::iterator iter = this->m->part6.begin(); - iter != this->m->part6.end(); ++iter) + iter != this->m->part6.end(); ++iter) { - QPDFObjectHandle& oh = *iter; - int obj = oh.getObjectID(); - obj_to_index[obj] = toI(shared.size()); - shared.push_back(CHSharedObjectEntry(obj)); + QPDFObjectHandle& oh = *iter; + int obj = oh.getObjectID(); + 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); if (! this->m->part8.empty()) { - this->m->c_shared_object_data.first_shared_obj = - this->m->part8.at(0).getObjectID(); - for (std::vector::iterator iter = - this->m->part8.begin(); - iter != this->m->part8.end(); ++iter) - { - QPDFObjectHandle& oh = *iter; - int obj = oh.getObjectID(); - obj_to_index[obj] = toI(shared.size()); - shared.push_back(CHSharedObjectEntry(obj)); - } + this->m->c_shared_object_data.first_shared_obj = + this->m->part8.at(0).getObjectID(); + for (std::vector::iterator iter = + this->m->part8.begin(); + iter != this->m->part8.end(); ++iter) + { + QPDFObjectHandle& oh = *iter; + int obj = oh.getObjectID(); + obj_to_index[obj] = toI(shared.size()); + shared.push_back(CHSharedObjectEntry(obj)); + } } if (static_cast(this->m->c_shared_object_data.nshared_total) != this->m->c_shared_object_data.entries.size()) @@ -1840,26 +1840,26 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) 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, toI(i)); - if (this->m->obj_user_to_objects.count(ou) == 0) + CHPageOffsetEntry& pe = this->m->c_page_offset_data.entries.at(i); + ObjUser ou(ObjUser::ou_page, toI(i)); + if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" " calculating linearization data"); } - std::set const& ogs = this->m->obj_user_to_objects[ou]; - for (std::set::const_iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { - QPDFObjGen const& og = *iter; - if ((this->m->object_to_obj_users[og].size() > 1) && - (obj_to_index.count(og.getObj()) > 0)) - { - int idx = obj_to_index[og.getObj()]; - ++pe.nshared_objects; - pe.shared_identifiers.push_back(idx); - } - } + std::set const& ogs = this->m->obj_user_to_objects[ou]; + for (std::set::const_iterator iter = ogs.begin(); + iter != ogs.end(); ++iter) + { + QPDFObjGen const& og = *iter; + if ((this->m->object_to_obj_users[og].size() > 1) && + (obj_to_index.count(og.getObj()) > 0)) + { + int idx = obj_to_index[og.getObj()]; + ++pe.nshared_objects; + pe.shared_identifiers.push_back(idx); + } + } } } @@ -1873,23 +1873,23 @@ QPDF::pushOutlinesToPart( QPDFObjectHandle outlines = root.getKey("/Outlines"); if (outlines.isNull()) { - return; + return; } outlines = getUncompressedObject(outlines, object_stream_data); QPDFObjGen outlines_og(outlines.getObjGen()); QTC::TC("qpdf", "QPDF lin outlines in part", - ((&part == (&this->m->part6)) ? 0 - : (&part == (&this->m->part9)) ? 1 - : 9999)); // can't happen + ((&part == (&this->m->part6)) ? 0 + : (&part == (&this->m->part9)) ? 1 + : 9999)); // can't happen this->m->c_outline_data.first_object = outlines_og.getObj(); this->m->c_outline_data.nobjects = 1; lc_outlines.erase(outlines_og); part.push_back(outlines); for (std::set::iterator iter = lc_outlines.begin(); - iter != lc_outlines.end(); ++iter) + iter != lc_outlines.end(); ++iter) { - part.push_back(objGenToIndirect(*iter)); - ++this->m->c_outline_data.nobjects; + part.push_back(objGenToIndirect(*iter)); + ++this->m->c_outline_data.nobjects; } } @@ -1934,12 +1934,12 @@ QPDF::outputLengthNextN( int length = 0; for (int i = 0; i < n; ++i) { - if (lengths.count(first + i) == 0) + if (lengths.count(first + i) == 0) { stopOnError("found item with unknown length" " while writing linearization data"); } - length += toI((*(lengths.find(first + toI(i)))).second); + length += toI((*(lengths.find(first + toI(i)))).second); } return length; } @@ -1966,7 +1966,7 @@ QPDF::calculateHPageOffset( int min_nobjects = cphe.at(0).nobjects; int max_nobjects = min_nobjects; int min_length = outputLengthNextN( - pages.at(0).getObjectID(), min_nobjects, lengths, obj_renumber); + pages.at(0).getObjectID(), min_nobjects, lengths, obj_renumber); int max_length = min_length; int max_shared = cphe.at(0).nshared_objects; @@ -1977,26 +1977,26 @@ QPDF::calculateHPageOffset( for (unsigned int i = 0; i < npages; ++i) { - // Calculate values for each page, assigning full values to - // the delta items. They will be adjusted later. + // Calculate values for each page, assigning full values to + // the delta items. They will be adjusted later. - // Repeat calculations for page 0 so we can assign to phe[i] - // without duplicating those assignments. + // Repeat calculations for page 0 so we can assign to phe[i] + // without duplicating those assignments. - int nobjects = cphe.at(i).nobjects; - int length = outputLengthNextN( - pages.at(i).getObjectID(), nobjects, lengths, obj_renumber); - int nshared = cphe.at(i).nshared_objects; + int nobjects = cphe.at(i).nobjects; + int length = outputLengthNextN( + pages.at(i).getObjectID(), nobjects, lengths, obj_renumber); + int nshared = cphe.at(i).nshared_objects; - min_nobjects = std::min(min_nobjects, nobjects); - max_nobjects = std::max(max_nobjects, nobjects); - min_length = std::min(min_length, length); - max_length = std::max(max_length, length); - max_shared = std::max(max_shared, nshared); + min_nobjects = std::min(min_nobjects, nobjects); + max_nobjects = std::max(max_nobjects, nobjects); + min_length = std::min(min_length, length); + max_length = std::max(max_length, length); + max_shared = std::max(max_shared, nshared); - phe.at(i).delta_nobjects = nobjects; - phe.at(i).delta_page_length = length; - phe.at(i).nshared_objects = nshared; + phe.at(i).delta_nobjects = nobjects; + phe.at(i).delta_page_length = length; + phe.at(i).nshared_objects = nshared; } ph.min_nobjects = min_nobjects; @@ -2008,8 +2008,8 @@ QPDF::calculateHPageOffset( ph.nbits_delta_page_length = nbits(max_length - min_length); ph.nbits_nshared_objects = nbits(max_shared); ph.nbits_shared_identifier = - nbits(this->m->c_shared_object_data.nshared_total); - ph.shared_denominator = 4; // doesn't matter + nbits(this->m->c_shared_object_data.nshared_total); + ph.shared_denominator = 4; // doesn't matter // It isn't clear how to compute content offset and content // length. Since we are not interleaving page objects with the @@ -2021,23 +2021,23 @@ QPDF::calculateHPageOffset( for (size_t i = 0; i < npages; ++i) { - // Adjust delta entries - if ((phe.at(i).delta_nobjects < min_nobjects) || + // Adjust delta entries + if ((phe.at(i).delta_nobjects < min_nobjects) || (phe.at(i).delta_page_length < min_length)) { stopOnError("found too small delta nobjects or delta page length" " while writing linearization data"); } - phe.at(i).delta_nobjects -= min_nobjects; - phe.at(i).delta_page_length -= min_length; - phe.at(i).delta_content_length = phe.at(i).delta_page_length; + phe.at(i).delta_nobjects -= min_nobjects; + phe.at(i).delta_page_length -= min_length; + phe.at(i).delta_content_length = phe.at(i).delta_page_length; - 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)); - phe.at(i).shared_numerators.push_back(0); - } + 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)); + phe.at(i).shared_numerators.push_back(0); + } } } @@ -2054,18 +2054,18 @@ QPDF::calculateHSharedObject( soe.clear(); int min_length = outputLengthNextN( - csoe.at(0).object, 1, lengths, obj_renumber); + csoe.at(0).object, 1, lengths, obj_renumber); int max_length = min_length; for (size_t i = 0; i < toS(cso.nshared_total); ++i) { - // Assign absolute numbers to deltas; adjust later - int length = outputLengthNextN( - csoe.at(i).object, 1, lengths, obj_renumber); - min_length = std::min(min_length, length); - max_length = std::max(max_length, length); + // Assign absolute numbers to deltas; adjust later + int length = outputLengthNextN( + csoe.at(i).object, 1, lengths, obj_renumber); + min_length = std::min(min_length, length); + max_length = std::max(max_length, length); soe.push_back(HSharedObjectEntry()); - soe.at(i).delta_group_length = length; + soe.at(i).delta_group_length = length; } if (soe.size() != QIntC::to_size(cso.nshared_total)) { @@ -2076,23 +2076,23 @@ QPDF::calculateHSharedObject( so.nshared_first_page = cso.nshared_first_page; if (so.nshared_total > so.nshared_first_page) { - so.first_shared_obj = - (*(obj_renumber.find(cso.first_shared_obj))).second; - so.first_shared_offset = - (*(xref.find(so.first_shared_obj))).second.getOffset(); + so.first_shared_obj = + (*(obj_renumber.find(cso.first_shared_obj))).second; + so.first_shared_offset = + (*(xref.find(so.first_shared_obj))).second.getOffset(); } so.min_group_length = min_length; so.nbits_delta_group_length = nbits(max_length - min_length); for (size_t i = 0; i < toS(cso.nshared_total); ++i) { - // Adjust deltas - if (soe.at(i).delta_group_length < min_length) + // Adjust deltas + if (soe.at(i).delta_group_length < min_length) { stopOnError("found too small group length while" " writing linearization data"); } - soe.at(i).delta_group_length -= min_length; + soe.at(i).delta_group_length -= min_length; } } @@ -2106,31 +2106,31 @@ QPDF::calculateHOutline( if (cho.nobjects == 0) { - return; + return; } HGeneric& ho = this->m->outline_hints; ho.first_object = - (*(obj_renumber.find(cho.first_object))).second; + (*(obj_renumber.find(cho.first_object))).second; ho.first_object_offset = - (*(xref.find(ho.first_object))).second.getOffset(); + (*(xref.find(ho.first_object))).second.getOffset(); ho.nobjects = cho.nobjects; ho.group_length = outputLengthNextN( - cho.first_object, ho.nobjects, lengths, obj_renumber); + cho.first_object, ho.nobjects, lengths, obj_renumber); } template static void write_vector_int(BitWriter& w, int nitems, std::vector& vec, - int bits, int_type T::*field) + int bits, int_type T::*field) { // nitems times, write bits bits from the given field of the ith // vector to the given bit writer. for (size_t i = 0; i < QIntC::to_size(nitems); ++i) { - w.writeBits(QIntC::to_ulonglong(vec.at(i).*field), + 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 @@ -2141,18 +2141,18 @@ write_vector_int(BitWriter& w, int nitems, std::vector& vec, template static void write_vector_vector(BitWriter& w, - int nitems1, std::vector& vec1, int T::*nitems2, - int bits, std::vector T::*vec2) + int nitems1, std::vector& vec1, int T::*nitems2, + int bits, std::vector T::*vec2) { // nitems1 times, write nitems2 (from the ith element of vec1) items // from the vec2 vector field of the ith item of vec1. for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) { - for (size_t i2 = 0; i2 < QIntC::to_size(vec1.at(i1).*nitems2); ++i2) - { - w.writeBits(QIntC::to_ulonglong((vec1.at(i1).*vec2).at(i2)), + for (size_t i2 = 0; i2 < QIntC::to_size(vec1.at(i1).*nitems2); ++i2) + { + w.writeBits(QIntC::to_ulonglong((vec1.at(i1).*vec2).at(i2)), QIntC::to_size(bits)); - } + } } w.flush(); } @@ -2181,28 +2181,28 @@ QPDF::writeHPageOffset(BitWriter& w) std::vector& entries = t.entries; write_vector_int(w, nitems, entries, - t.nbits_delta_nobjects, - &HPageOffsetEntry::delta_nobjects); + t.nbits_delta_nobjects, + &HPageOffsetEntry::delta_nobjects); write_vector_int(w, nitems, entries, - t.nbits_delta_page_length, - &HPageOffsetEntry::delta_page_length); + t.nbits_delta_page_length, + &HPageOffsetEntry::delta_page_length); write_vector_int(w, nitems, entries, - t.nbits_nshared_objects, - &HPageOffsetEntry::nshared_objects); + t.nbits_nshared_objects, + &HPageOffsetEntry::nshared_objects); write_vector_vector(w, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_identifier, - &HPageOffsetEntry::shared_identifiers); + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_identifier, + &HPageOffsetEntry::shared_identifiers); write_vector_vector(w, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_numerator, - &HPageOffsetEntry::shared_numerators); + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_numerator, + &HPageOffsetEntry::shared_numerators); write_vector_int(w, nitems, entries, - t.nbits_delta_content_offset, - &HPageOffsetEntry::delta_content_offset); + t.nbits_delta_content_offset, + &HPageOffsetEntry::delta_content_offset); write_vector_int(w, nitems, entries, - t.nbits_delta_content_length, - &HPageOffsetEntry::delta_content_length); + t.nbits_delta_content_length, + &HPageOffsetEntry::delta_content_length); } void @@ -2219,28 +2219,28 @@ QPDF::writeHSharedObject(BitWriter& w) 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); + (t.nshared_total > t.nshared_first_page) ? 1 : 0); int nitems = t.nshared_total; std::vector& entries = t.entries; write_vector_int(w, nitems, entries, - t.nbits_delta_group_length, - &HSharedObjectEntry::delta_group_length); + t.nbits_delta_group_length, + &HSharedObjectEntry::delta_group_length); write_vector_int(w, nitems, entries, - 1, &HSharedObjectEntry::signature_present); + 1, &HSharedObjectEntry::signature_present); 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) + // If signature were present, we'd have to write a 128-bit hash. + if (entries.at(i).signature_present != 0) { stopOnError("found unexpected signature present" " while writing linearization data"); } } write_vector_int(w, nitems, entries, - t.nbits_nobjects, - &HSharedObjectEntry::nobjects_minus_one); + t.nbits_nobjects, + &HSharedObjectEntry::nobjects_minus_one); } void @@ -2254,10 +2254,10 @@ QPDF::writeHGeneric(BitWriter& w, HGeneric& t) void QPDF::generateHintStream(std::map const& xref, - std::map const& lengths, - std::map const& obj_renumber, - PointerHolder& hint_buffer, - int& S, int& O) + std::map const& lengths, + std::map const& obj_renumber, + PointerHolder& hint_buffer, + int& S, int& O) { // Populate actual hint table values calculateHPageOffset(xref, lengths, obj_renumber); @@ -2277,8 +2277,8 @@ QPDF::generateHintStream(std::map const& xref, O = 0; if (this->m->outline_hints.nobjects > 0) { - O = toI(c.getCount()); - writeHGeneric(w, this->m->outline_hints); + 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 ae85e36c..bf799a78 100644 --- a/libqpdf/QPDF_optimization.cc +++ b/libqpdf/QPDF_optimization.cc @@ -41,18 +41,18 @@ QPDF::ObjUser::operator<(ObjUser const& rhs) const { if (this->ou_type < rhs.ou_type) { - return true; + return true; } else if (this->ou_type == rhs.ou_type) { - if (this->pageno < rhs.pageno) - { - return true; - } - else if (this->pageno == rhs.pageno) - { - return (this->key < rhs.key); - } + if (this->pageno < rhs.pageno) + { + return true; + } + else if (this->pageno == rhs.pageno) + { + return (this->key < rhs.key); + } } return false; @@ -60,20 +60,20 @@ QPDF::ObjUser::operator<(ObjUser const& rhs) const void QPDF::optimize(std::map const& object_stream_data, - bool allow_changes) + bool allow_changes) { optimize(object_stream_data, allow_changes, nullptr); } void QPDF::optimize(std::map const& object_stream_data, - bool allow_changes, + bool allow_changes, std::function skip_stream_parameters) { if (! this->m->obj_user_to_objects.empty()) { - // already optimized - return; + // already optimized + return; } // The PDF specification indicates that /Outlines is supposed to @@ -106,35 +106,35 @@ QPDF::optimize(std::map const& object_stream_data, // Traverse document-level items std::set keys = this->m->trailer.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) + iter != keys.end(); ++iter) { - std::string const& key = *iter; - if (key == "/Root") - { - // handled separately - } - else - { - updateObjectMaps(ObjUser(ObjUser::ou_trailer_key, key), - this->m->trailer.getKey(key), + std::string const& key = *iter; + if (key == "/Root") + { + // handled separately + } + else + { + updateObjectMaps(ObjUser(ObjUser::ou_trailer_key, key), + this->m->trailer.getKey(key), skip_stream_parameters); - } + } } keys = root.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) + iter != keys.end(); ++iter) { - // Technically, /I keys from /Thread dictionaries are supposed - // to be handled separately, but we are going to disregard - // that specification for now. There is loads of evidence - // that pdlin and Acrobat both disregard things like this from - // time to time, so this is almost certain not to cause any - // problems. - - std::string const& key = *iter; - updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), - root.getKey(key), + // Technically, /I keys from /Thread dictionaries are supposed + // to be handled separately, but we are going to disregard + // that specification for now. There is loads of evidence + // that pdlin and Acrobat both disregard things like this from + // time to time, so this is almost certain not to cause any + // problems. + + std::string const& key = *iter; + updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), + root.getKey(key), skip_stream_parameters); } @@ -208,10 +208,10 @@ QPDF::pushInheritedAttributesToPageInternal( if (! cur_pages.isDictionary()) { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "invalid object in page tree"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "invalid object in page tree"); } // Extract the underlying dictionary object @@ -219,60 +219,60 @@ QPDF::pushInheritedAttributesToPageInternal( if (type == "/Pages") { - // Make a list of inheritable keys. Only the keys /MediaBox, - // /CropBox, /Resources, and /Rotate are inheritable - // attributes. Push this object onto the stack of pages nodes - // that have values for this attribute. - - std::set inheritable_keys; - std::set keys = cur_pages.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - std::string const& key = *iter; + // Make a list of inheritable keys. Only the keys /MediaBox, + // /CropBox, /Resources, and /Rotate are inheritable + // attributes. Push this object onto the stack of pages nodes + // that have values for this attribute. + + std::set inheritable_keys; + std::set keys = cur_pages.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + std::string const& key = *iter; if ( (key == "/MediaBox") || (key == "/CropBox") || (key == "/Resources") || (key == "/Rotate") ) - { - if (! allow_changes) - { - throw QPDFExc(qpdf_e_internal, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "optimize detected an " + { + if (! allow_changes) + { + throw QPDFExc(qpdf_e_internal, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "optimize detected an " "inheritable attribute when called " - "in no-change mode"); - } - - // This is an inheritable resource - inheritable_keys.insert(key); - QPDFObjectHandle oh = cur_pages.getKey(key); - QTC::TC("qpdf", "QPDF opt direct pages resource", - oh.isIndirect() ? 0 : 1); - if (! oh.isIndirect()) - { - if (! oh.isScalar()) - { - // Replace shared direct object non-scalar - // resources with indirect objects to avoid - // copying large structures around. - cur_pages.replaceKey(key, makeIndirectObject(oh)); - oh = cur_pages.getKey(key); - } - else - { - // It's okay to copy scalars. - QTC::TC("qpdf", "QPDF opt inherited scalar"); - } - } - key_ancestors[key].push_back(oh); - if (key_ancestors[key].size() > 1) - { - QTC::TC("qpdf", "QPDF opt key ancestors depth > 1"); - } - // Remove this resource from this node. It will be - // reattached at the page level. - cur_pages.removeKey(key); - } + "in no-change mode"); + } + + // This is an inheritable resource + inheritable_keys.insert(key); + QPDFObjectHandle oh = cur_pages.getKey(key); + QTC::TC("qpdf", "QPDF opt direct pages resource", + oh.isIndirect() ? 0 : 1); + if (! oh.isIndirect()) + { + if (! oh.isScalar()) + { + // Replace shared direct object non-scalar + // resources with indirect objects to avoid + // copying large structures around. + cur_pages.replaceKey(key, makeIndirectObject(oh)); + oh = cur_pages.getKey(key); + } + else + { + // It's okay to copy scalars. + QTC::TC("qpdf", "QPDF opt inherited scalar"); + } + } + key_ancestors[key].push_back(oh); + if (key_ancestors[key].size() > 1) + { + QTC::TC("qpdf", "QPDF opt key ancestors depth > 1"); + } + // Remove this resource from this node. It will be + // reattached at the page level. + cur_pages.removeKey(key); + } else if (! ((key == "/Type") || (key == "/Parent") || (key == "/Kids") || (key == "/Count"))) { @@ -292,71 +292,71 @@ QPDF::pushInheritedAttributesToPageInternal( " flattening the /Pages tree")); } } - } + } - // Visit descendant nodes. - QPDFObjectHandle kids = cur_pages.getKey("/Kids"); - int n = kids.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + // Visit descendant nodes. + QPDFObjectHandle kids = cur_pages.getKey("/Kids"); + int n = kids.getArrayNItems(); + for (int i = 0; i < n; ++i) + { pushInheritedAttributesToPageInternal( kids.getArrayItem(i), key_ancestors, pages, allow_changes, warn_skipped_keys, visited); - } - - // For each inheritable key, pop the stack. If the stack - // becomes empty, remove it from the map. That way, the - // invariant that the list of keys in key_ancestors is exactly - // those keys for which inheritable attributes are available. - - if (! inheritable_keys.empty()) - { - QTC::TC("qpdf", "QPDF opt inheritable keys"); - for (std::set::iterator iter = - inheritable_keys.begin(); - iter != inheritable_keys.end(); ++iter) - { - std::string const& key = (*iter); - key_ancestors[key].pop_back(); - if (key_ancestors[key].empty()) - { - QTC::TC("qpdf", "QPDF opt erase empty key ancestor"); - key_ancestors.erase(key); - } - } - } - else - { - QTC::TC("qpdf", "QPDF opt no inheritable keys"); - } + } + + // For each inheritable key, pop the stack. If the stack + // becomes empty, remove it from the map. That way, the + // invariant that the list of keys in key_ancestors is exactly + // those keys for which inheritable attributes are available. + + if (! inheritable_keys.empty()) + { + QTC::TC("qpdf", "QPDF opt inheritable keys"); + for (std::set::iterator iter = + inheritable_keys.begin(); + iter != inheritable_keys.end(); ++iter) + { + std::string const& key = (*iter); + key_ancestors[key].pop_back(); + if (key_ancestors[key].empty()) + { + QTC::TC("qpdf", "QPDF opt erase empty key ancestor"); + key_ancestors.erase(key); + } + } + } + else + { + QTC::TC("qpdf", "QPDF opt no inheritable keys"); + } } else if (type == "/Page") { - // Add all available inheritable attributes not present in - // this object to this object. - for (std::map >::iterator - iter = key_ancestors.begin(); - iter != key_ancestors.end(); ++iter) - { - std::string const& key = (*iter).first; - if (! cur_pages.hasKey(key)) - { - QTC::TC("qpdf", "QPDF opt resource inherited"); - cur_pages.replaceKey(key, (*iter).second.back()); - } - else - { - QTC::TC("qpdf", "QPDF opt page resource hides ancestor"); - } - } + // Add all available inheritable attributes not present in + // this object to this object. + for (std::map >::iterator + iter = key_ancestors.begin(); + iter != key_ancestors.end(); ++iter) + { + std::string const& key = (*iter).first; + if (! cur_pages.hasKey(key)) + { + QTC::TC("qpdf", "QPDF opt resource inherited"); + cur_pages.replaceKey(key, (*iter).second.back()); + } + else + { + QTC::TC("qpdf", "QPDF opt page resource hides ancestor"); + } + } pages.push_back(cur_pages); } else { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "invalid Type " + type + " in page tree"); + throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "invalid Type " + type + " in page tree"); } visited.erase(this_og); } @@ -393,59 +393,59 @@ QPDF::updateObjectMapsInternal( if (oh.isIndirect()) { - QPDFObjGen og(oh.getObjGen()); - if (visited.count(og)) - { - QTC::TC("qpdf", "QPDF opt loop detected"); - return; - } - this->m->obj_user_to_objects[ou].insert(og); - this->m->object_to_obj_users[og].insert(ou); - visited.insert(og); + QPDFObjGen og(oh.getObjGen()); + if (visited.count(og)) + { + QTC::TC("qpdf", "QPDF opt loop detected"); + return; + } + this->m->obj_user_to_objects[ou].insert(og); + this->m->object_to_obj_users[og].insert(ou); + visited.insert(og); } if (oh.isArray()) { - int n = oh.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - updateObjectMapsInternal( + int n = oh.getArrayNItems(); + for (int i = 0; i < n; ++i) + { + updateObjectMapsInternal( ou, oh.getArrayItem(i), skip_stream_parameters, visited, false, 1 + depth); - } + } } else if (oh.isDictionary() || oh.isStream()) { - QPDFObjectHandle dict = oh; + QPDFObjectHandle dict = oh; bool is_stream = oh.isStream(); int ssp = 0; - if (is_stream) - { - dict = oh.getDict(); + if (is_stream) + { + dict = oh.getDict(); if (skip_stream_parameters) { ssp = skip_stream_parameters(oh); } - } - - std::set keys = dict.getKeys(); - for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - std::string const& key = *iter; - if (is_page_node && (key == "/Thumb")) - { - // Traverse page thumbnail dictionaries as a special - // case. - updateObjectMapsInternal( + } + + std::set keys = dict.getKeys(); + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); ++iter) + { + std::string const& key = *iter; + if (is_page_node && (key == "/Thumb")) + { + // Traverse page thumbnail dictionaries as a special + // case. + updateObjectMapsInternal( ObjUser(ObjUser::ou_thumb, ou.pageno), dict.getKey(key), skip_stream_parameters, visited, false, 1 + depth); - } - else if (is_page_node && (key == "/Parent")) - { - // Don't traverse back up the page tree - } + } + else if (is_page_node && (key == "/Parent")) + { + // Don't traverse back up the page tree + } else if (((ssp >= 1) && (key == "/Length")) || ((ssp >= 2) && ((key == "/Filter") || (key == "/DecodeParms")))) @@ -453,13 +453,13 @@ QPDF::updateObjectMapsInternal( // Don't traverse into stream parameters that we are // not going to write. } - else - { - updateObjectMapsInternal( + else + { + updateObjectMapsInternal( ou, dict.getKey(key), skip_stream_parameters, visited, false, 1 + depth); - } - } + } + } } } @@ -468,7 +468,7 @@ QPDF::filterCompressedObjects(std::map const& object_stream_data) { if (object_stream_data.empty()) { - return; + return; } // Transform object_to_obj_users and obj_user_to_objects so that @@ -480,49 +480,49 @@ QPDF::filterCompressedObjects(std::map const& object_stream_data) std::map > t_object_to_obj_users; for (std::map >::iterator i1 = - this->m->obj_user_to_objects.begin(); - i1 != this->m->obj_user_to_objects.end(); ++i1) + this->m->obj_user_to_objects.begin(); + i1 != this->m->obj_user_to_objects.end(); ++i1) { - ObjUser const& ou = (*i1).first; - std::set const& objects = (*i1).second; - for (std::set::const_iterator i2 = objects.begin(); - i2 != objects.end(); ++i2) - { - QPDFObjGen const& og = (*i2); - std::map::const_iterator i3 = - object_stream_data.find(og.getObj()); - if (i3 == object_stream_data.end()) - { - t_obj_user_to_objects[ou].insert(og); - } - else - { - t_obj_user_to_objects[ou].insert(QPDFObjGen((*i3).second, 0)); - } - } + ObjUser const& ou = (*i1).first; + std::set const& objects = (*i1).second; + for (std::set::const_iterator i2 = objects.begin(); + i2 != objects.end(); ++i2) + { + QPDFObjGen const& og = (*i2); + std::map::const_iterator i3 = + object_stream_data.find(og.getObj()); + if (i3 == object_stream_data.end()) + { + t_obj_user_to_objects[ou].insert(og); + } + else + { + t_obj_user_to_objects[ou].insert(QPDFObjGen((*i3).second, 0)); + } + } } for (std::map >::iterator i1 = - this->m->object_to_obj_users.begin(); - i1 != this->m->object_to_obj_users.end(); ++i1) + this->m->object_to_obj_users.begin(); + i1 != this->m->object_to_obj_users.end(); ++i1) { - QPDFObjGen const& og = (*i1).first; - std::set const& objusers = (*i1).second; - for (std::set::const_iterator i2 = objusers.begin(); - i2 != objusers.end(); ++i2) - { - ObjUser const& ou = (*i2); - std::map::const_iterator i3 = - object_stream_data.find(og.getObj()); - if (i3 == object_stream_data.end()) - { - t_object_to_obj_users[og].insert(ou); - } - else - { - t_object_to_obj_users[QPDFObjGen((*i3).second, 0)].insert(ou); - } - } + QPDFObjGen const& og = (*i1).first; + std::set const& objusers = (*i1).second; + for (std::set::const_iterator i2 = objusers.begin(); + i2 != objusers.end(); ++i2) + { + ObjUser const& ou = (*i2); + std::map::const_iterator i3 = + object_stream_data.find(og.getObj()); + if (i3 == object_stream_data.end()) + { + t_object_to_obj_users[og].insert(ou); + } + else + { + t_object_to_obj_users[QPDFObjGen((*i3).second, 0)].insert(ou); + } + } } this->m->obj_user_to_objects = t_obj_user_to_objects; diff --git a/libqpdf/QPDF_pages.cc b/libqpdf/QPDF_pages.cc index 2a1b798f..032809e2 100644 --- a/libqpdf/QPDF_pages.cc +++ b/libqpdf/QPDF_pages.cc @@ -86,7 +86,7 @@ QPDF::getAllPages() getRoot().replaceKey("/Pages", pages); } seen.clear(); - getAllPagesInternal(pages, this->m->all_pages, visited, seen); + getAllPagesInternal(pages, this->m->all_pages, visited, seen); } return this->m->all_pages; } @@ -110,10 +110,10 @@ QPDF::getAllPagesInternal(QPDFObjectHandle cur_node, if (cur_node.hasKey("/Kids")) { wanted_type = "/Pages"; - QPDFObjectHandle kids = cur_node.getKey("/Kids"); - int n = kids.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + QPDFObjectHandle kids = cur_node.getKey("/Kids"); + int n = kids.getArrayNItems(); + for (int i = 0; i < n; ++i) + { QPDFObjectHandle kid = kids.getArrayItem(i); if (! kid.isIndirect()) { @@ -129,14 +129,14 @@ QPDF::getAllPagesInternal(QPDFObjectHandle cur_node, kid = makeIndirectObject(QPDFObjectHandle(kid).shallowCopy()); kids.setArrayItem(i, kid); } - getAllPagesInternal(kid, result, visited, seen); - } + getAllPagesInternal(kid, result, visited, seen); + } } else { wanted_type = "/Page"; seen.insert(this_og); - result.push_back(cur_node); + result.push_back(cur_node); } if (! cur_node.isDictionaryOfType(wanted_type)) diff --git a/libqpdf/QTC.cc b/libqpdf/QTC.cc index cbaf558b..53e57ce2 100644 --- a/libqpdf/QTC.cc +++ b/libqpdf/QTC.cc @@ -16,7 +16,7 @@ void QTC::TC(char const* const scope, char const* const ccase, int n) if (! tc_active(scope)) { - return; + return; } std::string filename; @@ -27,13 +27,13 @@ void QTC::TC(char const* const scope, char const* const ccase, int n) #endif if (! QUtil::get_env(TC_ENV, &filename)) { - return; + return; } #undef TC_ENV if (cache.count(std::make_pair(ccase, n))) { - return; + return; } cache.insert(std::make_pair(ccase, n)); diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index 3c90bb90..d0ac13ed 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -300,12 +300,12 @@ int_to_string_base_internal(T num, int base, int length) int str_length = QIntC::to_int(cvt.length()); if ((length > 0) && (str_length < length)) { - result.append(QIntC::to_size(length - str_length), '0'); + result.append(QIntC::to_size(length - str_length), '0'); } result += cvt; if ((length < 0) && (str_length < -length)) { - result.append(QIntC::to_size(-length - str_length), ' '); + result.append(QIntC::to_size(-length - str_length), ' '); } return result; } @@ -455,7 +455,7 @@ QUtil::os_wrapper(std::string const& description, int status) { if (status == -1) { - throw_system_error(description); + throw_system_error(description); } return status; } @@ -523,7 +523,7 @@ QUtil::fopen_wrapper(std::string const& description, FILE* f) { if (f == 0) { - throw_system_error(description); + throw_system_error(description); } return f; } @@ -841,17 +841,17 @@ QUtil::getWhoami(char* argv0) if (((whoami = strrchr(argv0, '/')) == NULL) && ((whoami = strrchr(argv0, '\\')) == NULL)) { - whoami = argv0; + whoami = argv0; } else { - ++whoami; + ++whoami; } if ((strlen(whoami) > 4) && - (strcmp(whoami + strlen(whoami) - 4, ".exe") == 0)) + (strcmp(whoami + strlen(whoami) - 4, ".exe") == 0)) { - whoami[strlen(whoami) - 4] = '\0'; + whoami[strlen(whoami) - 4] = '\0'; } return whoami; @@ -875,9 +875,9 @@ QUtil::get_env(std::string const& var, std::string* value) if (value) { - PointerHolder t = PointerHolder(true, new char[len + 1]); + PointerHolder t = PointerHolder(true, new char[len + 1]); ::GetEnvironmentVariable(var.c_str(), t.get(), len); - *value = t.get(); + *value = t.get(); } return true; @@ -1057,42 +1057,42 @@ QUtil::toUTF8(unsigned long uval) if (uval > 0x7fffffff) { - throw std::runtime_error("bounds error in QUtil::toUTF8"); + throw std::runtime_error("bounds error in QUtil::toUTF8"); } else if (uval < 128) { - result += static_cast(uval); + result += static_cast(uval); } else { - unsigned char bytes[7]; - bytes[6] = '\0'; - unsigned char* cur_byte = &bytes[5]; - - // maximum value that will fit in the current number of bytes - unsigned char maxval = 0x3f; // six bits - - while (uval > QIntC::to_ulong(maxval)) - { - // Assign low six bits plus 10000000 to lowest unused - // byte position, then shift - *cur_byte = static_cast(0x80 + (uval & 0x3f)); - uval >>= 6; - // Maximum that will fit in high byte now shrinks by one bit - maxval = static_cast(maxval >> 1); - // Slide to the left one byte - if (cur_byte <= bytes) - { - throw std::logic_error("QUtil::toUTF8: overflow error"); - } - --cur_byte; - } - // If maxval is k bits long, the high (7 - k) bits of the - // resulting byte must be high. - *cur_byte = static_cast( + unsigned char bytes[7]; + bytes[6] = '\0'; + unsigned char* cur_byte = &bytes[5]; + + // maximum value that will fit in the current number of bytes + unsigned char maxval = 0x3f; // six bits + + while (uval > QIntC::to_ulong(maxval)) + { + // Assign low six bits plus 10000000 to lowest unused + // byte position, then shift + *cur_byte = static_cast(0x80 + (uval & 0x3f)); + uval >>= 6; + // Maximum that will fit in high byte now shrinks by one bit + maxval = static_cast(maxval >> 1); + // Slide to the left one byte + if (cur_byte <= bytes) + { + throw std::logic_error("QUtil::toUTF8: overflow error"); + } + --cur_byte; + } + // If maxval is k bits long, the high (7 - k) bits of the + // resulting byte must be high. + *cur_byte = static_cast( QIntC::to_ulong(0xff - (1 + (maxval << 1))) + uval); - result += reinterpret_cast(cur_byte); + result += reinterpret_cast(cur_byte); } return result; @@ -1350,19 +1350,19 @@ QUtil::read_lines_from_file(std::function next_char, char c; while (next_char(c)) { - if (buf == 0) - { - lines.push_back(""); - buf = &(lines.back()); - buf->reserve(80); - } - - if (buf->capacity() == buf->size()) - { - buf->reserve(buf->capacity() * 2); - } - if (c == '\n') - { + if (buf == 0) + { + lines.push_back(""); + buf = &(lines.back()); + buf->reserve(80); + } + + if (buf->capacity() == buf->size()) + { + buf->reserve(buf->capacity() * 2); + } + if (c == '\n') + { if (preserve_eol) { buf->append(1, c); @@ -1376,12 +1376,12 @@ QUtil::read_lines_from_file(std::function next_char, buf->erase(buf->length() - 1); } } - buf = 0; - } - else - { - buf->append(1, c); - } + buf = 0; + } + else + { + buf->append(1, c); + } } } diff --git a/libqpdf/RC4_native.cc b/libqpdf/RC4_native.cc index 8559d9bd..bb0b9013 100644 --- a/libqpdf/RC4_native.cc +++ b/libqpdf/RC4_native.cc @@ -17,7 +17,7 @@ RC4_native::RC4_native(unsigned char const* key_data, int key_len) { if (key_len == -1) { - key_len = QIntC::to_int( + key_len = QIntC::to_int( strlen(reinterpret_cast(key_data))); } @@ -32,9 +32,9 @@ RC4_native::RC4_native(unsigned char const* key_data, int key_len) int i2 = 0; for (int i = 0; i < 256; ++i) { - i2 = (key_data[i1] + key.state[i] + i2) % 256; - swap_byte(key.state[i], key.state[i2]); - i1 = (i1 + 1) % key_len; + i2 = (key_data[i1] + key.state[i] + i2) % 256; + swap_byte(key.state[i], key.state[i2]); + i1 = (i1 + 1) % key_len; } } @@ -43,16 +43,16 @@ RC4_native::process(unsigned char *in_data, size_t len, unsigned char* out_data) { if (out_data == 0) { - // Convert in place - out_data = in_data; + // Convert in place + out_data = in_data; } for (size_t i = 0; i < len; ++i) { - 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]; + 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/SF_FlateLzwDecode.cc b/libqpdf/SF_FlateLzwDecode.cc index d444aef1..196cbded 100644 --- a/libqpdf/SF_FlateLzwDecode.cc +++ b/libqpdf/SF_FlateLzwDecode.cc @@ -92,7 +92,7 @@ SF_FlateLzwDecode::setDecodeParms(QPDFObjectHandle decode_parms) if ((this->predictor > 1) && (this->columns == 0)) { - filterable = false; + filterable = false; } return filterable; diff --git a/libqpdf/SparseOHArray.cc b/libqpdf/SparseOHArray.cc index 38822e6d..1bcf8309 100644 --- a/libqpdf/SparseOHArray.cc +++ b/libqpdf/SparseOHArray.cc @@ -28,8 +28,8 @@ SparseOHArray::at(size_t idx) const { if (idx >= this->n_elements) { - throw std::logic_error( - "INTERNAL ERROR: bounds error accessing SparseOHArray element"); + throw std::logic_error( + "INTERNAL ERROR: bounds error accessing SparseOHArray element"); } auto const& iter = this->elements.find(idx); if (iter == this->elements.end()) @@ -47,8 +47,8 @@ SparseOHArray::remove_last() { if (this->n_elements == 0) { - throw std::logic_error( - "INTERNAL ERROR: attempt to remove" + throw std::logic_error( + "INTERNAL ERROR: attempt to remove" " last item from empty SparseOHArray"); } --this->n_elements; @@ -60,7 +60,7 @@ SparseOHArray::releaseResolved() { for (auto& iter: this->elements) { - QPDFObjectHandle::ReleaseResolver::releaseResolved(iter.second); + QPDFObjectHandle::ReleaseResolver::releaseResolved(iter.second); } } @@ -69,7 +69,7 @@ SparseOHArray::setAt(size_t idx, QPDFObjectHandle oh) { if (idx >= this->n_elements) { - throw std::logic_error("bounds error setting item in SparseOHArray"); + throw std::logic_error("bounds error setting item in SparseOHArray"); } if (oh.isDirectNull()) { @@ -86,7 +86,7 @@ SparseOHArray::erase(size_t idx) { if (idx >= this->n_elements) { - throw std::logic_error("bounds error erasing item from SparseOHArray"); + throw std::logic_error("bounds error erasing item from SparseOHArray"); } decltype(this->elements) dest; for (auto const& iter: this->elements) diff --git a/libqpdf/bits.icc b/libqpdf/bits.icc index 3fb9dfa1..14c4640d 100644 --- a/libqpdf/bits.icc +++ b/libqpdf/bits.icc @@ -18,7 +18,7 @@ #ifdef BITS_READ static unsigned long long read_bits(unsigned char const*& p, size_t& bit_offset, - size_t& bits_available, size_t bits_wanted) + size_t& bits_available, size_t bits_wanted) { // View p as a stream of bits: @@ -29,67 +29,67 @@ read_bits(unsigned char const*& p, size_t& bit_offset, if (bits_wanted > bits_available) { - throw std::runtime_error( + throw std::runtime_error( "overflow reading bit stream: wanted = " + QUtil::uint_to_string(bits_wanted) + "; available = " + QUtil::uint_to_string(bits_available)); } if (bits_wanted > 32) { - throw std::out_of_range("read_bits: too many bits requested"); + throw std::out_of_range("read_bits: too many bits requested"); } unsigned long result = 0; #ifdef BITS_TESTING if (bits_wanted == 0) { - QTC::TC("libtests", "bits zero bits wanted"); + QTC::TC("libtests", "bits zero bits wanted"); } #endif while (bits_wanted > 0) { - // Grab bits from the first byte clearing anything before - // bit_offset. - unsigned char byte = static_cast( + // Grab bits from the first byte clearing anything before + // bit_offset. + unsigned char byte = static_cast( *p & ((1U << (bit_offset + 1U)) - 1U)); - // There are bit_offset + 1 bits available in the first byte. - size_t to_copy = std::min(bits_wanted, bit_offset + 1); - size_t leftover = (bit_offset + 1) - to_copy; + // There are bit_offset + 1 bits available in the first byte. + 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", - ((bit_offset == 0) ? 0 : - (bit_offset == 7) ? 1 : - 2)); - QTC::TC("libtests", "bits leftover", (leftover > 0) ? 1 : 0); + QTC::TC("libtests", "bits bit_offset", + ((bit_offset == 0) ? 0 : + (bit_offset == 7) ? 1 : + 2)); + QTC::TC("libtests", "bits leftover", (leftover > 0) ? 1 : 0); #endif - // Right shift so that all the bits we want are right justified. - byte = static_cast(byte >> leftover); - - // Copy the bits into result - result <<= to_copy; - result |= byte; - - // Update pointers - if (leftover) - { - bit_offset = leftover - 1; - } - else - { - bit_offset = 7; - ++p; - } - bits_wanted -= to_copy; - bits_available -= to_copy; + // Right shift so that all the bits we want are right justified. + byte = static_cast(byte >> leftover); + + // Copy the bits into result + result <<= to_copy; + result |= byte; + + // Update pointers + if (leftover) + { + bit_offset = leftover - 1; + } + else + { + bit_offset = 7; + ++p; + } + bits_wanted -= to_copy; + bits_available -= to_copy; #ifdef BITS_TESTING - QTC::TC("libtests", "bits iterations", - ((bits_wanted > 8) ? 0 : - (bits_wanted > 0) ? 1 : - 2)); + QTC::TC("libtests", "bits iterations", + ((bits_wanted > 8) ? 0 : + (bits_wanted > 0) ? 1 : + 2)); #endif } @@ -100,50 +100,50 @@ read_bits(unsigned char const*& p, size_t& bit_offset, #ifdef BITS_WRITE static void write_bits(unsigned char& ch, size_t& bit_offset, - unsigned long long val, size_t bits, Pipeline* pipeline) + unsigned long long val, size_t bits, Pipeline* pipeline) { if (bits > 32) { - throw std::out_of_range("write_bits: too many bits requested"); + throw std::out_of_range("write_bits: too many bits requested"); } // bit_offset + 1 is the number of bits left in ch #ifdef BITS_TESTING if (bits == 0) { - QTC::TC("libtests", "bits write zero bits"); + QTC::TC("libtests", "bits write zero bits"); } #endif while (bits > 0) { - 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) - { + 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) + { #ifdef BITS_TESTING - QTC::TC("libtests", "bits write pipeline"); + QTC::TC("libtests", "bits write pipeline"); #endif - pipeline->write(&ch, 1); - bit_offset = 7; - ch = 0; - } - else - { + pipeline->write(&ch, 1); + bit_offset = 7; + ch = 0; + } + else + { #ifdef BITS_TESTING - QTC::TC("libtests", "bits write leftover"); + QTC::TC("libtests", "bits write leftover"); #endif - bit_offset -= bits_to_write; - } - bits -= bits_to_write; + bit_offset -= bits_to_write; + } + bits -= bits_to_write; #ifdef BITS_TESTING - QTC::TC("libtests", "bits write iterations", - ((bits > 8) ? 0 : - (bits > 0) ? 1 : - 2)); + QTC::TC("libtests", "bits write iterations", + ((bits > 8) ? 0 : + (bits > 0) ? 1 : + 2)); #endif } diff --git a/libqpdf/qpdf-c.cc b/libqpdf/qpdf-c.cc index 13297654..01c2a7ca 100644 --- a/libqpdf/qpdf-c.cc +++ b/libqpdf/qpdf-c.cc @@ -35,7 +35,7 @@ struct _qpdf_data std::string tmp_string; // Parameters for functions we call - char const* filename; // or description + char const* filename; // or description char const* buffer; unsigned long long size; char const* password; @@ -98,7 +98,7 @@ static void call_read(qpdf_data qpdf) static void call_read_memory(qpdf_data qpdf) { qpdf->qpdf->processMemoryFile(qpdf->filename, qpdf->buffer, - QIntC::to_size(qpdf->size), qpdf->password); + QIntC::to_size(qpdf->size), qpdf->password); } // must set qpdf->filename @@ -134,29 +134,29 @@ static QPDF_ERROR_CODE trap_errors( QPDF_ERROR_CODE status = QPDF_SUCCESS; try { - fn(qpdf); + fn(qpdf); } catch (QPDFExc& e) { - qpdf->error = make_pointer_holder(e); - status |= QPDF_ERRORS; + qpdf->error = make_pointer_holder(e); + status |= QPDF_ERRORS; } catch (std::runtime_error& e) { - qpdf->error = make_pointer_holder( + qpdf->error = make_pointer_holder( qpdf_e_system, "", "", 0, e.what()); - status |= QPDF_ERRORS; + status |= QPDF_ERRORS; } catch (std::exception& e) { - qpdf->error = make_pointer_holder( + qpdf->error = make_pointer_holder( qpdf_e_internal, "", "", 0, e.what()); - status |= QPDF_ERRORS; + status |= QPDF_ERRORS; } if (qpdf_more_warnings(qpdf)) { - status |= QPDF_WARNINGS; + status |= QPDF_WARNINGS; } return status; } @@ -202,19 +202,19 @@ QPDF_BOOL qpdf_more_warnings(qpdf_data qpdf) if (qpdf->warnings.empty()) { - std::vector w = qpdf->qpdf->getWarnings(); - if (! w.empty()) - { - qpdf->warnings.assign(w.begin(), w.end()); - } + std::vector w = qpdf->qpdf->getWarnings(); + if (! w.empty()) + { + qpdf->warnings.assign(w.begin(), w.end()); + } } if (qpdf->warnings.empty()) { - return QPDF_FALSE; + return QPDF_FALSE; } else { - return QPDF_TRUE; + return QPDF_TRUE; } } @@ -228,14 +228,14 @@ qpdf_error qpdf_get_error(qpdf_data qpdf) { if (qpdf->error.get()) { - qpdf->tmp_error.exc = qpdf->error; - qpdf->error = 0; - QTC::TC("qpdf", "qpdf-c qpdf_get_error returned error"); - return &qpdf->tmp_error; + qpdf->tmp_error.exc = qpdf->error; + qpdf->error = 0; + QTC::TC("qpdf", "qpdf-c qpdf_get_error returned error"); + return &qpdf->tmp_error; } else { - return 0; + return 0; } } @@ -243,15 +243,15 @@ qpdf_error qpdf_next_warning(qpdf_data qpdf) { if (qpdf_more_warnings(qpdf)) { - qpdf->tmp_error.exc = make_pointer_holder( + qpdf->tmp_error.exc = make_pointer_holder( qpdf->warnings.front()); - qpdf->warnings.pop_front(); - QTC::TC("qpdf", "qpdf-c qpdf_next_warning returned warning"); - return &qpdf->tmp_error; + qpdf->warnings.pop_front(); + QTC::TC("qpdf", "qpdf-c qpdf_next_warning returned warning"); + return &qpdf->tmp_error; } else { - return 0; + return 0; } } @@ -259,7 +259,7 @@ char const* qpdf_get_error_full_text(qpdf_data qpdf, qpdf_error e) { if (e == 0) { - return ""; + return ""; } return e->exc->what(); } @@ -268,7 +268,7 @@ enum qpdf_error_code_e qpdf_get_error_code(qpdf_data qpdf, qpdf_error e) { if (e == 0) { - return qpdf_e_success; + return qpdf_e_success; } return e->exc->getErrorCode(); } @@ -277,7 +277,7 @@ char const* qpdf_get_error_filename(qpdf_data qpdf, qpdf_error e) { if (e == 0) { - return ""; + return ""; } return e->exc->getFilename().c_str(); } @@ -286,7 +286,7 @@ unsigned long long qpdf_get_error_file_position(qpdf_data qpdf, qpdf_error e) { if (e == 0) { - return 0; + return 0; } return QIntC::to_ulonglong(e->exc->getFilePosition()); } @@ -295,7 +295,7 @@ char const* qpdf_get_error_message_detail(qpdf_data qpdf, qpdf_error e) { if (e == 0) { - return ""; + return ""; } return e->exc->getMessageDetail().c_str(); } @@ -326,7 +326,7 @@ void qpdf_set_attempt_recovery(qpdf_data qpdf, QPDF_BOOL value) } QPDF_ERROR_CODE qpdf_read(qpdf_data qpdf, char const* filename, - char const* password) + char const* password) { QPDF_ERROR_CODE status = QPDF_SUCCESS; qpdf->filename = filename; @@ -345,10 +345,10 @@ QPDF_ERROR_CODE qpdf_read(qpdf_data qpdf, char const* filename, } QPDF_ERROR_CODE qpdf_read_memory(qpdf_data qpdf, - char const* description, - char const* buffer, - unsigned long long size, - char const* password) + char const* description, + char const* buffer, + unsigned long long size, + char const* password) { QPDF_ERROR_CODE status = QPDF_SUCCESS; qpdf->filename = description; @@ -394,16 +394,16 @@ char const* qpdf_get_info_key(qpdf_data qpdf, char const* key) QPDFObjectHandle trailer = qpdf->qpdf->getTrailer(); if (trailer.hasKey("/Info")) { - QPDFObjectHandle info = trailer.getKey("/Info"); - if (info.hasKey(key)) - { - QPDFObjectHandle value = info.getKey(key); - if (value.isString()) - { - qpdf->tmp_string = value.getStringValue(); - result = qpdf->tmp_string.c_str(); - } - } + QPDFObjectHandle info = trailer.getKey("/Info"); + if (info.hasKey(key)) + { + QPDFObjectHandle value = info.getKey(key); + if (value.isString()) + { + qpdf->tmp_string = value.getStringValue(); + result = qpdf->tmp_string.c_str(); + } + } } QTC::TC("qpdf", "qpdf-c get_info_key", (result == 0 ? 0 : 1)); return result; @@ -413,31 +413,31 @@ void qpdf_set_info_key(qpdf_data qpdf, char const* key, char const* value) { if ((key == 0) || (std::strlen(key) == 0) || (key[0] != '/')) { - return; + return; } QPDFObjectHandle value_object; if (value) { - QTC::TC("qpdf", "qpdf-c set_info_key to value"); - value_object = QPDFObjectHandle::newString(value); + QTC::TC("qpdf", "qpdf-c set_info_key to value"); + value_object = QPDFObjectHandle::newString(value); } else { - QTC::TC("qpdf", "qpdf-c set_info_key to null"); - value_object = QPDFObjectHandle::newNull(); + QTC::TC("qpdf", "qpdf-c set_info_key to null"); + value_object = QPDFObjectHandle::newNull(); } QPDFObjectHandle trailer = qpdf->qpdf->getTrailer(); if (! trailer.hasKey("/Info")) { - QTC::TC("qpdf", "qpdf-c add info to trailer"); - trailer.replaceKey( - "/Info", - qpdf->qpdf->makeIndirectObject(QPDFObjectHandle::newDictionary())); + QTC::TC("qpdf", "qpdf-c add info to trailer"); + trailer.replaceKey( + "/Info", + qpdf->qpdf->makeIndirectObject(QPDFObjectHandle::newDictionary())); } else { - QTC::TC("qpdf", "qpdf-c set-info-key use existing info"); + QTC::TC("qpdf", "qpdf-c set-info-key use existing info"); } QPDFObjectHandle info = trailer.getKey("/Info"); @@ -514,14 +514,14 @@ static void qpdf_init_write_internal(qpdf_data qpdf) { if (qpdf->qpdf_writer.get()) { - QTC::TC("qpdf", "qpdf-c called qpdf_init_write multiple times"); - qpdf->qpdf_writer = 0; - if (qpdf->output_buffer.get()) - { - qpdf->output_buffer = 0; - qpdf->write_memory = false; - qpdf->filename = 0; - } + QTC::TC("qpdf", "qpdf-c called qpdf_init_write multiple times"); + qpdf->qpdf_writer = 0; + if (qpdf->output_buffer.get()) + { + qpdf->output_buffer = 0; + qpdf->write_memory = false; + qpdf->filename = 0; + } } } @@ -547,7 +547,7 @@ static void qpdf_get_buffer_internal(qpdf_data qpdf) { if (qpdf->write_memory && (qpdf->output_buffer == 0)) { - qpdf->output_buffer = qpdf->qpdf_writer->getBufferSharedPointer(); + qpdf->output_buffer = qpdf->qpdf_writer->getBufferSharedPointer(); } } @@ -557,7 +557,7 @@ size_t qpdf_get_buffer_length(qpdf_data qpdf) size_t result = 0; if (qpdf->output_buffer.get()) { - result = qpdf->output_buffer->getSize(); + result = qpdf->output_buffer->getSize(); } return result; } @@ -568,7 +568,7 @@ unsigned char const* qpdf_get_buffer(qpdf_data qpdf) qpdf_get_buffer_internal(qpdf); if (qpdf->output_buffer.get()) { - result = qpdf->output_buffer->getBuffer(); + result = qpdf->output_buffer->getBuffer(); } return result; } @@ -659,8 +659,8 @@ void qpdf_set_r2_encryption_parameters( { QTC::TC("qpdf", "qpdf-c called qpdf_set_r2_encryption_parameters"); qpdf->qpdf_writer->setR2EncryptionParameters( - user_password, owner_password, - allow_print != QPDF_FALSE, allow_modify != QPDF_FALSE, + user_password, owner_password, + allow_print != QPDF_FALSE, allow_modify != QPDF_FALSE, allow_extract != QPDF_FALSE, allow_annotate != QPDF_FALSE); } @@ -743,8 +743,8 @@ void qpdf_set_r3_encryption_parameters( # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR3EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, + user_password, owner_password, + allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, print, modify); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop @@ -765,10 +765,10 @@ void qpdf_set_r4_encryption_parameters( # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR4EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, + user_password, owner_password, + allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, print, modify, - encrypt_metadata != QPDF_FALSE, use_aes != QPDF_FALSE); + encrypt_metadata != QPDF_FALSE, use_aes != QPDF_FALSE); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif @@ -788,10 +788,10 @@ void qpdf_set_r5_encryption_parameters( # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR5EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, + user_password, owner_password, + allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, print, modify, - encrypt_metadata != QPDF_FALSE); + encrypt_metadata != QPDF_FALSE); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif @@ -811,8 +811,8 @@ void qpdf_set_r6_encryption_parameters( # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR6EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, + user_password, owner_password, + allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, print, modify, encrypt_metadata != QPDF_FALSE); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop diff --git a/libqpdf/qpdf/MD5.hh b/libqpdf/qpdf/MD5.hh index d04a89b4..bbea5707 100644 --- a/libqpdf/qpdf/MD5.hh +++ b/libqpdf/qpdf/MD5.hh @@ -51,13 +51,13 @@ class MD5 static std::string getDataChecksum(char const* buf, size_t len); QPDF_DLL static std::string getFileChecksum(char const* filename, - qpdf_offset_t up_to_offset = -1); + qpdf_offset_t up_to_offset = -1); QPDF_DLL static bool checkDataChecksum(char const* const checksum, - char const* buf, size_t len); + char const* buf, size_t len); QPDF_DLL static bool checkFileChecksum(char const* const checksum, - char const* filename, + char const* filename, qpdf_offset_t up_to_offset = -1); private: diff --git a/libqpdf/qpdf/MD5_native.hh b/libqpdf/qpdf/MD5_native.hh index d7e65a50..47486589 100644 --- a/libqpdf/qpdf/MD5_native.hh +++ b/libqpdf/qpdf/MD5_native.hh @@ -21,9 +21,9 @@ class MD5_native static void encode(unsigned char *, uint32_t *, size_t); static void decode(uint32_t *, unsigned char *, size_t); - uint32_t state[4]; // state (ABCD) - uint32_t count[2]; // number of bits, modulo 2^64 (lsb first) - unsigned char buffer[64]; // input buffer + uint32_t state[4]; // state (ABCD) + uint32_t count[2]; // number of bits, modulo 2^64 (lsb first) + unsigned char buffer[64]; // input buffer bool finalized; Digest digest_val; diff --git a/libqpdf/qpdf/Pl_AES_PDF.hh b/libqpdf/qpdf/Pl_AES_PDF.hh index 4d0d5fb3..87e4de55 100644 --- a/libqpdf/qpdf/Pl_AES_PDF.hh +++ b/libqpdf/qpdf/Pl_AES_PDF.hh @@ -14,7 +14,7 @@ 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, + bool encrypt, unsigned char const* key, size_t key_bytes); QPDF_DLL virtual ~Pl_AES_PDF(); diff --git a/libqpdf/qpdf/Pl_LZWDecoder.hh b/libqpdf/qpdf/Pl_LZWDecoder.hh index 0456310f..e034da05 100644 --- a/libqpdf/qpdf/Pl_LZWDecoder.hh +++ b/libqpdf/qpdf/Pl_LZWDecoder.hh @@ -11,7 +11,7 @@ class Pl_LZWDecoder: public Pipeline public: QPDF_DLL Pl_LZWDecoder(char const* identifier, Pipeline* next, - bool early_code_change); + bool early_code_change); QPDF_DLL virtual ~Pl_LZWDecoder(); QPDF_DLL diff --git a/libqpdf/qpdf/Pl_PNGFilter.hh b/libqpdf/qpdf/Pl_PNGFilter.hh index 3530a73a..ebf87aa3 100644 --- a/libqpdf/qpdf/Pl_PNGFilter.hh +++ b/libqpdf/qpdf/Pl_PNGFilter.hh @@ -17,7 +17,7 @@ class Pl_PNGFilter: public Pipeline QPDF_DLL Pl_PNGFilter(char const* identifier, Pipeline* next, - action_e action, unsigned int columns, + action_e action, unsigned int columns, unsigned int samples_per_pixel = 1, unsigned int bits_per_sample = 8); QPDF_DLL diff --git a/libqpdf/qpdf/Pl_RC4.hh b/libqpdf/qpdf/Pl_RC4.hh index 250ab2b8..33e35d58 100644 --- a/libqpdf/qpdf/Pl_RC4.hh +++ b/libqpdf/qpdf/Pl_RC4.hh @@ -13,8 +13,8 @@ class Pl_RC4: public Pipeline // key_len of -1 means treat key_data as a null-terminated string QPDF_DLL Pl_RC4(char const* identifier, Pipeline* next, - unsigned char const* key_data, int key_len = -1, - size_t out_bufsize = def_bufsize); + unsigned char const* key_data, int key_len = -1, + size_t out_bufsize = def_bufsize); QPDF_DLL virtual ~Pl_RC4(); diff --git a/libqpdf/qpdf/QPDF_Stream.hh b/libqpdf/qpdf/QPDF_Stream.hh index c4fdd379..3d70ea4e 100644 --- a/libqpdf/qpdf/QPDF_Stream.hh +++ b/libqpdf/qpdf/QPDF_Stream.hh @@ -17,8 +17,8 @@ class QPDF_Stream: public QPDFObject { public: QPDF_Stream(QPDF*, int objid, int generation, - QPDFObjectHandle stream_dict, - qpdf_offset_t offset, size_t length); + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, size_t length); virtual ~QPDF_Stream(); virtual std::string unparse(); virtual JSON getJSON(); @@ -44,12 +44,12 @@ class QPDF_Stream: public QPDFObject PointerHolder getStreamData(qpdf_stream_decode_level_e); PointerHolder getRawStreamData(); void replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); void replaceStreamData( - PointerHolder provider, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + PointerHolder provider, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); void addTokenFilter( PointerHolder token_filter); @@ -74,8 +74,8 @@ class QPDF_Stream: public QPDFObject std::function()>> filter_factories; void replaceFilterData(QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms, - size_t length); + QPDFObjectHandle const& decode_parms, + size_t length); bool filterable(std::vector>& filters, bool& specialized_compression, bool& lossy_compression); void warn(QPDFExc const& e); diff --git a/libqpdf/qpdfjob-c.cc b/libqpdf/qpdfjob-c.cc index 98bd82df..8d8b9d7c 100644 --- a/libqpdf/qpdfjob-c.cc +++ b/libqpdf/qpdfjob-c.cc @@ -21,7 +21,7 @@ int qpdfjob_run_from_argv(char const* const argv[]) } catch (std::exception& e) { - std::cerr << whoami << ": " << e.what() << std::endl; + std::cerr << whoami << ": " << e.what() << std::endl; return QPDFJob::EXIT_ERROR; } return j.getExitCode(); @@ -52,7 +52,7 @@ int qpdfjob_run_from_json(char const* json) } catch (std::exception& e) { - std::cerr << "qpdfjob json: " << e.what() << std::endl; + std::cerr << "qpdfjob json: " << e.what() << std::endl; return QPDFJob::EXIT_ERROR; } return j.getExitCode(); diff --git a/libqpdf/sha2.c b/libqpdf/sha2.c index 45fdd7e6..b8bfaaf1 100644 --- a/libqpdf/sha2.c +++ b/libqpdf/sha2.c @@ -50,15 +50,15 @@ #define SSG2_1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SPH_T32((x) >> 10)) static const sph_u32 H224[8] = { - SPH_C32(0xC1059ED8), SPH_C32(0x367CD507), SPH_C32(0x3070DD17), - SPH_C32(0xF70E5939), SPH_C32(0xFFC00B31), SPH_C32(0x68581511), - SPH_C32(0x64F98FA7), SPH_C32(0xBEFA4FA4) + SPH_C32(0xC1059ED8), SPH_C32(0x367CD507), SPH_C32(0x3070DD17), + SPH_C32(0xF70E5939), SPH_C32(0xFFC00B31), SPH_C32(0x68581511), + SPH_C32(0x64F98FA7), SPH_C32(0xBEFA4FA4) }; static const sph_u32 H256[8] = { - SPH_C32(0x6A09E667), SPH_C32(0xBB67AE85), SPH_C32(0x3C6EF372), - SPH_C32(0xA54FF53A), SPH_C32(0x510E527F), SPH_C32(0x9B05688C), - SPH_C32(0x1F83D9AB), SPH_C32(0x5BE0CD19) + SPH_C32(0x6A09E667), SPH_C32(0xBB67AE85), SPH_C32(0x3C6EF372), + SPH_C32(0xA54FF53A), SPH_C32(0x510E527F), SPH_C32(0x9B05688C), + SPH_C32(0x1F83D9AB), SPH_C32(0x5BE0CD19) }; /* @@ -74,531 +74,531 @@ static const sph_u32 H256[8] = { #if SPH_SMALL_FOOTPRINT_SHA2 static const sph_u32 K[64] = { - SPH_C32(0x428A2F98), SPH_C32(0x71374491), - SPH_C32(0xB5C0FBCF), SPH_C32(0xE9B5DBA5), - SPH_C32(0x3956C25B), SPH_C32(0x59F111F1), - SPH_C32(0x923F82A4), SPH_C32(0xAB1C5ED5), - SPH_C32(0xD807AA98), SPH_C32(0x12835B01), - SPH_C32(0x243185BE), SPH_C32(0x550C7DC3), - SPH_C32(0x72BE5D74), SPH_C32(0x80DEB1FE), - SPH_C32(0x9BDC06A7), SPH_C32(0xC19BF174), - SPH_C32(0xE49B69C1), SPH_C32(0xEFBE4786), - SPH_C32(0x0FC19DC6), SPH_C32(0x240CA1CC), - SPH_C32(0x2DE92C6F), SPH_C32(0x4A7484AA), - SPH_C32(0x5CB0A9DC), SPH_C32(0x76F988DA), - SPH_C32(0x983E5152), SPH_C32(0xA831C66D), - SPH_C32(0xB00327C8), SPH_C32(0xBF597FC7), - SPH_C32(0xC6E00BF3), SPH_C32(0xD5A79147), - SPH_C32(0x06CA6351), SPH_C32(0x14292967), - SPH_C32(0x27B70A85), SPH_C32(0x2E1B2138), - SPH_C32(0x4D2C6DFC), SPH_C32(0x53380D13), - SPH_C32(0x650A7354), SPH_C32(0x766A0ABB), - SPH_C32(0x81C2C92E), SPH_C32(0x92722C85), - SPH_C32(0xA2BFE8A1), SPH_C32(0xA81A664B), - SPH_C32(0xC24B8B70), SPH_C32(0xC76C51A3), - SPH_C32(0xD192E819), SPH_C32(0xD6990624), - SPH_C32(0xF40E3585), SPH_C32(0x106AA070), - SPH_C32(0x19A4C116), SPH_C32(0x1E376C08), - SPH_C32(0x2748774C), SPH_C32(0x34B0BCB5), - SPH_C32(0x391C0CB3), SPH_C32(0x4ED8AA4A), - SPH_C32(0x5B9CCA4F), SPH_C32(0x682E6FF3), - SPH_C32(0x748F82EE), SPH_C32(0x78A5636F), - SPH_C32(0x84C87814), SPH_C32(0x8CC70208), - SPH_C32(0x90BEFFFA), SPH_C32(0xA4506CEB), - SPH_C32(0xBEF9A3F7), SPH_C32(0xC67178F2) + SPH_C32(0x428A2F98), SPH_C32(0x71374491), + SPH_C32(0xB5C0FBCF), SPH_C32(0xE9B5DBA5), + SPH_C32(0x3956C25B), SPH_C32(0x59F111F1), + SPH_C32(0x923F82A4), SPH_C32(0xAB1C5ED5), + SPH_C32(0xD807AA98), SPH_C32(0x12835B01), + SPH_C32(0x243185BE), SPH_C32(0x550C7DC3), + SPH_C32(0x72BE5D74), SPH_C32(0x80DEB1FE), + SPH_C32(0x9BDC06A7), SPH_C32(0xC19BF174), + SPH_C32(0xE49B69C1), SPH_C32(0xEFBE4786), + SPH_C32(0x0FC19DC6), SPH_C32(0x240CA1CC), + SPH_C32(0x2DE92C6F), SPH_C32(0x4A7484AA), + SPH_C32(0x5CB0A9DC), SPH_C32(0x76F988DA), + SPH_C32(0x983E5152), SPH_C32(0xA831C66D), + SPH_C32(0xB00327C8), SPH_C32(0xBF597FC7), + SPH_C32(0xC6E00BF3), SPH_C32(0xD5A79147), + SPH_C32(0x06CA6351), SPH_C32(0x14292967), + SPH_C32(0x27B70A85), SPH_C32(0x2E1B2138), + SPH_C32(0x4D2C6DFC), SPH_C32(0x53380D13), + SPH_C32(0x650A7354), SPH_C32(0x766A0ABB), + SPH_C32(0x81C2C92E), SPH_C32(0x92722C85), + SPH_C32(0xA2BFE8A1), SPH_C32(0xA81A664B), + SPH_C32(0xC24B8B70), SPH_C32(0xC76C51A3), + SPH_C32(0xD192E819), SPH_C32(0xD6990624), + SPH_C32(0xF40E3585), SPH_C32(0x106AA070), + SPH_C32(0x19A4C116), SPH_C32(0x1E376C08), + SPH_C32(0x2748774C), SPH_C32(0x34B0BCB5), + SPH_C32(0x391C0CB3), SPH_C32(0x4ED8AA4A), + SPH_C32(0x5B9CCA4F), SPH_C32(0x682E6FF3), + SPH_C32(0x748F82EE), SPH_C32(0x78A5636F), + SPH_C32(0x84C87814), SPH_C32(0x8CC70208), + SPH_C32(0x90BEFFFA), SPH_C32(0xA4506CEB), + SPH_C32(0xBEF9A3F7), SPH_C32(0xC67178F2) }; #define SHA2_MEXP1(in, pc) do { \ - W[pc] = in(pc); \ - } while (0) + W[pc] = in(pc); \ + } while (0) #define SHA2_MEXP2(in, pc) do { \ - W[(pc) & 0x0F] = SPH_T32(SSG2_1(W[((pc) - 2) & 0x0F]) \ - + W[((pc) - 7) & 0x0F] \ - + SSG2_0(W[((pc) - 15) & 0x0F]) + W[(pc) & 0x0F]); \ - } while (0) + W[(pc) & 0x0F] = SPH_T32(SSG2_1(W[((pc) - 2) & 0x0F]) \ + + W[((pc) - 7) & 0x0F] \ + + SSG2_0(W[((pc) - 15) & 0x0F]) + W[(pc) & 0x0F]); \ + } while (0) #define SHA2_STEPn(n, a, b, c, d, e, f, g, h, in, pc) do { \ - sph_u32 t1, t2; \ - SHA2_MEXP ## n(in, pc); \ - t1 = SPH_T32(h + BSG2_1(e) + CH(e, f, g) \ - + K[pcount + (pc)] + W[(pc) & 0x0F]); \ - t2 = SPH_T32(BSG2_0(a) + MAJ(a, b, c)); \ - d = SPH_T32(d + t1); \ - h = SPH_T32(t1 + t2); \ - } while (0) + sph_u32 t1, t2; \ + SHA2_MEXP ## n(in, pc); \ + t1 = SPH_T32(h + BSG2_1(e) + CH(e, f, g) \ + + K[pcount + (pc)] + W[(pc) & 0x0F]); \ + t2 = SPH_T32(BSG2_0(a) + MAJ(a, b, c)); \ + d = SPH_T32(d + t1); \ + h = SPH_T32(t1 + t2); \ + } while (0) #define SHA2_STEP1(a, b, c, d, e, f, g, h, in, pc) \ - SHA2_STEPn(1, a, b, c, d, e, f, g, h, in, pc) + SHA2_STEPn(1, a, b, c, d, e, f, g, h, in, pc) #define SHA2_STEP2(a, b, c, d, e, f, g, h, in, pc) \ - SHA2_STEPn(2, a, b, c, d, e, f, g, h, in, pc) + SHA2_STEPn(2, a, b, c, d, e, f, g, h, in, pc) #define SHA2_ROUND_BODY(in, r) do { \ - sph_u32 A, B, C, D, E, F, G, H; \ - sph_u32 W[16]; \ - unsigned pcount; \ + sph_u32 A, B, C, D, E, F, G, H; \ + sph_u32 W[16]; \ + unsigned pcount; \ \ - A = (r)[0]; \ - B = (r)[1]; \ - C = (r)[2]; \ - D = (r)[3]; \ - E = (r)[4]; \ - F = (r)[5]; \ - G = (r)[6]; \ - H = (r)[7]; \ - pcount = 0; \ - SHA2_STEP1(A, B, C, D, E, F, G, H, in, 0); \ - SHA2_STEP1(H, A, B, C, D, E, F, G, in, 1); \ - SHA2_STEP1(G, H, A, B, C, D, E, F, in, 2); \ - SHA2_STEP1(F, G, H, A, B, C, D, E, in, 3); \ - SHA2_STEP1(E, F, G, H, A, B, C, D, in, 4); \ - SHA2_STEP1(D, E, F, G, H, A, B, C, in, 5); \ - SHA2_STEP1(C, D, E, F, G, H, A, B, in, 6); \ - SHA2_STEP1(B, C, D, E, F, G, H, A, in, 7); \ - SHA2_STEP1(A, B, C, D, E, F, G, H, in, 8); \ - SHA2_STEP1(H, A, B, C, D, E, F, G, in, 9); \ - SHA2_STEP1(G, H, A, B, C, D, E, F, in, 10); \ - SHA2_STEP1(F, G, H, A, B, C, D, E, in, 11); \ - SHA2_STEP1(E, F, G, H, A, B, C, D, in, 12); \ - SHA2_STEP1(D, E, F, G, H, A, B, C, in, 13); \ - SHA2_STEP1(C, D, E, F, G, H, A, B, in, 14); \ - SHA2_STEP1(B, C, D, E, F, G, H, A, in, 15); \ - for (pcount = 16; pcount < 64; pcount += 16) { \ - SHA2_STEP2(A, B, C, D, E, F, G, H, in, 0); \ - SHA2_STEP2(H, A, B, C, D, E, F, G, in, 1); \ - SHA2_STEP2(G, H, A, B, C, D, E, F, in, 2); \ - SHA2_STEP2(F, G, H, A, B, C, D, E, in, 3); \ - SHA2_STEP2(E, F, G, H, A, B, C, D, in, 4); \ - SHA2_STEP2(D, E, F, G, H, A, B, C, in, 5); \ - SHA2_STEP2(C, D, E, F, G, H, A, B, in, 6); \ - SHA2_STEP2(B, C, D, E, F, G, H, A, in, 7); \ - SHA2_STEP2(A, B, C, D, E, F, G, H, in, 8); \ - SHA2_STEP2(H, A, B, C, D, E, F, G, in, 9); \ - SHA2_STEP2(G, H, A, B, C, D, E, F, in, 10); \ - SHA2_STEP2(F, G, H, A, B, C, D, E, in, 11); \ - SHA2_STEP2(E, F, G, H, A, B, C, D, in, 12); \ - SHA2_STEP2(D, E, F, G, H, A, B, C, in, 13); \ - SHA2_STEP2(C, D, E, F, G, H, A, B, in, 14); \ - SHA2_STEP2(B, C, D, E, F, G, H, A, in, 15); \ - } \ - (r)[0] = SPH_T32((r)[0] + A); \ - (r)[1] = SPH_T32((r)[1] + B); \ - (r)[2] = SPH_T32((r)[2] + C); \ - (r)[3] = SPH_T32((r)[3] + D); \ - (r)[4] = SPH_T32((r)[4] + E); \ - (r)[5] = SPH_T32((r)[5] + F); \ - (r)[6] = SPH_T32((r)[6] + G); \ - (r)[7] = SPH_T32((r)[7] + H); \ - } while (0) + A = (r)[0]; \ + B = (r)[1]; \ + C = (r)[2]; \ + D = (r)[3]; \ + E = (r)[4]; \ + F = (r)[5]; \ + G = (r)[6]; \ + H = (r)[7]; \ + pcount = 0; \ + SHA2_STEP1(A, B, C, D, E, F, G, H, in, 0); \ + SHA2_STEP1(H, A, B, C, D, E, F, G, in, 1); \ + SHA2_STEP1(G, H, A, B, C, D, E, F, in, 2); \ + SHA2_STEP1(F, G, H, A, B, C, D, E, in, 3); \ + SHA2_STEP1(E, F, G, H, A, B, C, D, in, 4); \ + SHA2_STEP1(D, E, F, G, H, A, B, C, in, 5); \ + SHA2_STEP1(C, D, E, F, G, H, A, B, in, 6); \ + SHA2_STEP1(B, C, D, E, F, G, H, A, in, 7); \ + SHA2_STEP1(A, B, C, D, E, F, G, H, in, 8); \ + SHA2_STEP1(H, A, B, C, D, E, F, G, in, 9); \ + SHA2_STEP1(G, H, A, B, C, D, E, F, in, 10); \ + SHA2_STEP1(F, G, H, A, B, C, D, E, in, 11); \ + SHA2_STEP1(E, F, G, H, A, B, C, D, in, 12); \ + SHA2_STEP1(D, E, F, G, H, A, B, C, in, 13); \ + SHA2_STEP1(C, D, E, F, G, H, A, B, in, 14); \ + SHA2_STEP1(B, C, D, E, F, G, H, A, in, 15); \ + for (pcount = 16; pcount < 64; pcount += 16) { \ + SHA2_STEP2(A, B, C, D, E, F, G, H, in, 0); \ + SHA2_STEP2(H, A, B, C, D, E, F, G, in, 1); \ + SHA2_STEP2(G, H, A, B, C, D, E, F, in, 2); \ + SHA2_STEP2(F, G, H, A, B, C, D, E, in, 3); \ + SHA2_STEP2(E, F, G, H, A, B, C, D, in, 4); \ + SHA2_STEP2(D, E, F, G, H, A, B, C, in, 5); \ + SHA2_STEP2(C, D, E, F, G, H, A, B, in, 6); \ + SHA2_STEP2(B, C, D, E, F, G, H, A, in, 7); \ + SHA2_STEP2(A, B, C, D, E, F, G, H, in, 8); \ + SHA2_STEP2(H, A, B, C, D, E, F, G, in, 9); \ + SHA2_STEP2(G, H, A, B, C, D, E, F, in, 10); \ + SHA2_STEP2(F, G, H, A, B, C, D, E, in, 11); \ + SHA2_STEP2(E, F, G, H, A, B, C, D, in, 12); \ + SHA2_STEP2(D, E, F, G, H, A, B, C, in, 13); \ + SHA2_STEP2(C, D, E, F, G, H, A, B, in, 14); \ + SHA2_STEP2(B, C, D, E, F, G, H, A, in, 15); \ + } \ + (r)[0] = SPH_T32((r)[0] + A); \ + (r)[1] = SPH_T32((r)[1] + B); \ + (r)[2] = SPH_T32((r)[2] + C); \ + (r)[3] = SPH_T32((r)[3] + D); \ + (r)[4] = SPH_T32((r)[4] + E); \ + (r)[5] = SPH_T32((r)[5] + F); \ + (r)[6] = SPH_T32((r)[6] + G); \ + (r)[7] = SPH_T32((r)[7] + H); \ + } while (0) #else #define SHA2_ROUND_BODY(in, r) do { \ - sph_u32 A, B, C, D, E, F, G, H, T1, T2; \ - sph_u32 W00, W01, W02, W03, W04, W05, W06, W07; \ - sph_u32 W08, W09, W10, W11, W12, W13, W14, W15; \ + sph_u32 A, B, C, D, E, F, G, H, T1, T2; \ + sph_u32 W00, W01, W02, W03, W04, W05, W06, W07; \ + sph_u32 W08, W09, W10, W11, W12, W13, W14, W15; \ \ - A = (r)[0]; \ - B = (r)[1]; \ - C = (r)[2]; \ - D = (r)[3]; \ - E = (r)[4]; \ - F = (r)[5]; \ - G = (r)[6]; \ - H = (r)[7]; \ - W00 = in(0); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0x428A2F98) + W00); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W01 = in(1); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0x71374491) + W01); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W02 = in(2); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0xB5C0FBCF) + W02); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W03 = in(3); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0xE9B5DBA5) + W03); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W04 = in(4); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0x3956C25B) + W04); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W05 = in(5); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0x59F111F1) + W05); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W06 = in(6); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0x923F82A4) + W06); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W07 = in(7); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0xAB1C5ED5) + W07); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W08 = in(8); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0xD807AA98) + W08); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W09 = in(9); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0x12835B01) + W09); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W10 = in(10); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0x243185BE) + W10); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W11 = in(11); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0x550C7DC3) + W11); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W12 = in(12); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0x72BE5D74) + W12); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W13 = in(13); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0x80DEB1FE) + W13); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W14 = in(14); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0x9BDC06A7) + W14); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W15 = in(15); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0xC19BF174) + W15); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W00 = SPH_T32(SSG2_1(W14) + W09 + SSG2_0(W01) + W00); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0xE49B69C1) + W00); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W01 = SPH_T32(SSG2_1(W15) + W10 + SSG2_0(W02) + W01); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0xEFBE4786) + W01); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W02 = SPH_T32(SSG2_1(W00) + W11 + SSG2_0(W03) + W02); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0x0FC19DC6) + W02); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W03 = SPH_T32(SSG2_1(W01) + W12 + SSG2_0(W04) + W03); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0x240CA1CC) + W03); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W04 = SPH_T32(SSG2_1(W02) + W13 + SSG2_0(W05) + W04); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0x2DE92C6F) + W04); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W05 = SPH_T32(SSG2_1(W03) + W14 + SSG2_0(W06) + W05); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0x4A7484AA) + W05); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W06 = SPH_T32(SSG2_1(W04) + W15 + SSG2_0(W07) + W06); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0x5CB0A9DC) + W06); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W07 = SPH_T32(SSG2_1(W05) + W00 + SSG2_0(W08) + W07); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0x76F988DA) + W07); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W08 = SPH_T32(SSG2_1(W06) + W01 + SSG2_0(W09) + W08); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0x983E5152) + W08); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W09 = SPH_T32(SSG2_1(W07) + W02 + SSG2_0(W10) + W09); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0xA831C66D) + W09); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W10 = SPH_T32(SSG2_1(W08) + W03 + SSG2_0(W11) + W10); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0xB00327C8) + W10); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W11 = SPH_T32(SSG2_1(W09) + W04 + SSG2_0(W12) + W11); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0xBF597FC7) + W11); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W12 = SPH_T32(SSG2_1(W10) + W05 + SSG2_0(W13) + W12); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0xC6E00BF3) + W12); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W13 = SPH_T32(SSG2_1(W11) + W06 + SSG2_0(W14) + W13); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0xD5A79147) + W13); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W14 = SPH_T32(SSG2_1(W12) + W07 + SSG2_0(W15) + W14); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0x06CA6351) + W14); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W15 = SPH_T32(SSG2_1(W13) + W08 + SSG2_0(W00) + W15); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0x14292967) + W15); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W00 = SPH_T32(SSG2_1(W14) + W09 + SSG2_0(W01) + W00); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0x27B70A85) + W00); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W01 = SPH_T32(SSG2_1(W15) + W10 + SSG2_0(W02) + W01); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0x2E1B2138) + W01); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W02 = SPH_T32(SSG2_1(W00) + W11 + SSG2_0(W03) + W02); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0x4D2C6DFC) + W02); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W03 = SPH_T32(SSG2_1(W01) + W12 + SSG2_0(W04) + W03); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0x53380D13) + W03); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W04 = SPH_T32(SSG2_1(W02) + W13 + SSG2_0(W05) + W04); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0x650A7354) + W04); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W05 = SPH_T32(SSG2_1(W03) + W14 + SSG2_0(W06) + W05); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0x766A0ABB) + W05); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W06 = SPH_T32(SSG2_1(W04) + W15 + SSG2_0(W07) + W06); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0x81C2C92E) + W06); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W07 = SPH_T32(SSG2_1(W05) + W00 + SSG2_0(W08) + W07); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0x92722C85) + W07); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W08 = SPH_T32(SSG2_1(W06) + W01 + SSG2_0(W09) + W08); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0xA2BFE8A1) + W08); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W09 = SPH_T32(SSG2_1(W07) + W02 + SSG2_0(W10) + W09); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0xA81A664B) + W09); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W10 = SPH_T32(SSG2_1(W08) + W03 + SSG2_0(W11) + W10); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0xC24B8B70) + W10); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W11 = SPH_T32(SSG2_1(W09) + W04 + SSG2_0(W12) + W11); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0xC76C51A3) + W11); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W12 = SPH_T32(SSG2_1(W10) + W05 + SSG2_0(W13) + W12); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0xD192E819) + W12); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W13 = SPH_T32(SSG2_1(W11) + W06 + SSG2_0(W14) + W13); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0xD6990624) + W13); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W14 = SPH_T32(SSG2_1(W12) + W07 + SSG2_0(W15) + W14); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0xF40E3585) + W14); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W15 = SPH_T32(SSG2_1(W13) + W08 + SSG2_0(W00) + W15); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0x106AA070) + W15); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W00 = SPH_T32(SSG2_1(W14) + W09 + SSG2_0(W01) + W00); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0x19A4C116) + W00); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W01 = SPH_T32(SSG2_1(W15) + W10 + SSG2_0(W02) + W01); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0x1E376C08) + W01); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W02 = SPH_T32(SSG2_1(W00) + W11 + SSG2_0(W03) + W02); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0x2748774C) + W02); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W03 = SPH_T32(SSG2_1(W01) + W12 + SSG2_0(W04) + W03); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0x34B0BCB5) + W03); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W04 = SPH_T32(SSG2_1(W02) + W13 + SSG2_0(W05) + W04); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0x391C0CB3) + W04); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W05 = SPH_T32(SSG2_1(W03) + W14 + SSG2_0(W06) + W05); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0x4ED8AA4A) + W05); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W06 = SPH_T32(SSG2_1(W04) + W15 + SSG2_0(W07) + W06); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0x5B9CCA4F) + W06); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W07 = SPH_T32(SSG2_1(W05) + W00 + SSG2_0(W08) + W07); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0x682E6FF3) + W07); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - W08 = SPH_T32(SSG2_1(W06) + W01 + SSG2_0(W09) + W08); \ - T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ - + SPH_C32(0x748F82EE) + W08); \ - T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ - D = SPH_T32(D + T1); \ - H = SPH_T32(T1 + T2); \ - W09 = SPH_T32(SSG2_1(W07) + W02 + SSG2_0(W10) + W09); \ - T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ - + SPH_C32(0x78A5636F) + W09); \ - T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ - C = SPH_T32(C + T1); \ - G = SPH_T32(T1 + T2); \ - W10 = SPH_T32(SSG2_1(W08) + W03 + SSG2_0(W11) + W10); \ - T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ - + SPH_C32(0x84C87814) + W10); \ - T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ - B = SPH_T32(B + T1); \ - F = SPH_T32(T1 + T2); \ - W11 = SPH_T32(SSG2_1(W09) + W04 + SSG2_0(W12) + W11); \ - T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ - + SPH_C32(0x8CC70208) + W11); \ - T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ - A = SPH_T32(A + T1); \ - E = SPH_T32(T1 + T2); \ - W12 = SPH_T32(SSG2_1(W10) + W05 + SSG2_0(W13) + W12); \ - T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ - + SPH_C32(0x90BEFFFA) + W12); \ - T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ - H = SPH_T32(H + T1); \ - D = SPH_T32(T1 + T2); \ - W13 = SPH_T32(SSG2_1(W11) + W06 + SSG2_0(W14) + W13); \ - T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ - + SPH_C32(0xA4506CEB) + W13); \ - T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ - G = SPH_T32(G + T1); \ - C = SPH_T32(T1 + T2); \ - W14 = SPH_T32(SSG2_1(W12) + W07 + SSG2_0(W15) + W14); \ - T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ - + SPH_C32(0xBEF9A3F7) + W14); \ - T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ - F = SPH_T32(F + T1); \ - B = SPH_T32(T1 + T2); \ - W15 = SPH_T32(SSG2_1(W13) + W08 + SSG2_0(W00) + W15); \ - T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ - + SPH_C32(0xC67178F2) + W15); \ - T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ - E = SPH_T32(E + T1); \ - A = SPH_T32(T1 + T2); \ - (r)[0] = SPH_T32((r)[0] + A); \ - (r)[1] = SPH_T32((r)[1] + B); \ - (r)[2] = SPH_T32((r)[2] + C); \ - (r)[3] = SPH_T32((r)[3] + D); \ - (r)[4] = SPH_T32((r)[4] + E); \ - (r)[5] = SPH_T32((r)[5] + F); \ - (r)[6] = SPH_T32((r)[6] + G); \ - (r)[7] = SPH_T32((r)[7] + H); \ - } while (0) + A = (r)[0]; \ + B = (r)[1]; \ + C = (r)[2]; \ + D = (r)[3]; \ + E = (r)[4]; \ + F = (r)[5]; \ + G = (r)[6]; \ + H = (r)[7]; \ + W00 = in(0); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0x428A2F98) + W00); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W01 = in(1); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0x71374491) + W01); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W02 = in(2); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0xB5C0FBCF) + W02); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W03 = in(3); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0xE9B5DBA5) + W03); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W04 = in(4); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0x3956C25B) + W04); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W05 = in(5); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0x59F111F1) + W05); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W06 = in(6); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0x923F82A4) + W06); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W07 = in(7); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0xAB1C5ED5) + W07); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W08 = in(8); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0xD807AA98) + W08); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W09 = in(9); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0x12835B01) + W09); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W10 = in(10); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0x243185BE) + W10); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W11 = in(11); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0x550C7DC3) + W11); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W12 = in(12); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0x72BE5D74) + W12); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W13 = in(13); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0x80DEB1FE) + W13); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W14 = in(14); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0x9BDC06A7) + W14); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W15 = in(15); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0xC19BF174) + W15); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W00 = SPH_T32(SSG2_1(W14) + W09 + SSG2_0(W01) + W00); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0xE49B69C1) + W00); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W01 = SPH_T32(SSG2_1(W15) + W10 + SSG2_0(W02) + W01); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0xEFBE4786) + W01); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W02 = SPH_T32(SSG2_1(W00) + W11 + SSG2_0(W03) + W02); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0x0FC19DC6) + W02); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W03 = SPH_T32(SSG2_1(W01) + W12 + SSG2_0(W04) + W03); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0x240CA1CC) + W03); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W04 = SPH_T32(SSG2_1(W02) + W13 + SSG2_0(W05) + W04); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0x2DE92C6F) + W04); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W05 = SPH_T32(SSG2_1(W03) + W14 + SSG2_0(W06) + W05); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0x4A7484AA) + W05); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W06 = SPH_T32(SSG2_1(W04) + W15 + SSG2_0(W07) + W06); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0x5CB0A9DC) + W06); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W07 = SPH_T32(SSG2_1(W05) + W00 + SSG2_0(W08) + W07); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0x76F988DA) + W07); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W08 = SPH_T32(SSG2_1(W06) + W01 + SSG2_0(W09) + W08); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0x983E5152) + W08); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W09 = SPH_T32(SSG2_1(W07) + W02 + SSG2_0(W10) + W09); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0xA831C66D) + W09); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W10 = SPH_T32(SSG2_1(W08) + W03 + SSG2_0(W11) + W10); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0xB00327C8) + W10); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W11 = SPH_T32(SSG2_1(W09) + W04 + SSG2_0(W12) + W11); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0xBF597FC7) + W11); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W12 = SPH_T32(SSG2_1(W10) + W05 + SSG2_0(W13) + W12); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0xC6E00BF3) + W12); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W13 = SPH_T32(SSG2_1(W11) + W06 + SSG2_0(W14) + W13); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0xD5A79147) + W13); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W14 = SPH_T32(SSG2_1(W12) + W07 + SSG2_0(W15) + W14); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0x06CA6351) + W14); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W15 = SPH_T32(SSG2_1(W13) + W08 + SSG2_0(W00) + W15); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0x14292967) + W15); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W00 = SPH_T32(SSG2_1(W14) + W09 + SSG2_0(W01) + W00); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0x27B70A85) + W00); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W01 = SPH_T32(SSG2_1(W15) + W10 + SSG2_0(W02) + W01); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0x2E1B2138) + W01); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W02 = SPH_T32(SSG2_1(W00) + W11 + SSG2_0(W03) + W02); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0x4D2C6DFC) + W02); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W03 = SPH_T32(SSG2_1(W01) + W12 + SSG2_0(W04) + W03); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0x53380D13) + W03); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W04 = SPH_T32(SSG2_1(W02) + W13 + SSG2_0(W05) + W04); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0x650A7354) + W04); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W05 = SPH_T32(SSG2_1(W03) + W14 + SSG2_0(W06) + W05); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0x766A0ABB) + W05); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W06 = SPH_T32(SSG2_1(W04) + W15 + SSG2_0(W07) + W06); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0x81C2C92E) + W06); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W07 = SPH_T32(SSG2_1(W05) + W00 + SSG2_0(W08) + W07); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0x92722C85) + W07); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W08 = SPH_T32(SSG2_1(W06) + W01 + SSG2_0(W09) + W08); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0xA2BFE8A1) + W08); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W09 = SPH_T32(SSG2_1(W07) + W02 + SSG2_0(W10) + W09); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0xA81A664B) + W09); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W10 = SPH_T32(SSG2_1(W08) + W03 + SSG2_0(W11) + W10); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0xC24B8B70) + W10); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W11 = SPH_T32(SSG2_1(W09) + W04 + SSG2_0(W12) + W11); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0xC76C51A3) + W11); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W12 = SPH_T32(SSG2_1(W10) + W05 + SSG2_0(W13) + W12); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0xD192E819) + W12); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W13 = SPH_T32(SSG2_1(W11) + W06 + SSG2_0(W14) + W13); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0xD6990624) + W13); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W14 = SPH_T32(SSG2_1(W12) + W07 + SSG2_0(W15) + W14); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0xF40E3585) + W14); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W15 = SPH_T32(SSG2_1(W13) + W08 + SSG2_0(W00) + W15); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0x106AA070) + W15); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W00 = SPH_T32(SSG2_1(W14) + W09 + SSG2_0(W01) + W00); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0x19A4C116) + W00); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W01 = SPH_T32(SSG2_1(W15) + W10 + SSG2_0(W02) + W01); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0x1E376C08) + W01); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W02 = SPH_T32(SSG2_1(W00) + W11 + SSG2_0(W03) + W02); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0x2748774C) + W02); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W03 = SPH_T32(SSG2_1(W01) + W12 + SSG2_0(W04) + W03); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0x34B0BCB5) + W03); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W04 = SPH_T32(SSG2_1(W02) + W13 + SSG2_0(W05) + W04); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0x391C0CB3) + W04); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W05 = SPH_T32(SSG2_1(W03) + W14 + SSG2_0(W06) + W05); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0x4ED8AA4A) + W05); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W06 = SPH_T32(SSG2_1(W04) + W15 + SSG2_0(W07) + W06); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0x5B9CCA4F) + W06); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W07 = SPH_T32(SSG2_1(W05) + W00 + SSG2_0(W08) + W07); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0x682E6FF3) + W07); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + W08 = SPH_T32(SSG2_1(W06) + W01 + SSG2_0(W09) + W08); \ + T1 = SPH_T32(H + BSG2_1(E) + CH(E, F, G) \ + + SPH_C32(0x748F82EE) + W08); \ + T2 = SPH_T32(BSG2_0(A) + MAJ(A, B, C)); \ + D = SPH_T32(D + T1); \ + H = SPH_T32(T1 + T2); \ + W09 = SPH_T32(SSG2_1(W07) + W02 + SSG2_0(W10) + W09); \ + T1 = SPH_T32(G + BSG2_1(D) + CH(D, E, F) \ + + SPH_C32(0x78A5636F) + W09); \ + T2 = SPH_T32(BSG2_0(H) + MAJ(H, A, B)); \ + C = SPH_T32(C + T1); \ + G = SPH_T32(T1 + T2); \ + W10 = SPH_T32(SSG2_1(W08) + W03 + SSG2_0(W11) + W10); \ + T1 = SPH_T32(F + BSG2_1(C) + CH(C, D, E) \ + + SPH_C32(0x84C87814) + W10); \ + T2 = SPH_T32(BSG2_0(G) + MAJ(G, H, A)); \ + B = SPH_T32(B + T1); \ + F = SPH_T32(T1 + T2); \ + W11 = SPH_T32(SSG2_1(W09) + W04 + SSG2_0(W12) + W11); \ + T1 = SPH_T32(E + BSG2_1(B) + CH(B, C, D) \ + + SPH_C32(0x8CC70208) + W11); \ + T2 = SPH_T32(BSG2_0(F) + MAJ(F, G, H)); \ + A = SPH_T32(A + T1); \ + E = SPH_T32(T1 + T2); \ + W12 = SPH_T32(SSG2_1(W10) + W05 + SSG2_0(W13) + W12); \ + T1 = SPH_T32(D + BSG2_1(A) + CH(A, B, C) \ + + SPH_C32(0x90BEFFFA) + W12); \ + T2 = SPH_T32(BSG2_0(E) + MAJ(E, F, G)); \ + H = SPH_T32(H + T1); \ + D = SPH_T32(T1 + T2); \ + W13 = SPH_T32(SSG2_1(W11) + W06 + SSG2_0(W14) + W13); \ + T1 = SPH_T32(C + BSG2_1(H) + CH(H, A, B) \ + + SPH_C32(0xA4506CEB) + W13); \ + T2 = SPH_T32(BSG2_0(D) + MAJ(D, E, F)); \ + G = SPH_T32(G + T1); \ + C = SPH_T32(T1 + T2); \ + W14 = SPH_T32(SSG2_1(W12) + W07 + SSG2_0(W15) + W14); \ + T1 = SPH_T32(B + BSG2_1(G) + CH(G, H, A) \ + + SPH_C32(0xBEF9A3F7) + W14); \ + T2 = SPH_T32(BSG2_0(C) + MAJ(C, D, E)); \ + F = SPH_T32(F + T1); \ + B = SPH_T32(T1 + T2); \ + W15 = SPH_T32(SSG2_1(W13) + W08 + SSG2_0(W00) + W15); \ + T1 = SPH_T32(A + BSG2_1(F) + CH(F, G, H) \ + + SPH_C32(0xC67178F2) + W15); \ + T2 = SPH_T32(BSG2_0(B) + MAJ(B, C, D)); \ + E = SPH_T32(E + T1); \ + A = SPH_T32(T1 + T2); \ + (r)[0] = SPH_T32((r)[0] + A); \ + (r)[1] = SPH_T32((r)[1] + B); \ + (r)[2] = SPH_T32((r)[2] + C); \ + (r)[3] = SPH_T32((r)[3] + D); \ + (r)[4] = SPH_T32((r)[4] + E); \ + (r)[5] = SPH_T32((r)[5] + F); \ + (r)[6] = SPH_T32((r)[6] + G); \ + (r)[7] = SPH_T32((r)[7] + H); \ + } while (0) #endif @@ -609,7 +609,7 @@ static void sha2_round(const unsigned char *data, sph_u32 r[8]) { #define SHA2_IN(x) sph_dec32be_aligned(data + (4 * (x))) - SHA2_ROUND_BODY(SHA2_IN, r); + SHA2_ROUND_BODY(SHA2_IN, r); #undef SHA2_IN } @@ -617,14 +617,14 @@ sha2_round(const unsigned char *data, sph_u32 r[8]) void sph_sha224_init(void *cc) { - sph_sha224_context *sc; + sph_sha224_context *sc; - sc = cc; - memcpy(sc->val, H224, sizeof H224); + sc = cc; + memcpy(sc->val, H224, sizeof H224); #if SPH_64 - sc->count = 0; + sc->count = 0; #else - sc->count_high = sc->count_low = 0; + sc->count_high = sc->count_low = 0; #endif } @@ -632,14 +632,14 @@ sph_sha224_init(void *cc) void sph_sha256_init(void *cc) { - sph_sha256_context *sc; + sph_sha256_context *sc; - sc = cc; - memcpy(sc->val, H256, sizeof H256); + sc = cc; + memcpy(sc->val, H256, sizeof H256); #if SPH_64 - sc->count = 0; + sc->count = 0; #else - sc->count_high = sc->count_low = 0; + sc->count_high = sc->count_low = 0; #endif } @@ -652,32 +652,32 @@ sph_sha256_init(void *cc) void sph_sha224_close(void *cc, void *dst) { - sha224_close(cc, dst, 7); - sph_sha224_init(cc); + sha224_close(cc, dst, 7); + sph_sha224_init(cc); } /* see sph_sha2.h */ void sph_sha224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { - sha224_addbits_and_close(cc, ub, n, dst, 7); - sph_sha224_init(cc); + sha224_addbits_and_close(cc, ub, n, dst, 7); + sph_sha224_init(cc); } /* see sph_sha2.h */ void sph_sha256_close(void *cc, void *dst) { - sha224_close(cc, dst, 8); - sph_sha256_init(cc); + sha224_close(cc, dst, 8); + sph_sha256_init(cc); } /* see sph_sha2.h */ void sph_sha256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { - sha224_addbits_and_close(cc, ub, n, dst, 8); - sph_sha256_init(cc); + sha224_addbits_and_close(cc, ub, n, dst, 8); + sph_sha256_init(cc); } /* see sph_sha2.h */ @@ -685,6 +685,6 @@ void sph_sha224_comp(const sph_u32 msg[16], sph_u32 val[8]) { #define SHA2_IN(x) msg[x] - SHA2_ROUND_BODY(SHA2_IN, val); + SHA2_ROUND_BODY(SHA2_IN, val); #undef SHA2_IN } diff --git a/libqpdf/sha2big.c b/libqpdf/sha2big.c index e4aadbdb..34d1f3d9 100644 --- a/libqpdf/sha2big.c +++ b/libqpdf/sha2big.c @@ -48,60 +48,60 @@ #define SSG5_1(x) (ROTR64(x, 19) ^ ROTR64(x, 61) ^ SPH_T64((x) >> 6)) static const sph_u64 K512[80] = { - SPH_C64(0x428A2F98D728AE22), SPH_C64(0x7137449123EF65CD), - SPH_C64(0xB5C0FBCFEC4D3B2F), SPH_C64(0xE9B5DBA58189DBBC), - SPH_C64(0x3956C25BF348B538), SPH_C64(0x59F111F1B605D019), - SPH_C64(0x923F82A4AF194F9B), SPH_C64(0xAB1C5ED5DA6D8118), - SPH_C64(0xD807AA98A3030242), SPH_C64(0x12835B0145706FBE), - SPH_C64(0x243185BE4EE4B28C), SPH_C64(0x550C7DC3D5FFB4E2), - SPH_C64(0x72BE5D74F27B896F), SPH_C64(0x80DEB1FE3B1696B1), - SPH_C64(0x9BDC06A725C71235), SPH_C64(0xC19BF174CF692694), - SPH_C64(0xE49B69C19EF14AD2), SPH_C64(0xEFBE4786384F25E3), - SPH_C64(0x0FC19DC68B8CD5B5), SPH_C64(0x240CA1CC77AC9C65), - SPH_C64(0x2DE92C6F592B0275), SPH_C64(0x4A7484AA6EA6E483), - SPH_C64(0x5CB0A9DCBD41FBD4), SPH_C64(0x76F988DA831153B5), - SPH_C64(0x983E5152EE66DFAB), SPH_C64(0xA831C66D2DB43210), - SPH_C64(0xB00327C898FB213F), SPH_C64(0xBF597FC7BEEF0EE4), - SPH_C64(0xC6E00BF33DA88FC2), SPH_C64(0xD5A79147930AA725), - SPH_C64(0x06CA6351E003826F), SPH_C64(0x142929670A0E6E70), - SPH_C64(0x27B70A8546D22FFC), SPH_C64(0x2E1B21385C26C926), - SPH_C64(0x4D2C6DFC5AC42AED), SPH_C64(0x53380D139D95B3DF), - SPH_C64(0x650A73548BAF63DE), SPH_C64(0x766A0ABB3C77B2A8), - SPH_C64(0x81C2C92E47EDAEE6), SPH_C64(0x92722C851482353B), - SPH_C64(0xA2BFE8A14CF10364), SPH_C64(0xA81A664BBC423001), - SPH_C64(0xC24B8B70D0F89791), SPH_C64(0xC76C51A30654BE30), - SPH_C64(0xD192E819D6EF5218), SPH_C64(0xD69906245565A910), - SPH_C64(0xF40E35855771202A), SPH_C64(0x106AA07032BBD1B8), - SPH_C64(0x19A4C116B8D2D0C8), SPH_C64(0x1E376C085141AB53), - SPH_C64(0x2748774CDF8EEB99), SPH_C64(0x34B0BCB5E19B48A8), - SPH_C64(0x391C0CB3C5C95A63), SPH_C64(0x4ED8AA4AE3418ACB), - SPH_C64(0x5B9CCA4F7763E373), SPH_C64(0x682E6FF3D6B2B8A3), - SPH_C64(0x748F82EE5DEFB2FC), SPH_C64(0x78A5636F43172F60), - SPH_C64(0x84C87814A1F0AB72), SPH_C64(0x8CC702081A6439EC), - SPH_C64(0x90BEFFFA23631E28), SPH_C64(0xA4506CEBDE82BDE9), - SPH_C64(0xBEF9A3F7B2C67915), SPH_C64(0xC67178F2E372532B), - SPH_C64(0xCA273ECEEA26619C), SPH_C64(0xD186B8C721C0C207), - SPH_C64(0xEADA7DD6CDE0EB1E), SPH_C64(0xF57D4F7FEE6ED178), - SPH_C64(0x06F067AA72176FBA), SPH_C64(0x0A637DC5A2C898A6), - SPH_C64(0x113F9804BEF90DAE), SPH_C64(0x1B710B35131C471B), - SPH_C64(0x28DB77F523047D84), SPH_C64(0x32CAAB7B40C72493), - SPH_C64(0x3C9EBE0A15C9BEBC), SPH_C64(0x431D67C49C100D4C), - SPH_C64(0x4CC5D4BECB3E42B6), SPH_C64(0x597F299CFC657E2A), - SPH_C64(0x5FCB6FAB3AD6FAEC), SPH_C64(0x6C44198C4A475817) + SPH_C64(0x428A2F98D728AE22), SPH_C64(0x7137449123EF65CD), + SPH_C64(0xB5C0FBCFEC4D3B2F), SPH_C64(0xE9B5DBA58189DBBC), + SPH_C64(0x3956C25BF348B538), SPH_C64(0x59F111F1B605D019), + SPH_C64(0x923F82A4AF194F9B), SPH_C64(0xAB1C5ED5DA6D8118), + SPH_C64(0xD807AA98A3030242), SPH_C64(0x12835B0145706FBE), + SPH_C64(0x243185BE4EE4B28C), SPH_C64(0x550C7DC3D5FFB4E2), + SPH_C64(0x72BE5D74F27B896F), SPH_C64(0x80DEB1FE3B1696B1), + SPH_C64(0x9BDC06A725C71235), SPH_C64(0xC19BF174CF692694), + SPH_C64(0xE49B69C19EF14AD2), SPH_C64(0xEFBE4786384F25E3), + SPH_C64(0x0FC19DC68B8CD5B5), SPH_C64(0x240CA1CC77AC9C65), + SPH_C64(0x2DE92C6F592B0275), SPH_C64(0x4A7484AA6EA6E483), + SPH_C64(0x5CB0A9DCBD41FBD4), SPH_C64(0x76F988DA831153B5), + SPH_C64(0x983E5152EE66DFAB), SPH_C64(0xA831C66D2DB43210), + SPH_C64(0xB00327C898FB213F), SPH_C64(0xBF597FC7BEEF0EE4), + SPH_C64(0xC6E00BF33DA88FC2), SPH_C64(0xD5A79147930AA725), + SPH_C64(0x06CA6351E003826F), SPH_C64(0x142929670A0E6E70), + SPH_C64(0x27B70A8546D22FFC), SPH_C64(0x2E1B21385C26C926), + SPH_C64(0x4D2C6DFC5AC42AED), SPH_C64(0x53380D139D95B3DF), + SPH_C64(0x650A73548BAF63DE), SPH_C64(0x766A0ABB3C77B2A8), + SPH_C64(0x81C2C92E47EDAEE6), SPH_C64(0x92722C851482353B), + SPH_C64(0xA2BFE8A14CF10364), SPH_C64(0xA81A664BBC423001), + SPH_C64(0xC24B8B70D0F89791), SPH_C64(0xC76C51A30654BE30), + SPH_C64(0xD192E819D6EF5218), SPH_C64(0xD69906245565A910), + SPH_C64(0xF40E35855771202A), SPH_C64(0x106AA07032BBD1B8), + SPH_C64(0x19A4C116B8D2D0C8), SPH_C64(0x1E376C085141AB53), + SPH_C64(0x2748774CDF8EEB99), SPH_C64(0x34B0BCB5E19B48A8), + SPH_C64(0x391C0CB3C5C95A63), SPH_C64(0x4ED8AA4AE3418ACB), + SPH_C64(0x5B9CCA4F7763E373), SPH_C64(0x682E6FF3D6B2B8A3), + SPH_C64(0x748F82EE5DEFB2FC), SPH_C64(0x78A5636F43172F60), + SPH_C64(0x84C87814A1F0AB72), SPH_C64(0x8CC702081A6439EC), + SPH_C64(0x90BEFFFA23631E28), SPH_C64(0xA4506CEBDE82BDE9), + SPH_C64(0xBEF9A3F7B2C67915), SPH_C64(0xC67178F2E372532B), + SPH_C64(0xCA273ECEEA26619C), SPH_C64(0xD186B8C721C0C207), + SPH_C64(0xEADA7DD6CDE0EB1E), SPH_C64(0xF57D4F7FEE6ED178), + SPH_C64(0x06F067AA72176FBA), SPH_C64(0x0A637DC5A2C898A6), + SPH_C64(0x113F9804BEF90DAE), SPH_C64(0x1B710B35131C471B), + SPH_C64(0x28DB77F523047D84), SPH_C64(0x32CAAB7B40C72493), + SPH_C64(0x3C9EBE0A15C9BEBC), SPH_C64(0x431D67C49C100D4C), + SPH_C64(0x4CC5D4BECB3E42B6), SPH_C64(0x597F299CFC657E2A), + SPH_C64(0x5FCB6FAB3AD6FAEC), SPH_C64(0x6C44198C4A475817) }; static const sph_u64 H384[8] = { - SPH_C64(0xCBBB9D5DC1059ED8), SPH_C64(0x629A292A367CD507), - SPH_C64(0x9159015A3070DD17), SPH_C64(0x152FECD8F70E5939), - SPH_C64(0x67332667FFC00B31), SPH_C64(0x8EB44A8768581511), - SPH_C64(0xDB0C2E0D64F98FA7), SPH_C64(0x47B5481DBEFA4FA4) + SPH_C64(0xCBBB9D5DC1059ED8), SPH_C64(0x629A292A367CD507), + SPH_C64(0x9159015A3070DD17), SPH_C64(0x152FECD8F70E5939), + SPH_C64(0x67332667FFC00B31), SPH_C64(0x8EB44A8768581511), + SPH_C64(0xDB0C2E0D64F98FA7), SPH_C64(0x47B5481DBEFA4FA4) }; static const sph_u64 H512[8] = { - SPH_C64(0x6A09E667F3BCC908), SPH_C64(0xBB67AE8584CAA73B), - SPH_C64(0x3C6EF372FE94F82B), SPH_C64(0xA54FF53A5F1D36F1), - SPH_C64(0x510E527FADE682D1), SPH_C64(0x9B05688C2B3E6C1F), - SPH_C64(0x1F83D9ABFB41BD6B), SPH_C64(0x5BE0CD19137E2179) + SPH_C64(0x6A09E667F3BCC908), SPH_C64(0xBB67AE8584CAA73B), + SPH_C64(0x3C6EF372FE94F82B), SPH_C64(0xA54FF53A5F1D36F1), + SPH_C64(0x510E527FADE682D1), SPH_C64(0x9B05688C2B3E6C1F), + SPH_C64(0x1F83D9ABFB41BD6B), SPH_C64(0x5BE0CD19137E2179) }; /* @@ -120,50 +120,50 @@ static const sph_u64 H512[8] = { */ #define SHA3_STEP(A, B, C, D, E, F, G, H, i) do { \ - sph_u64 T1, T2; \ - T1 = SPH_T64(H + BSG5_1(E) + CH(E, F, G) + K512[i] + W[i]); \ - T2 = SPH_T64(BSG5_0(A) + MAJ(A, B, C)); \ - D = SPH_T64(D + T1); \ - H = SPH_T64(T1 + T2); \ - } while (0) + sph_u64 T1, T2; \ + T1 = SPH_T64(H + BSG5_1(E) + CH(E, F, G) + K512[i] + W[i]); \ + T2 = SPH_T64(BSG5_0(A) + MAJ(A, B, C)); \ + D = SPH_T64(D + T1); \ + H = SPH_T64(T1 + T2); \ + } while (0) #define SHA3_ROUND_BODY(in, r) do { \ - int i; \ - sph_u64 A, B, C, D, E, F, G, H; \ - sph_u64 W[80]; \ + int i; \ + sph_u64 A, B, C, D, E, F, G, H; \ + sph_u64 W[80]; \ \ - for (i = 0; i < 16; i ++) \ - W[i] = in(i); \ - for (i = 16; i < 80; i ++) \ - W[i] = SPH_T64(SSG5_1(W[i - 2]) + W[i - 7] \ - + SSG5_0(W[i - 15]) + W[i - 16]); \ - A = (r)[0]; \ - B = (r)[1]; \ - C = (r)[2]; \ - D = (r)[3]; \ - E = (r)[4]; \ - F = (r)[5]; \ - G = (r)[6]; \ - H = (r)[7]; \ - for (i = 0; i < 80; i += 8) { \ - SHA3_STEP(A, B, C, D, E, F, G, H, i + 0); \ - SHA3_STEP(H, A, B, C, D, E, F, G, i + 1); \ - SHA3_STEP(G, H, A, B, C, D, E, F, i + 2); \ - SHA3_STEP(F, G, H, A, B, C, D, E, i + 3); \ - SHA3_STEP(E, F, G, H, A, B, C, D, i + 4); \ - SHA3_STEP(D, E, F, G, H, A, B, C, i + 5); \ - SHA3_STEP(C, D, E, F, G, H, A, B, i + 6); \ - SHA3_STEP(B, C, D, E, F, G, H, A, i + 7); \ - } \ - (r)[0] = SPH_T64((r)[0] + A); \ - (r)[1] = SPH_T64((r)[1] + B); \ - (r)[2] = SPH_T64((r)[2] + C); \ - (r)[3] = SPH_T64((r)[3] + D); \ - (r)[4] = SPH_T64((r)[4] + E); \ - (r)[5] = SPH_T64((r)[5] + F); \ - (r)[6] = SPH_T64((r)[6] + G); \ - (r)[7] = SPH_T64((r)[7] + H); \ - } while (0) + for (i = 0; i < 16; i ++) \ + W[i] = in(i); \ + for (i = 16; i < 80; i ++) \ + W[i] = SPH_T64(SSG5_1(W[i - 2]) + W[i - 7] \ + + SSG5_0(W[i - 15]) + W[i - 16]); \ + A = (r)[0]; \ + B = (r)[1]; \ + C = (r)[2]; \ + D = (r)[3]; \ + E = (r)[4]; \ + F = (r)[5]; \ + G = (r)[6]; \ + H = (r)[7]; \ + for (i = 0; i < 80; i += 8) { \ + SHA3_STEP(A, B, C, D, E, F, G, H, i + 0); \ + SHA3_STEP(H, A, B, C, D, E, F, G, i + 1); \ + SHA3_STEP(G, H, A, B, C, D, E, F, i + 2); \ + SHA3_STEP(F, G, H, A, B, C, D, E, i + 3); \ + SHA3_STEP(E, F, G, H, A, B, C, D, i + 4); \ + SHA3_STEP(D, E, F, G, H, A, B, C, i + 5); \ + SHA3_STEP(C, D, E, F, G, H, A, B, i + 6); \ + SHA3_STEP(B, C, D, E, F, G, H, A, i + 7); \ + } \ + (r)[0] = SPH_T64((r)[0] + A); \ + (r)[1] = SPH_T64((r)[1] + B); \ + (r)[2] = SPH_T64((r)[2] + C); \ + (r)[3] = SPH_T64((r)[3] + D); \ + (r)[4] = SPH_T64((r)[4] + E); \ + (r)[5] = SPH_T64((r)[5] + F); \ + (r)[6] = SPH_T64((r)[6] + G); \ + (r)[7] = SPH_T64((r)[7] + H); \ + } while (0) /* * One round of SHA-384 / SHA-512. The data must be aligned for 64-bit access. @@ -172,7 +172,7 @@ static void sha3_round(const unsigned char *data, sph_u64 r[8]) { #define SHA3_IN(x) sph_dec64be_aligned(data + (8 * (x))) - SHA3_ROUND_BODY(SHA3_IN, r); + SHA3_ROUND_BODY(SHA3_IN, r); #undef SHA3_IN } @@ -180,22 +180,22 @@ sha3_round(const unsigned char *data, sph_u64 r[8]) void sph_sha384_init(void *cc) { - sph_sha384_context *sc; + sph_sha384_context *sc; - sc = cc; - memcpy(sc->val, H384, sizeof H384); - sc->count = 0; + sc = cc; + memcpy(sc->val, H384, sizeof H384); + sc->count = 0; } /* see sph_sha3.h */ void sph_sha512_init(void *cc) { - sph_sha512_context *sc; + sph_sha512_context *sc; - sc = cc; - memcpy(sc->val, H512, sizeof H512); - sc->count = 0; + sc = cc; + memcpy(sc->val, H512, sizeof H512); + sc->count = 0; } #define RFUN sha3_round @@ -207,32 +207,32 @@ sph_sha512_init(void *cc) void sph_sha384_close(void *cc, void *dst) { - sha384_close(cc, dst, 6); - sph_sha384_init(cc); + sha384_close(cc, dst, 6); + sph_sha384_init(cc); } /* see sph_sha3.h */ void sph_sha384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { - sha384_addbits_and_close(cc, ub, n, dst, 6); - sph_sha384_init(cc); + sha384_addbits_and_close(cc, ub, n, dst, 6); + sph_sha384_init(cc); } /* see sph_sha3.h */ void sph_sha512_close(void *cc, void *dst) { - sha384_close(cc, dst, 8); - sph_sha512_init(cc); + sha384_close(cc, dst, 8); + sph_sha512_init(cc); } /* see sph_sha3.h */ void sph_sha512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { - sha384_addbits_and_close(cc, ub, n, dst, 8); - sph_sha512_init(cc); + sha384_addbits_and_close(cc, ub, n, dst, 8); + sph_sha512_init(cc); } /* see sph_sha3.h */ @@ -240,7 +240,7 @@ void sph_sha384_comp(const sph_u64 msg[16], sph_u64 val[8]) { #define SHA3_IN(x) msg[x] - SHA3_ROUND_BODY(SHA3_IN, val); + SHA3_ROUND_BODY(SHA3_IN, val); #undef SHA3_IN } diff --git a/libqpdf/sph/md_helper.c b/libqpdf/sph/md_helper.c index 829391a7..5c114515 100644 --- a/libqpdf/sph/md_helper.c +++ b/libqpdf/sph/md_helper.c @@ -128,103 +128,103 @@ void SPH_XCAT(sph_, HASH)(void *cc, const void *data, size_t len) #endif { - SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; - unsigned current; + SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; + unsigned current; - sc = cc; + sc = cc; #if SPH_64 - current = (unsigned)sc->count & (SPH_BLEN - 1U); + current = (unsigned)sc->count & (SPH_BLEN - 1U); #else - current = (unsigned)sc->count_low & (SPH_BLEN - 1U); + current = (unsigned)sc->count_low & (SPH_BLEN - 1U); #endif - while (len > 0) { - unsigned clen; + while (len > 0) { + unsigned clen; #if !SPH_64 - sph_u32 clow, clow2; + sph_u32 clow, clow2; #endif - clen = SPH_BLEN - current; - if (clen > len) - clen = (unsigned)len; - memcpy(sc->buf + current, data, clen); - data = (const unsigned char *)data + clen; - current += clen; - len -= clen; - if (current == SPH_BLEN) { - RFUN(sc->buf, SPH_VAL); - current = 0; - } + clen = SPH_BLEN - current; + if (clen > len) + clen = (unsigned)len; + memcpy(sc->buf + current, data, clen); + data = (const unsigned char *)data + clen; + current += clen; + len -= clen; + if (current == SPH_BLEN) { + RFUN(sc->buf, SPH_VAL); + current = 0; + } #if SPH_64 - sc->count += clen; + sc->count += clen; #else - clow = sc->count_low; - clow2 = SPH_T32(clow + clen); - sc->count_low = clow2; - if (clow2 < clow) - sc->count_high ++; + clow = sc->count_low; + clow2 = SPH_T32(clow + clen); + sc->count_low = clow2; + if (clow2 < clow) + sc->count_high ++; #endif - } + } } #ifdef SPH_UPTR void SPH_XCAT(sph_, HASH)(void *cc, const void *data, size_t len) { - SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; - unsigned current; - size_t orig_len; + SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; + unsigned current; + size_t orig_len; #if !SPH_64 - sph_u32 clow, clow2; + sph_u32 clow, clow2; #endif - if (len < (2 * SPH_BLEN)) { - SPH_XCAT(HASH, _short)(cc, data, len); - return; - } - sc = cc; + if (len < (2 * SPH_BLEN)) { + SPH_XCAT(HASH, _short)(cc, data, len); + return; + } + sc = cc; #if SPH_64 - current = (unsigned)sc->count & (SPH_BLEN - 1U); + current = (unsigned)sc->count & (SPH_BLEN - 1U); #else - current = (unsigned)sc->count_low & (SPH_BLEN - 1U); + current = (unsigned)sc->count_low & (SPH_BLEN - 1U); #endif - if (current > 0) { - unsigned t; + if (current > 0) { + unsigned t; - t = SPH_BLEN - current; - SPH_XCAT(HASH, _short)(cc, data, t); - data = (const unsigned char *)data + t; - len -= t; - } + t = SPH_BLEN - current; + SPH_XCAT(HASH, _short)(cc, data, t); + data = (const unsigned char *)data + t; + len -= t; + } #if !SPH_UNALIGNED - if (((SPH_UPTR)data & (SPH_WLEN - 1U)) != 0) { - SPH_XCAT(HASH, _short)(cc, data, len); - return; - } + if (((SPH_UPTR)data & (SPH_WLEN - 1U)) != 0) { + SPH_XCAT(HASH, _short)(cc, data, len); + return; + } #endif - orig_len = len; - while (len >= SPH_BLEN) { - RFUN(data, SPH_VAL); - len -= SPH_BLEN; - data = (const unsigned char *)data + SPH_BLEN; - } - if (len > 0) - memcpy(sc->buf, data, len); + orig_len = len; + while (len >= SPH_BLEN) { + RFUN(data, SPH_VAL); + len -= SPH_BLEN; + data = (const unsigned char *)data + SPH_BLEN; + } + if (len > 0) + memcpy(sc->buf, data, len); #if SPH_64 - sc->count += (sph_u64)orig_len; + sc->count += (sph_u64)orig_len; #else - clow = sc->count_low; - clow2 = SPH_T32(clow + orig_len); - sc->count_low = clow2; - if (clow2 < clow) - sc->count_high ++; - /* - * This code handles the improbable situation where "size_t" is - * greater than 32 bits, and yet we do not have a 64-bit type. - */ - orig_len >>= 12; - orig_len >>= 10; - orig_len >>= 10; - sc->count_high += orig_len; + clow = sc->count_low; + clow2 = SPH_T32(clow + orig_len); + sc->count_low = clow2; + if (clow2 < clow) + sc->count_high ++; + /* + * This code handles the improbable situation where "size_t" is + * greater than 32 bits, and yet we do not have a 64-bit type. + */ + orig_len >>= 12; + orig_len >>= 10; + orig_len >>= 10; + sc->count_high += orig_len; #endif } #endif @@ -237,110 +237,110 @@ SPH_XCAT(sph_, HASH)(void *cc, const void *data, size_t len) */ static void SPH_XCAT(HASH, _addbits_and_close)(void *cc, - unsigned ub, unsigned n, void *dst, unsigned rnum) + unsigned ub, unsigned n, void *dst, unsigned rnum) { - SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; - unsigned current, u; + SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; + unsigned current, u; #if !SPH_64 - sph_u32 low, high; + sph_u32 low, high; #endif - sc = cc; + sc = cc; #if SPH_64 - current = (unsigned)sc->count & (SPH_BLEN - 1U); + current = (unsigned)sc->count & (SPH_BLEN - 1U); #else - current = (unsigned)sc->count_low & (SPH_BLEN - 1U); + current = (unsigned)sc->count_low & (SPH_BLEN - 1U); #endif #ifdef PW01 - sc->buf[current ++] = (0x100 | (ub & 0xFF)) >> (8 - n); + sc->buf[current ++] = (0x100 | (ub & 0xFF)) >> (8 - n); #else - { - unsigned z; + { + unsigned z; - z = 0x80U >> n; - sc->buf[current ++] = ((ub & -z) | z) & 0xFF; - } + z = 0x80U >> n; + sc->buf[current ++] = ((ub & -z) | z) & 0xFF; + } #endif - if (current > SPH_MAXPAD) { - memset(sc->buf + current, 0, SPH_BLEN - current); - RFUN(sc->buf, SPH_VAL); - memset(sc->buf, 0, SPH_MAXPAD); - } else { - memset(sc->buf + current, 0, SPH_MAXPAD - current); - } + if (current > SPH_MAXPAD) { + memset(sc->buf + current, 0, SPH_BLEN - current); + RFUN(sc->buf, SPH_VAL); + memset(sc->buf, 0, SPH_MAXPAD); + } else { + memset(sc->buf + current, 0, SPH_MAXPAD - current); + } #if defined BE64 #if defined PLW1 - sph_enc64be_aligned(sc->buf + SPH_MAXPAD, - SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64be_aligned(sc->buf + SPH_MAXPAD, + SPH_T64(sc->count << 3) + (sph_u64)n); #elif defined PLW4 - memset(sc->buf + SPH_MAXPAD, 0, 2 * SPH_WLEN); - sph_enc64be_aligned(sc->buf + SPH_MAXPAD + 2 * SPH_WLEN, - sc->count >> 61); - sph_enc64be_aligned(sc->buf + SPH_MAXPAD + 3 * SPH_WLEN, - SPH_T64(sc->count << 3) + (sph_u64)n); + memset(sc->buf + SPH_MAXPAD, 0, 2 * SPH_WLEN); + sph_enc64be_aligned(sc->buf + SPH_MAXPAD + 2 * SPH_WLEN, + sc->count >> 61); + sph_enc64be_aligned(sc->buf + SPH_MAXPAD + 3 * SPH_WLEN, + SPH_T64(sc->count << 3) + (sph_u64)n); #else - sph_enc64be_aligned(sc->buf + SPH_MAXPAD, sc->count >> 61); - sph_enc64be_aligned(sc->buf + SPH_MAXPAD + SPH_WLEN, - SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64be_aligned(sc->buf + SPH_MAXPAD, sc->count >> 61); + sph_enc64be_aligned(sc->buf + SPH_MAXPAD + SPH_WLEN, + SPH_T64(sc->count << 3) + (sph_u64)n); #endif #elif defined LE64 #if defined PLW1 - sph_enc64le_aligned(sc->buf + SPH_MAXPAD, - SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64le_aligned(sc->buf + SPH_MAXPAD, + SPH_T64(sc->count << 3) + (sph_u64)n); #elif defined PLW1 - sph_enc64le_aligned(sc->buf + SPH_MAXPAD, - SPH_T64(sc->count << 3) + (sph_u64)n); - sph_enc64le_aligned(sc->buf + SPH_MAXPAD + SPH_WLEN, sc->count >> 61); - memset(sc->buf + SPH_MAXPAD + 2 * SPH_WLEN, 0, 2 * SPH_WLEN); + sph_enc64le_aligned(sc->buf + SPH_MAXPAD, + SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64le_aligned(sc->buf + SPH_MAXPAD + SPH_WLEN, sc->count >> 61); + memset(sc->buf + SPH_MAXPAD + 2 * SPH_WLEN, 0, 2 * SPH_WLEN); #else - sph_enc64le_aligned(sc->buf + SPH_MAXPAD, - SPH_T64(sc->count << 3) + (sph_u64)n); - sph_enc64le_aligned(sc->buf + SPH_MAXPAD + SPH_WLEN, sc->count >> 61); + sph_enc64le_aligned(sc->buf + SPH_MAXPAD, + SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64le_aligned(sc->buf + SPH_MAXPAD + SPH_WLEN, sc->count >> 61); #endif #else #if SPH_64 #ifdef BE32 - sph_enc64be_aligned(sc->buf + SPH_MAXPAD, - SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64be_aligned(sc->buf + SPH_MAXPAD, + SPH_T64(sc->count << 3) + (sph_u64)n); #else - sph_enc64le_aligned(sc->buf + SPH_MAXPAD, - SPH_T64(sc->count << 3) + (sph_u64)n); + sph_enc64le_aligned(sc->buf + SPH_MAXPAD, + SPH_T64(sc->count << 3) + (sph_u64)n); #endif #else - low = sc->count_low; - high = SPH_T32((sc->count_high << 3) | (low >> 29)); - low = SPH_T32(low << 3) + (sph_u32)n; + low = sc->count_low; + high = SPH_T32((sc->count_high << 3) | (low >> 29)); + low = SPH_T32(low << 3) + (sph_u32)n; #ifdef BE32 - sph_enc32be(sc->buf + SPH_MAXPAD, high); - sph_enc32be(sc->buf + SPH_MAXPAD + SPH_WLEN, low); + sph_enc32be(sc->buf + SPH_MAXPAD, high); + sph_enc32be(sc->buf + SPH_MAXPAD + SPH_WLEN, low); #else - sph_enc32le(sc->buf + SPH_MAXPAD, low); - sph_enc32le(sc->buf + SPH_MAXPAD + SPH_WLEN, high); + sph_enc32le(sc->buf + SPH_MAXPAD, low); + sph_enc32le(sc->buf + SPH_MAXPAD + SPH_WLEN, high); #endif #endif #endif - RFUN(sc->buf, SPH_VAL); + RFUN(sc->buf, SPH_VAL); #ifdef SPH_NO_OUTPUT - (void)dst; - (void)rnum; - (void)u; + (void)dst; + (void)rnum; + (void)u; #else - for (u = 0; u < rnum; u ++) { + for (u = 0; u < rnum; u ++) { #if defined BE64 - sph_enc64be((unsigned char *)dst + 8 * u, sc->val[u]); + sph_enc64be((unsigned char *)dst + 8 * u, sc->val[u]); #elif defined LE64 - sph_enc64le((unsigned char *)dst + 8 * u, sc->val[u]); + sph_enc64le((unsigned char *)dst + 8 * u, sc->val[u]); #elif defined BE32 - sph_enc32be((unsigned char *)dst + 4 * u, sc->val[u]); + sph_enc32be((unsigned char *)dst + 4 * u, sc->val[u]); #else - sph_enc32le((unsigned char *)dst + 4 * u, sc->val[u]); + sph_enc32le((unsigned char *)dst + 4 * u, sc->val[u]); #endif - } + } #endif } static void SPH_XCAT(HASH, _close)(void *cc, void *dst, unsigned rnum) { - SPH_XCAT(HASH, _addbits_and_close)(cc, 0, 0, dst, rnum); + SPH_XCAT(HASH, _addbits_and_close)(cc, 0, 0, dst, rnum); } diff --git a/libqpdf/sph/sph_sha2.h b/libqpdf/sph/sph_sha2.h index dde62088..dbab2947 100644 --- a/libqpdf/sph/sph_sha2.h +++ b/libqpdf/sph/sph_sha2.h @@ -69,12 +69,12 @@ extern "C" { */ typedef struct { #ifndef DOXYGEN_IGNORE - unsigned char buf[64]; /* first field, for alignment */ - sph_u32 val[8]; + unsigned char buf[64]; /* first field, for alignment */ + sph_u32 val[8]; #if SPH_64 - sph_u64 count; + sph_u64 count; #else - sph_u32 count_high, count_low; + sph_u32 count_high, count_low; #endif #endif } sph_sha224_context; @@ -233,9 +233,9 @@ void sph_sha256_comp(const sph_u32 msg[16], sph_u32 val[8]); */ typedef struct { #ifndef DOXYGEN_IGNORE - unsigned char buf[128]; /* first field, for alignment */ - sph_u64 val[8]; - sph_u64 count; + unsigned char buf[128]; /* first field, for alignment */ + sph_u64 val[8]; + sph_u64 count; #endif } sph_sha384_context; diff --git a/libqpdf/sph/sph_types.h b/libqpdf/sph/sph_types.h index ce2a1db1..25beac3e 100644 --- a/libqpdf/sph/sph_types.h +++ b/libqpdf/sph/sph_types.h @@ -1033,7 +1033,7 @@ typedef long long sph_s64; * 64-bit Sparc architecture (implies v9). */ #elif ((defined __sparc__ || defined __sparc) && defined __arch64__) \ - || defined __sparcv9 + || defined __sparcv9 #define SPH_DETECT_BIG_ENDIAN 1 #define SPH_DETECT_UPTR sph_u64 @@ -1046,7 +1046,7 @@ typedef long long sph_s64; * 32-bit Sparc. */ #elif (defined __sparc__ || defined __sparc) \ - && !(defined __sparcv9 || defined __arch64__) + && !(defined __sparcv9 || defined __arch64__) #define SPH_DETECT_BIG_ENDIAN 1 #define SPH_DETECT_UPTR sph_u32 @@ -1080,7 +1080,7 @@ typedef long long sph_s64; * PowerPC. */ #elif defined __powerpc__ || defined __POWERPC__ || defined __ppc__ \ - || defined _ARCH_PPC + || defined _ARCH_PPC /* * Note: we do not declare cross-endian access to be "fast": even if @@ -1106,7 +1106,7 @@ typedef long long sph_s64; * Itanium, 64-bit. */ #elif defined __ia64 || defined __ia64__ \ - || defined __itanium__ || defined _M_IA64 + || defined __itanium__ || defined _M_IA64 #if defined __BIG_ENDIAN__ || defined _BIG_ENDIAN #define SPH_DETECT_BIG_ENDIAN 1 @@ -1192,8 +1192,8 @@ typedef long long sph_s64; static SPH_INLINE sph_u32 sph_bswap32(sph_u32 x) { - __asm__ __volatile__ ("bswapl %0" : "=r" (x) : "0" (x)); - return x; + __asm__ __volatile__ ("bswapl %0" : "=r" (x) : "0" (x)); + return x; } #if SPH_64 @@ -1201,8 +1201,8 @@ sph_bswap32(sph_u32 x) static SPH_INLINE sph_u64 sph_bswap64(sph_u64 x) { - return ((sph_u64)sph_bswap32((sph_u32)x) << 32) - | (sph_u64)sph_bswap32((sph_u32)(x >> 32)); + return ((sph_u64)sph_bswap32((sph_u32)x) << 32) + | (sph_u64)sph_bswap32((sph_u32)(x >> 32)); } #endif @@ -1217,8 +1217,8 @@ sph_bswap64(sph_u64 x) static SPH_INLINE sph_u32 sph_bswap32(sph_u32 x) { - __asm__ __volatile__ ("bswapl %0" : "=r" (x) : "0" (x)); - return x; + __asm__ __volatile__ ("bswapl %0" : "=r" (x) : "0" (x)); + return x; } #if SPH_64 @@ -1226,8 +1226,8 @@ sph_bswap32(sph_u32 x) static SPH_INLINE sph_u64 sph_bswap64(sph_u64 x) { - __asm__ __volatile__ ("bswapq %0" : "=r" (x) : "0" (x)); - return x; + __asm__ __volatile__ ("bswapq %0" : "=r" (x) : "0" (x)); + return x; } #endif @@ -1243,11 +1243,11 @@ sph_bswap64(sph_u64 x) static __inline sph_u32 __declspec(naked) __fastcall sph_bswap32(sph_u32 x) { - __asm { - bswap ecx - mov eax,ecx - ret - } + __asm { + bswap ecx + mov eax,ecx + ret + } } #if SPH_64 @@ -1255,8 +1255,8 @@ sph_bswap32(sph_u32 x) static SPH_INLINE sph_u64 sph_bswap64(sph_u64 x) { - return ((sph_u64)sph_bswap32((sph_u32)x) << 32) - | (sph_u64)sph_bswap32((sph_u32)(x >> 32)); + return ((sph_u64)sph_bswap32((sph_u32)x) << 32) + | (sph_u64)sph_bswap32((sph_u32)(x >> 32)); } #endif @@ -1270,10 +1270,10 @@ sph_bswap64(sph_u64 x) static SPH_INLINE sph_u32 sph_bswap32(sph_u32 x) { - x = SPH_T32((x << 16) | (x >> 16)); - x = ((x & SPH_C32(0xFF00FF00)) >> 8) - | ((x & SPH_C32(0x00FF00FF)) << 8); - return x; + x = SPH_T32((x << 16) | (x >> 16)); + x = ((x & SPH_C32(0xFF00FF00)) >> 8) + | ((x & SPH_C32(0x00FF00FF)) << 8); + return x; } #if SPH_64 @@ -1287,12 +1287,12 @@ sph_bswap32(sph_u32 x) static SPH_INLINE sph_u64 sph_bswap64(sph_u64 x) { - x = SPH_T64((x << 32) | (x >> 32)); - x = ((x & SPH_C64(0xFFFF0000FFFF0000)) >> 16) - | ((x & SPH_C64(0x0000FFFF0000FFFF)) << 16); - x = ((x & SPH_C64(0xFF00FF00FF00FF00)) >> 8) - | ((x & SPH_C64(0x00FF00FF00FF00FF)) << 8); - return x; + x = SPH_T64((x << 32) | (x >> 32)); + x = ((x & SPH_C64(0xFFFF0000FFFF0000)) >> 16) + | ((x & SPH_C64(0x0000FFFF0000FFFF)) << 16); + x = ((x & SPH_C64(0xFF00FF00FF00FF00)) >> 8) + | ((x & SPH_C64(0x00FF00FF00FF00FF)) << 8); + return x; } #endif @@ -1318,48 +1318,48 @@ sph_bswap64(sph_u64 x) */ #define SPH_SPARCV9_SET_ASI \ - sph_u32 sph_sparcv9_asi; \ - __asm__ __volatile__ ( \ - "rd %%asi,%0\n\twr %%g0,0x88,%%asi" : "=r" (sph_sparcv9_asi)); + sph_u32 sph_sparcv9_asi; \ + __asm__ __volatile__ ( \ + "rd %%asi,%0\n\twr %%g0,0x88,%%asi" : "=r" (sph_sparcv9_asi)); #define SPH_SPARCV9_RESET_ASI \ - __asm__ __volatile__ ("wr %%g0,%0,%%asi" : : "r" (sph_sparcv9_asi)); + __asm__ __volatile__ ("wr %%g0,%0,%%asi" : : "r" (sph_sparcv9_asi)); #define SPH_SPARCV9_DEC32LE(base, idx) ({ \ - sph_u32 sph_sparcv9_tmp; \ - __asm__ __volatile__ ("lda [%1+" #idx "*4]%%asi,%0" \ - : "=r" (sph_sparcv9_tmp) : "r" (base)); \ - sph_sparcv9_tmp; \ - }) + sph_u32 sph_sparcv9_tmp; \ + __asm__ __volatile__ ("lda [%1+" #idx "*4]%%asi,%0" \ + : "=r" (sph_sparcv9_tmp) : "r" (base)); \ + sph_sparcv9_tmp; \ + }) #endif static SPH_INLINE void sph_enc16be(void *dst, unsigned val) { - ((unsigned char *)dst)[0] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[1] = (unsigned char)val; + ((unsigned char *)dst)[0] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[1] = (unsigned char)val; } static SPH_INLINE unsigned sph_dec16be(const void *src) { - return ((unsigned)(((const unsigned char *)src)[0]) << 8) - | (unsigned)(((const unsigned char *)src)[1]); + return ((unsigned)(((const unsigned char *)src)[0]) << 8) + | (unsigned)(((const unsigned char *)src)[1]); } static SPH_INLINE void sph_enc16le(void *dst, unsigned val) { - ((unsigned char *)dst)[0] = (unsigned char)val; - ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[0] = (unsigned char)val; + ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); } static SPH_INLINE unsigned sph_dec16le(const void *src) { - return (unsigned)(((const unsigned char *)src)[0]) - | ((unsigned)(((const unsigned char *)src)[1]) << 8); + return (unsigned)(((const unsigned char *)src)[0]) + | ((unsigned)(((const unsigned char *)src)[1]) << 8); } /** @@ -1374,27 +1374,27 @@ sph_enc32be(void *dst, sph_u32 val) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_LITTLE_ENDIAN - val = sph_bswap32(val); + val = sph_bswap32(val); #endif - *(sph_u32 *)dst = val; + *(sph_u32 *)dst = val; #else - if (((SPH_UPTR)dst & 3) == 0) { + if (((SPH_UPTR)dst & 3) == 0) { #if SPH_LITTLE_ENDIAN - val = sph_bswap32(val); + val = sph_bswap32(val); #endif - *(sph_u32 *)dst = val; - } else { - ((unsigned char *)dst)[0] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[3] = (unsigned char)(val); - } + *(sph_u32 *)dst = val; + } else { + ((unsigned char *)dst)[0] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[3] = (unsigned char)(val); + } #endif #else - ((unsigned char *)dst)[0] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[3] = (unsigned char)(val); + ((unsigned char *)dst)[0] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[3] = (unsigned char)(val); #endif } @@ -1409,14 +1409,14 @@ static SPH_INLINE void sph_enc32be_aligned(void *dst, sph_u32 val) { #if SPH_LITTLE_ENDIAN - *(sph_u32 *)dst = sph_bswap32(val); + *(sph_u32 *)dst = sph_bswap32(val); #elif SPH_BIG_ENDIAN - *(sph_u32 *)dst = val; + *(sph_u32 *)dst = val; #else - ((unsigned char *)dst)[0] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[3] = (unsigned char)(val); + ((unsigned char *)dst)[0] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[3] = (unsigned char)(val); #endif } @@ -1432,29 +1432,29 @@ sph_dec32be(const void *src) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_LITTLE_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); + return sph_bswap32(*(const sph_u32 *)src); #else - return *(const sph_u32 *)src; + return *(const sph_u32 *)src; #endif #else - if (((SPH_UPTR)src & 3) == 0) { + if (((SPH_UPTR)src & 3) == 0) { #if SPH_LITTLE_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); + return sph_bswap32(*(const sph_u32 *)src); #else - return *(const sph_u32 *)src; + return *(const sph_u32 *)src; #endif - } else { - return ((sph_u32)(((const unsigned char *)src)[0]) << 24) - | ((sph_u32)(((const unsigned char *)src)[1]) << 16) - | ((sph_u32)(((const unsigned char *)src)[2]) << 8) - | (sph_u32)(((const unsigned char *)src)[3]); - } + } else { + return ((sph_u32)(((const unsigned char *)src)[0]) << 24) + | ((sph_u32)(((const unsigned char *)src)[1]) << 16) + | ((sph_u32)(((const unsigned char *)src)[2]) << 8) + | (sph_u32)(((const unsigned char *)src)[3]); + } #endif #else - return ((sph_u32)(((const unsigned char *)src)[0]) << 24) - | ((sph_u32)(((const unsigned char *)src)[1]) << 16) - | ((sph_u32)(((const unsigned char *)src)[2]) << 8) - | (sph_u32)(((const unsigned char *)src)[3]); + return ((sph_u32)(((const unsigned char *)src)[0]) << 24) + | ((sph_u32)(((const unsigned char *)src)[1]) << 16) + | ((sph_u32)(((const unsigned char *)src)[2]) << 8) + | (sph_u32)(((const unsigned char *)src)[3]); #endif } @@ -1469,14 +1469,14 @@ static SPH_INLINE sph_u32 sph_dec32be_aligned(const void *src) { #if SPH_LITTLE_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); + return sph_bswap32(*(const sph_u32 *)src); #elif SPH_BIG_ENDIAN - return *(const sph_u32 *)src; + return *(const sph_u32 *)src; #else - return ((sph_u32)(((const unsigned char *)src)[0]) << 24) - | ((sph_u32)(((const unsigned char *)src)[1]) << 16) - | ((sph_u32)(((const unsigned char *)src)[2]) << 8) - | (sph_u32)(((const unsigned char *)src)[3]); + return ((sph_u32)(((const unsigned char *)src)[0]) << 24) + | ((sph_u32)(((const unsigned char *)src)[1]) << 16) + | ((sph_u32)(((const unsigned char *)src)[2]) << 8) + | (sph_u32)(((const unsigned char *)src)[3]); #endif } @@ -1492,27 +1492,27 @@ sph_enc32le(void *dst, sph_u32 val) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_BIG_ENDIAN - val = sph_bswap32(val); + val = sph_bswap32(val); #endif - *(sph_u32 *)dst = val; + *(sph_u32 *)dst = val; #else - if (((SPH_UPTR)dst & 3) == 0) { + if (((SPH_UPTR)dst & 3) == 0) { #if SPH_BIG_ENDIAN - val = sph_bswap32(val); + val = sph_bswap32(val); #endif - *(sph_u32 *)dst = val; - } else { - ((unsigned char *)dst)[0] = (unsigned char)(val); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); - } + *(sph_u32 *)dst = val; + } else { + ((unsigned char *)dst)[0] = (unsigned char)(val); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); + } #endif #else - ((unsigned char *)dst)[0] = (unsigned char)(val); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[0] = (unsigned char)(val); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); #endif } @@ -1527,14 +1527,14 @@ static SPH_INLINE void sph_enc32le_aligned(void *dst, sph_u32 val) { #if SPH_LITTLE_ENDIAN - *(sph_u32 *)dst = val; + *(sph_u32 *)dst = val; #elif SPH_BIG_ENDIAN - *(sph_u32 *)dst = sph_bswap32(val); + *(sph_u32 *)dst = sph_bswap32(val); #else - ((unsigned char *)dst)[0] = (unsigned char)(val); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[0] = (unsigned char)(val); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); #endif } @@ -1550,25 +1550,25 @@ sph_dec32le(const void *src) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_BIG_ENDIAN - return sph_bswap32(*(const sph_u32 *)src); + return sph_bswap32(*(const sph_u32 *)src); #else - return *(const sph_u32 *)src; + return *(const sph_u32 *)src; #endif #else - if (((SPH_UPTR)src & 3) == 0) { + if (((SPH_UPTR)src & 3) == 0) { #if SPH_BIG_ENDIAN #if SPH_SPARCV9_GCC && !SPH_NO_ASM - sph_u32 tmp; - - /* - * "__volatile__" is needed here because without it, - * gcc-3.4.3 miscompiles the code and performs the - * access before the test on the address, thus triggering - * a bus error... - */ - __asm__ __volatile__ ( - "lda [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; + sph_u32 tmp; + + /* + * "__volatile__" is needed here because without it, + * gcc-3.4.3 miscompiles the code and performs the + * access before the test on the address, thus triggering + * a bus error... + */ + __asm__ __volatile__ ( + "lda [%1]0x88,%0" : "=r" (tmp) : "r" (src)); + return tmp; /* * On PowerPC, this turns out not to be worth the effort: the inline * assembly makes GCC optimizer uncomfortable, which tends to nullify @@ -1582,30 +1582,30 @@ sph_dec32le(const void *src) * functions, the generic code appears to be efficient enough already. * #elif (SPH_PPC32_GCC || SPH_PPC64_GCC) && !SPH_NO_ASM - sph_u32 tmp; + sph_u32 tmp; - __asm__ __volatile__ ( - "lwbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ( + "lwbrx %0,0,%1" : "=r" (tmp) : "r" (src)); + return tmp; */ #else - return sph_bswap32(*(const sph_u32 *)src); + return sph_bswap32(*(const sph_u32 *)src); #endif #else - return *(const sph_u32 *)src; + return *(const sph_u32 *)src; #endif - } else { - return (sph_u32)(((const unsigned char *)src)[0]) - | ((sph_u32)(((const unsigned char *)src)[1]) << 8) - | ((sph_u32)(((const unsigned char *)src)[2]) << 16) - | ((sph_u32)(((const unsigned char *)src)[3]) << 24); - } + } else { + return (sph_u32)(((const unsigned char *)src)[0]) + | ((sph_u32)(((const unsigned char *)src)[1]) << 8) + | ((sph_u32)(((const unsigned char *)src)[2]) << 16) + | ((sph_u32)(((const unsigned char *)src)[3]) << 24); + } #endif #else - return (sph_u32)(((const unsigned char *)src)[0]) - | ((sph_u32)(((const unsigned char *)src)[1]) << 8) - | ((sph_u32)(((const unsigned char *)src)[2]) << 16) - | ((sph_u32)(((const unsigned char *)src)[3]) << 24); + return (sph_u32)(((const unsigned char *)src)[0]) + | ((sph_u32)(((const unsigned char *)src)[1]) << 8) + | ((sph_u32)(((const unsigned char *)src)[2]) << 16) + | ((sph_u32)(((const unsigned char *)src)[3]) << 24); #endif } @@ -1620,30 +1620,30 @@ static SPH_INLINE sph_u32 sph_dec32le_aligned(const void *src) { #if SPH_LITTLE_ENDIAN - return *(const sph_u32 *)src; + return *(const sph_u32 *)src; #elif SPH_BIG_ENDIAN #if SPH_SPARCV9_GCC && !SPH_NO_ASM - sph_u32 tmp; + sph_u32 tmp; - __asm__ __volatile__ ("lda [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ("lda [%1]0x88,%0" : "=r" (tmp) : "r" (src)); + return tmp; /* * Not worth it generally. * #elif (SPH_PPC32_GCC || SPH_PPC64_GCC) && !SPH_NO_ASM - sph_u32 tmp; + sph_u32 tmp; - __asm__ __volatile__ ("lwbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ("lwbrx %0,0,%1" : "=r" (tmp) : "r" (src)); + return tmp; */ #else - return sph_bswap32(*(const sph_u32 *)src); + return sph_bswap32(*(const sph_u32 *)src); #endif #else - return (sph_u32)(((const unsigned char *)src)[0]) - | ((sph_u32)(((const unsigned char *)src)[1]) << 8) - | ((sph_u32)(((const unsigned char *)src)[2]) << 16) - | ((sph_u32)(((const unsigned char *)src)[3]) << 24); + return (sph_u32)(((const unsigned char *)src)[0]) + | ((sph_u32)(((const unsigned char *)src)[1]) << 8) + | ((sph_u32)(((const unsigned char *)src)[2]) << 16) + | ((sph_u32)(((const unsigned char *)src)[3]) << 24); #endif } @@ -1661,35 +1661,35 @@ sph_enc64be(void *dst, sph_u64 val) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_LITTLE_ENDIAN - val = sph_bswap64(val); + val = sph_bswap64(val); #endif - *(sph_u64 *)dst = val; + *(sph_u64 *)dst = val; #else - if (((SPH_UPTR)dst & 7) == 0) { + if (((SPH_UPTR)dst & 7) == 0) { #if SPH_LITTLE_ENDIAN - val = sph_bswap64(val); -#endif - *(sph_u64 *)dst = val; - } else { - ((unsigned char *)dst)[0] = (val >> 56); - ((unsigned char *)dst)[1] = (val >> 48); - ((unsigned char *)dst)[2] = (val >> 40); - ((unsigned char *)dst)[3] = (val >> 32); - ((unsigned char *)dst)[4] = (val >> 24); - ((unsigned char *)dst)[5] = (val >> 16); - ((unsigned char *)dst)[6] = (val >> 8); - ((unsigned char *)dst)[7] = val; - } + val = sph_bswap64(val); +#endif + *(sph_u64 *)dst = val; + } else { + ((unsigned char *)dst)[0] = (val >> 56); + ((unsigned char *)dst)[1] = (val >> 48); + ((unsigned char *)dst)[2] = (val >> 40); + ((unsigned char *)dst)[3] = (val >> 32); + ((unsigned char *)dst)[4] = (val >> 24); + ((unsigned char *)dst)[5] = (val >> 16); + ((unsigned char *)dst)[6] = (val >> 8); + ((unsigned char *)dst)[7] = val; + } #endif #else - ((unsigned char *)dst)[0] = (unsigned char)(val >> 56); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 48); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 40); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 32); - ((unsigned char *)dst)[4] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[5] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[6] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[7] = (unsigned char)(val); + ((unsigned char *)dst)[0] = (unsigned char)(val >> 56); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 48); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 40); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 32); + ((unsigned char *)dst)[4] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[5] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[6] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[7] = (unsigned char)(val); #endif } @@ -1704,18 +1704,18 @@ static SPH_INLINE void sph_enc64be_aligned(void *dst, sph_u64 val) { #if SPH_LITTLE_ENDIAN - *(sph_u64 *)dst = sph_bswap64(val); + *(sph_u64 *)dst = sph_bswap64(val); #elif SPH_BIG_ENDIAN - *(sph_u64 *)dst = val; + *(sph_u64 *)dst = val; #else - ((unsigned char *)dst)[0] = (unsigned char)(val >> 56); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 48); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 40); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 32); - ((unsigned char *)dst)[4] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[5] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[6] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[7] = (unsigned char)(val); + ((unsigned char *)dst)[0] = (unsigned char)(val >> 56); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 48); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 40); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 32); + ((unsigned char *)dst)[4] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[5] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[6] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[7] = (unsigned char)(val); #endif } @@ -1731,37 +1731,37 @@ sph_dec64be(const void *src) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_LITTLE_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); + return sph_bswap64(*(const sph_u64 *)src); #else - return *(const sph_u64 *)src; + return *(const sph_u64 *)src; #endif #else - if (((SPH_UPTR)src & 7) == 0) { + if (((SPH_UPTR)src & 7) == 0) { #if SPH_LITTLE_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); + return sph_bswap64(*(const sph_u64 *)src); #else - return *(const sph_u64 *)src; -#endif - } else { - return ((sph_u64)(((const unsigned char *)src)[0]) << 56) - | ((sph_u64)(((const unsigned char *)src)[1]) << 48) - | ((sph_u64)(((const unsigned char *)src)[2]) << 40) - | ((sph_u64)(((const unsigned char *)src)[3]) << 32) - | ((sph_u64)(((const unsigned char *)src)[4]) << 24) - | ((sph_u64)(((const unsigned char *)src)[5]) << 16) - | ((sph_u64)(((const unsigned char *)src)[6]) << 8) - | (sph_u64)(((const unsigned char *)src)[7]); - } + return *(const sph_u64 *)src; +#endif + } else { + return ((sph_u64)(((const unsigned char *)src)[0]) << 56) + | ((sph_u64)(((const unsigned char *)src)[1]) << 48) + | ((sph_u64)(((const unsigned char *)src)[2]) << 40) + | ((sph_u64)(((const unsigned char *)src)[3]) << 32) + | ((sph_u64)(((const unsigned char *)src)[4]) << 24) + | ((sph_u64)(((const unsigned char *)src)[5]) << 16) + | ((sph_u64)(((const unsigned char *)src)[6]) << 8) + | (sph_u64)(((const unsigned char *)src)[7]); + } #endif #else - return ((sph_u64)(((const unsigned char *)src)[0]) << 56) - | ((sph_u64)(((const unsigned char *)src)[1]) << 48) - | ((sph_u64)(((const unsigned char *)src)[2]) << 40) - | ((sph_u64)(((const unsigned char *)src)[3]) << 32) - | ((sph_u64)(((const unsigned char *)src)[4]) << 24) - | ((sph_u64)(((const unsigned char *)src)[5]) << 16) - | ((sph_u64)(((const unsigned char *)src)[6]) << 8) - | (sph_u64)(((const unsigned char *)src)[7]); + return ((sph_u64)(((const unsigned char *)src)[0]) << 56) + | ((sph_u64)(((const unsigned char *)src)[1]) << 48) + | ((sph_u64)(((const unsigned char *)src)[2]) << 40) + | ((sph_u64)(((const unsigned char *)src)[3]) << 32) + | ((sph_u64)(((const unsigned char *)src)[4]) << 24) + | ((sph_u64)(((const unsigned char *)src)[5]) << 16) + | ((sph_u64)(((const unsigned char *)src)[6]) << 8) + | (sph_u64)(((const unsigned char *)src)[7]); #endif } @@ -1776,18 +1776,18 @@ static SPH_INLINE sph_u64 sph_dec64be_aligned(const void *src) { #if SPH_LITTLE_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); + return sph_bswap64(*(const sph_u64 *)src); #elif SPH_BIG_ENDIAN - return *(const sph_u64 *)src; + return *(const sph_u64 *)src; #else - return ((sph_u64)(((const unsigned char *)src)[0]) << 56) - | ((sph_u64)(((const unsigned char *)src)[1]) << 48) - | ((sph_u64)(((const unsigned char *)src)[2]) << 40) - | ((sph_u64)(((const unsigned char *)src)[3]) << 32) - | ((sph_u64)(((const unsigned char *)src)[4]) << 24) - | ((sph_u64)(((const unsigned char *)src)[5]) << 16) - | ((sph_u64)(((const unsigned char *)src)[6]) << 8) - | (sph_u64)(((const unsigned char *)src)[7]); + return ((sph_u64)(((const unsigned char *)src)[0]) << 56) + | ((sph_u64)(((const unsigned char *)src)[1]) << 48) + | ((sph_u64)(((const unsigned char *)src)[2]) << 40) + | ((sph_u64)(((const unsigned char *)src)[3]) << 32) + | ((sph_u64)(((const unsigned char *)src)[4]) << 24) + | ((sph_u64)(((const unsigned char *)src)[5]) << 16) + | ((sph_u64)(((const unsigned char *)src)[6]) << 8) + | (sph_u64)(((const unsigned char *)src)[7]); #endif } @@ -1803,35 +1803,35 @@ sph_enc64le(void *dst, sph_u64 val) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_BIG_ENDIAN - val = sph_bswap64(val); + val = sph_bswap64(val); #endif - *(sph_u64 *)dst = val; + *(sph_u64 *)dst = val; #else - if (((SPH_UPTR)dst & 7) == 0) { + if (((SPH_UPTR)dst & 7) == 0) { #if SPH_BIG_ENDIAN - val = sph_bswap64(val); -#endif - *(sph_u64 *)dst = val; - } else { - ((unsigned char *)dst)[0] = val; - ((unsigned char *)dst)[1] = (val >> 8); - ((unsigned char *)dst)[2] = (val >> 16); - ((unsigned char *)dst)[3] = (val >> 24); - ((unsigned char *)dst)[4] = (val >> 32); - ((unsigned char *)dst)[5] = (val >> 40); - ((unsigned char *)dst)[6] = (val >> 48); - ((unsigned char *)dst)[7] = (val >> 56); - } + val = sph_bswap64(val); +#endif + *(sph_u64 *)dst = val; + } else { + ((unsigned char *)dst)[0] = val; + ((unsigned char *)dst)[1] = (val >> 8); + ((unsigned char *)dst)[2] = (val >> 16); + ((unsigned char *)dst)[3] = (val >> 24); + ((unsigned char *)dst)[4] = (val >> 32); + ((unsigned char *)dst)[5] = (val >> 40); + ((unsigned char *)dst)[6] = (val >> 48); + ((unsigned char *)dst)[7] = (val >> 56); + } #endif #else - ((unsigned char *)dst)[0] = (unsigned char)(val); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[4] = (unsigned char)(val >> 32); - ((unsigned char *)dst)[5] = (unsigned char)(val >> 40); - ((unsigned char *)dst)[6] = (unsigned char)(val >> 48); - ((unsigned char *)dst)[7] = (unsigned char)(val >> 56); + ((unsigned char *)dst)[0] = (unsigned char)(val); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[4] = (unsigned char)(val >> 32); + ((unsigned char *)dst)[5] = (unsigned char)(val >> 40); + ((unsigned char *)dst)[6] = (unsigned char)(val >> 48); + ((unsigned char *)dst)[7] = (unsigned char)(val >> 56); #endif } @@ -1846,18 +1846,18 @@ static SPH_INLINE void sph_enc64le_aligned(void *dst, sph_u64 val) { #if SPH_LITTLE_ENDIAN - *(sph_u64 *)dst = val; + *(sph_u64 *)dst = val; #elif SPH_BIG_ENDIAN - *(sph_u64 *)dst = sph_bswap64(val); + *(sph_u64 *)dst = sph_bswap64(val); #else - ((unsigned char *)dst)[0] = (unsigned char)(val); - ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); - ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); - ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); - ((unsigned char *)dst)[4] = (unsigned char)(val >> 32); - ((unsigned char *)dst)[5] = (unsigned char)(val >> 40); - ((unsigned char *)dst)[6] = (unsigned char)(val >> 48); - ((unsigned char *)dst)[7] = (unsigned char)(val >> 56); + ((unsigned char *)dst)[0] = (unsigned char)(val); + ((unsigned char *)dst)[1] = (unsigned char)(val >> 8); + ((unsigned char *)dst)[2] = (unsigned char)(val >> 16); + ((unsigned char *)dst)[3] = (unsigned char)(val >> 24); + ((unsigned char *)dst)[4] = (unsigned char)(val >> 32); + ((unsigned char *)dst)[5] = (unsigned char)(val >> 40); + ((unsigned char *)dst)[6] = (unsigned char)(val >> 48); + ((unsigned char *)dst)[7] = (unsigned char)(val >> 56); #endif } @@ -1873,59 +1873,59 @@ sph_dec64le(const void *src) #if defined SPH_UPTR #if SPH_UNALIGNED #if SPH_BIG_ENDIAN - return sph_bswap64(*(const sph_u64 *)src); + return sph_bswap64(*(const sph_u64 *)src); #else - return *(const sph_u64 *)src; + return *(const sph_u64 *)src; #endif #else - if (((SPH_UPTR)src & 7) == 0) { + if (((SPH_UPTR)src & 7) == 0) { #if SPH_BIG_ENDIAN #if SPH_SPARCV9_GCC_64 && !SPH_NO_ASM - sph_u64 tmp; + sph_u64 tmp; - __asm__ __volatile__ ( - "ldxa [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ( + "ldxa [%1]0x88,%0" : "=r" (tmp) : "r" (src)); + return tmp; /* * Not worth it generally. * #elif SPH_PPC32_GCC && !SPH_NO_ASM - return (sph_u64)sph_dec32le_aligned(src) - | ((sph_u64)sph_dec32le_aligned( - (const char *)src + 4) << 32); + return (sph_u64)sph_dec32le_aligned(src) + | ((sph_u64)sph_dec32le_aligned( + (const char *)src + 4) << 32); #elif SPH_PPC64_GCC && !SPH_NO_ASM - sph_u64 tmp; + sph_u64 tmp; - __asm__ __volatile__ ( - "ldbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ( + "ldbrx %0,0,%1" : "=r" (tmp) : "r" (src)); + return tmp; */ #else - return sph_bswap64(*(const sph_u64 *)src); + return sph_bswap64(*(const sph_u64 *)src); #endif #else - return *(const sph_u64 *)src; -#endif - } else { - return (sph_u64)(((const unsigned char *)src)[0]) - | ((sph_u64)(((const unsigned char *)src)[1]) << 8) - | ((sph_u64)(((const unsigned char *)src)[2]) << 16) - | ((sph_u64)(((const unsigned char *)src)[3]) << 24) - | ((sph_u64)(((const unsigned char *)src)[4]) << 32) - | ((sph_u64)(((const unsigned char *)src)[5]) << 40) - | ((sph_u64)(((const unsigned char *)src)[6]) << 48) - | ((sph_u64)(((const unsigned char *)src)[7]) << 56); - } + return *(const sph_u64 *)src; +#endif + } else { + return (sph_u64)(((const unsigned char *)src)[0]) + | ((sph_u64)(((const unsigned char *)src)[1]) << 8) + | ((sph_u64)(((const unsigned char *)src)[2]) << 16) + | ((sph_u64)(((const unsigned char *)src)[3]) << 24) + | ((sph_u64)(((const unsigned char *)src)[4]) << 32) + | ((sph_u64)(((const unsigned char *)src)[5]) << 40) + | ((sph_u64)(((const unsigned char *)src)[6]) << 48) + | ((sph_u64)(((const unsigned char *)src)[7]) << 56); + } #endif #else - return (sph_u64)(((const unsigned char *)src)[0]) - | ((sph_u64)(((const unsigned char *)src)[1]) << 8) - | ((sph_u64)(((const unsigned char *)src)[2]) << 16) - | ((sph_u64)(((const unsigned char *)src)[3]) << 24) - | ((sph_u64)(((const unsigned char *)src)[4]) << 32) - | ((sph_u64)(((const unsigned char *)src)[5]) << 40) - | ((sph_u64)(((const unsigned char *)src)[6]) << 48) - | ((sph_u64)(((const unsigned char *)src)[7]) << 56); + return (sph_u64)(((const unsigned char *)src)[0]) + | ((sph_u64)(((const unsigned char *)src)[1]) << 8) + | ((sph_u64)(((const unsigned char *)src)[2]) << 16) + | ((sph_u64)(((const unsigned char *)src)[3]) << 24) + | ((sph_u64)(((const unsigned char *)src)[4]) << 32) + | ((sph_u64)(((const unsigned char *)src)[5]) << 40) + | ((sph_u64)(((const unsigned char *)src)[6]) << 48) + | ((sph_u64)(((const unsigned char *)src)[7]) << 56); #endif } @@ -1940,37 +1940,37 @@ static SPH_INLINE sph_u64 sph_dec64le_aligned(const void *src) { #if SPH_LITTLE_ENDIAN - return *(const sph_u64 *)src; + return *(const sph_u64 *)src; #elif SPH_BIG_ENDIAN #if SPH_SPARCV9_GCC_64 && !SPH_NO_ASM - sph_u64 tmp; + sph_u64 tmp; - __asm__ __volatile__ ("ldxa [%1]0x88,%0" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ("ldxa [%1]0x88,%0" : "=r" (tmp) : "r" (src)); + return tmp; /* * Not worth it generally. * #elif SPH_PPC32_GCC && !SPH_NO_ASM - return (sph_u64)sph_dec32le_aligned(src) - | ((sph_u64)sph_dec32le_aligned((const char *)src + 4) << 32); + return (sph_u64)sph_dec32le_aligned(src) + | ((sph_u64)sph_dec32le_aligned((const char *)src + 4) << 32); #elif SPH_PPC64_GCC && !SPH_NO_ASM - sph_u64 tmp; + sph_u64 tmp; - __asm__ __volatile__ ("ldbrx %0,0,%1" : "=r" (tmp) : "r" (src)); - return tmp; + __asm__ __volatile__ ("ldbrx %0,0,%1" : "=r" (tmp) : "r" (src)); + return tmp; */ #else - return sph_bswap64(*(const sph_u64 *)src); + return sph_bswap64(*(const sph_u64 *)src); #endif #else - return (sph_u64)(((const unsigned char *)src)[0]) - | ((sph_u64)(((const unsigned char *)src)[1]) << 8) - | ((sph_u64)(((const unsigned char *)src)[2]) << 16) - | ((sph_u64)(((const unsigned char *)src)[3]) << 24) - | ((sph_u64)(((const unsigned char *)src)[4]) << 32) - | ((sph_u64)(((const unsigned char *)src)[5]) << 40) - | ((sph_u64)(((const unsigned char *)src)[6]) << 48) - | ((sph_u64)(((const unsigned char *)src)[7]) << 56); + return (sph_u64)(((const unsigned char *)src)[0]) + | ((sph_u64)(((const unsigned char *)src)[1]) << 8) + | ((sph_u64)(((const unsigned char *)src)[2]) << 16) + | ((sph_u64)(((const unsigned char *)src)[3]) << 24) + | ((sph_u64)(((const unsigned char *)src)[4]) << 32) + | ((sph_u64)(((const unsigned char *)src)[5]) << 40) + | ((sph_u64)(((const unsigned char *)src)[6]) << 48) + | ((sph_u64)(((const unsigned char *)src)[7]) << 56); #endif } -- cgit v1.2.3-70-g09d2