diff --git a/Filelist.txt b/Filelist.txt index beec818d..0dd3d2ce 100644 --- a/Filelist.txt +++ b/Filelist.txt @@ -263,6 +263,7 @@ strciphr.h tea.cpp tea.h test.cpp +trap.h tftables.cpp tiger.cpp tiger.h diff --git a/adler32.cpp b/adler32.cpp index 54cf892b..f48e9b73 100644 --- a/adler32.cpp +++ b/adler32.cpp @@ -46,8 +46,8 @@ void Adler32::Update(const byte *input, size_t length) s2 %= BASE; } - assert(s1 < BASE); - assert(s2 < BASE); + CRYPTOPP_ASSERT(s1 < BASE); + CRYPTOPP_ASSERT(s2 < BASE); m_s1 = (word16)s1; m_s2 = (word16)s2; diff --git a/algebra.cpp b/algebra.cpp index d6c204bc..c40e900e 100644 --- a/algebra.cpp +++ b/algebra.cpp @@ -262,7 +262,7 @@ void AbstractGroup::SimultaneousMultiply(T *results, const T &base, const Int for (i=0; iNotNegative()); + CRYPTOPP_ASSERT(expBegin->NotNegative()); exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 0)); exponents[i].FindNextWindow(); buckets[i].resize(((size_t) 1) << (exponents[i].windowSize-1), Identity()); diff --git a/algparam.cpp b/algparam.cpp index 2e93c9db..5ef155fd 100644 --- a/algparam.cpp +++ b/algparam.cpp @@ -22,7 +22,7 @@ bool CombinedNameValuePairs::GetVoidValue(const char *name, const std::type_info void AlgorithmParametersBase::operator=(const AlgorithmParametersBase &rhs) { CRYPTOPP_UNUSED(rhs); - assert(false); + CRYPTOPP_ASSERT(false); } bool AlgorithmParametersBase::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const diff --git a/algparam.h b/algparam.h index 87355acc..92eb384d 100644 --- a/algparam.h +++ b/algparam.h @@ -74,7 +74,7 @@ public: void Assign(const byte *data, size_t size, bool deepCopy) { // This fires, which means: no data with a size, or data with no size. - // assert((data && size) || !(data || size)); + // CRYPTOPP_ASSERT((data && size) || !(data || size)); if (deepCopy) m_block.Assign(data, size); else diff --git a/asn.cpp b/asn.cpp index 13cd50c3..297ff010 100644 --- a/asn.cpp +++ b/asn.cpp @@ -244,7 +244,7 @@ size_t OID::DecodeValue(BufferedTransformation &bt, word32 &v) void OID::DEREncode(BufferedTransformation &bt) const { - assert(m_values.size() >= 2); + CRYPTOPP_ASSERT(m_values.size() >= 2); ByteQueue temp; temp.Put(byte(m_values[0] * 40 + m_values[1])); for (size_t i=2; i State_KeySet) m_state = State_KeySet;} diff --git a/basecode.cpp b/basecode.cpp index e4806466..954d11cb 100644 --- a/basecode.cpp +++ b/basecode.cpp @@ -57,7 +57,7 @@ size_t BaseN_Encoder::Put2(const byte *begin, size_t length, int messageEnd, boo unsigned int b = begin[m_inputPosition++], bitsLeftInSource = 8; while (true) { - assert(m_bitsPerChar-m_bitPos >= 0); + CRYPTOPP_ASSERT(m_bitsPerChar-m_bitPos >= 0); unsigned int bitsLeftInTarget = (unsigned int)(m_bitsPerChar-m_bitPos); m_outBuf[m_bytePos] |= b >> (8-bitsLeftInTarget); if (bitsLeftInSource >= bitsLeftInTarget) @@ -78,13 +78,13 @@ size_t BaseN_Encoder::Put2(const byte *begin, size_t length, int messageEnd, boo } } - assert(m_bytePos <= m_outputBlockSize); + CRYPTOPP_ASSERT(m_bytePos <= m_outputBlockSize); if (m_bytePos == m_outputBlockSize) { int i; for (i=0; i::BLAKE2_Base() : m_state(1), m_block(1), m_digestSize(DI template BLAKE2_Base::BLAKE2_Base(bool treeMode, unsigned int digestSize) : m_state(1), m_block(1), m_digestSize(digestSize), m_treeMode(treeMode) { - assert(digestSize <= DIGESTSIZE); + CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE); UncheckedSetKey(NULL, 0, g_nullNameValuePairs); Restart(); @@ -363,10 +363,10 @@ BLAKE2_Base::BLAKE2_Base(const byte *key, size_t keyLength, const by const byte* personalization, size_t personalizationLength, bool treeMode, unsigned int digestSize) : m_state(1), m_block(1), m_digestSize(digestSize), m_treeMode(treeMode) { - assert(keyLength <= MAX_KEYLENGTH); - assert(digestSize <= DIGESTSIZE); - assert(saltLength <= SALTSIZE); - assert(personalizationLength <= PERSONALIZATIONSIZE); + CRYPTOPP_ASSERT(keyLength <= MAX_KEYLENGTH); + CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE); + CRYPTOPP_ASSERT(saltLength <= SALTSIZE); + CRYPTOPP_ASSERT(personalizationLength <= PERSONALIZATIONSIZE); UncheckedSetKey(key, static_cast(keyLength), MakeParameters(Name::DigestSize(),(int)digestSize)(Name::TreeMode(),treeMode, false) (Name::Salt(), ConstByteArrayParameter(salt, saltLength))(Name::Personalization(), ConstByteArrayParameter(personalization, personalizationLength))); @@ -439,7 +439,7 @@ void BLAKE2_Base::Update(const byte *input, size_t length) // Copy tail bytes if (input && length) { - assert(length <= BLOCKSIZE - state.length); + CRYPTOPP_ASSERT(length <= BLOCKSIZE - state.length); memcpy_s(&state.buffer[state.length], length, input, length); state.length += static_cast(length); } @@ -3470,10 +3470,10 @@ static const int LANE_L64 = 0; static void BLAKE2_NEON_Compress32(const byte* input, BLAKE2_State& state) { - //assert(IsAlignedOn(input,GetAlignmentOf())); - assert(IsAlignedOn(&state.h[0],GetAlignmentOf())); - assert(IsAlignedOn(&state.h[4],GetAlignmentOf())); - assert(IsAlignedOn(&state.t[0],GetAlignmentOf())); + //CRYPTOPP_ASSERT(IsAlignedOn(input,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(&state.h[0],GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(&state.h[4],GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(&state.t[0],GetAlignmentOf())); CRYPTOPP_ALIGN_DATA(16) uint32_t m0[4], m1[4], m2[4], m3[4], m4[4], m5[4], m6[4], m7[4]; CRYPTOPP_ALIGN_DATA(16) uint32_t m8[4], m9[4], m10[4], m11[4], m12[4], m13[4], m14[4], m15[4]; @@ -3976,10 +3976,10 @@ static void BLAKE2_NEON_Compress32(const byte* input, BLAKE2_State& state) { - //assert(IsAlignedOn(input,GetAlignmentOf())); - assert(IsAlignedOn(&state.h[0],GetAlignmentOf())); - assert(IsAlignedOn(&state.h[4],GetAlignmentOf())); - assert(IsAlignedOn(&state.t[0],GetAlignmentOf())); + //CRYPTOPP_ASSERT(IsAlignedOn(input,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(&state.h[0],GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(&state.h[4],GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(&state.t[0],GetAlignmentOf())); uint64x2_t m0m1,m2m3,m4m5,m6m7,m8m9,m10m11,m12m13,m14m15; diff --git a/blake2.h b/blake2.h index 5c1655da..8743996f 100644 --- a/blake2.h +++ b/blake2.h @@ -72,7 +72,7 @@ struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock BLAKE2_ParameterBlock(size_t digestSize) { - assert(digestSize <= DIGESTSIZE); + CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE); memset(this, 0x00, sizeof(*this)); digestLength = (byte)digestSize; fanout = depth = 1; @@ -107,7 +107,7 @@ struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock BLAKE2_ParameterBlock(size_t digestSize) { - assert(digestSize <= DIGESTSIZE); + CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE); memset(this, 0x00, sizeof(*this)); digestLength = (byte)digestSize; fanout = depth = 1; diff --git a/camellia.cpp b/camellia.cpp index 5afe8df5..13880393 100644 --- a/camellia.cpp +++ b/camellia.cpp @@ -91,13 +91,13 @@ void Camellia::Base::UncheckedSetKey(const byte *key, unsigned int keylen, const kwl = (word64(k0) << 32) | k1; \ kwr = (word64(k2) << 32) | k3 #define KS_ROUND_0(i) \ - assert(IsAlignedOn(CALC_ADDR(ks32, i+EFI(0)),GetAlignmentOf())); \ - assert(IsAlignedOn(CALC_ADDR(ks32, i+EFI(1)),GetAlignmentOf())); \ + CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(0)),GetAlignmentOf())); \ + CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(1)),GetAlignmentOf())); \ *(word64*)(void*)CALC_ADDR(ks32, i+EFI(0)) = kwl; \ *(word64*)(void*)CALC_ADDR(ks32, i+EFI(1)) = kwr #define KS_ROUND(i, r, which) \ - assert(IsAlignedOn(CALC_ADDR(ks32, i+EFI(r<64)),GetAlignmentOf())); \ - assert(IsAlignedOn(CALC_ADDR(ks32, i+EFI(r>64)),GetAlignmentOf())); \ + CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(r<64)),GetAlignmentOf())); \ + CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(r>64)),GetAlignmentOf())); \ if (which & (1<> (64 - (r%64))); \ if (which & (1<64))) *(word64*)(void*)CALC_ADDR(ks32, i+EFI(r>64)) = (kwl << (r%64)) | (kwr >> (64 - (r%64))) #else @@ -222,7 +222,7 @@ void Camellia::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBloc volatile word32 _u = 0; word32 u = _u; - assert(IsAlignedOn(s1,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(s1,GetAlignmentOf())); for (i=0; i<256; i+=cacheLineSize) u &= *(const word32 *)(void*)(s1+i); u &= *(const word32 *)(void*)(s1+252); diff --git a/cast.cpp b/cast.cpp index cc62b915..88162c06 100644 --- a/cast.cpp +++ b/cast.cpp @@ -282,7 +282,7 @@ void CAST256::Base::UncheckedSetKey(const byte *userKey, unsigned int keylength, int i1=8*j+i; int i2=8*(11-j)+i; - assert(i1= 2); + CRYPTOPP_ASSERT(m_L >= 2); if (m_L > 8) m_L = 8; @@ -66,7 +66,7 @@ void CCM_Base::UncheckedSpecifyDataLengths(lword headerLength, lword messageLeng if (headerLength>0) { - assert(m_bufferedDataLength == 0); + CRYPTOPP_ASSERT(m_bufferedDataLength == 0); if (headerLength < ((1<<16) - (1<<8))) { diff --git a/chacha.cpp b/chacha.cpp index 833a6acb..58fbda26 100644 --- a/chacha.cpp +++ b/chacha.cpp @@ -31,7 +31,7 @@ template void ChaCha_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length) { CRYPTOPP_UNUSED(params); - assert(length == 16 || length == 32); + CRYPTOPP_ASSERT(length == 16 || length == 32); // "expand 16-byte k" or "expand 32-byte k" m_state[0] = 0x61707865; @@ -50,7 +50,7 @@ template void ChaCha_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length); - assert(length==8); + CRYPTOPP_ASSERT(length==8); GetBlock get(IV); m_state[12] = m_state[13] = 0; diff --git a/cmac.cpp b/cmac.cpp index 95d37ddd..ce8563cf 100644 --- a/cmac.cpp +++ b/cmac.cpp @@ -57,7 +57,7 @@ void CMAC_Base::UncheckedSetKey(const byte *key, unsigned int length, const Name void CMAC_Base::Update(const byte *input, size_t length) { - assert((input && length) || !(input || length)); + CRYPTOPP_ASSERT((input && length) || !(input || length)); if (!length) return; @@ -84,7 +84,7 @@ void CMAC_Base::Update(const byte *input, size_t length) if (length > blockSize) { - assert(m_counter == 0); + CRYPTOPP_ASSERT(m_counter == 0); size_t leftOver = 1 + cipher.AdvancedProcessBlocks(m_reg, input, m_reg, length-1, BlockTransformation::BT_DontIncrementInOutPointers|BlockTransformation::BT_XorInput); input += (length - leftOver); length = leftOver; @@ -92,12 +92,12 @@ void CMAC_Base::Update(const byte *input, size_t length) if (length > 0) { - assert(m_counter + length <= blockSize); + CRYPTOPP_ASSERT(m_counter + length <= blockSize); xorbuf(m_reg+m_counter, input, length); m_counter += (unsigned int)length; } - assert(m_counter > 0); + CRYPTOPP_ASSERT(m_counter > 0); } void CMAC_Base::TruncatedFinal(byte *mac, size_t size) diff --git a/config.h b/config.h index 138626de..b4796095 100644 --- a/config.h +++ b/config.h @@ -138,6 +138,16 @@ # define CRYPTOPP_USER_PRIORITY 250 #endif +// CRYPTOPP_DEBUG enables the library's CRYPTOPP_ASSERT. CRYPTOPP_ASSERT +// raises a SIGTRAP (Unix) or calls DebugBreak() (Windows). CRYPTOPP_ASSERT +// is only in effect when CRYPTOPP_DEBUG, DEBUG or _DEBUG is defined. Unlike +// Posix assert, CRYPTOPP_ASSERT is not affected by NDEBUG (or failure to +// define it). +// Also see http://github.com/weidai11/cryptopp/issues/277, CVE-2010-4179 +#if (defined(DEBUG) || defined(_DEBUG)) && !defined(CRYPTOPP_DEBUG) +# define CRYPTOPP_DEBUG 1 +#endif + // ***************** Important Settings Again ******************** // But the defaults should be ok. diff --git a/config.recommend b/config.recommend index 629fb96c..d1840d42 100644 --- a/config.recommend +++ b/config.recommend @@ -138,6 +138,16 @@ # define CRYPTOPP_USER_PRIORITY 250 #endif +// CRYPTOPP_DEBUG enables the library's CRYPTOPP_ASSERT. CRYPTOPP_ASSERT +// raises a SIGTRAP (Unix) or calls DebugBreak() (Windows). CRYPTOPP_ASSERT +// is only in effect when CRYPTOPP_DEBUG, DEBUG or _DEBUG is defined. Unlike +// Posix assert, CRYPTOPP_ASSERT is not affected by NDEBUG (or failure to +// define it). +// Also see http://github.com/weidai11/cryptopp/issues/277, CVE-2010-4179 +#if (defined(DEBUG) || defined(_DEBUG)) && !defined(CRYPTOPP_DEBUG) +# define CRYPTOPP_DEBUG 1 +#endif + // ***************** Important Settings Again ******************** // But the defaults should be ok. diff --git a/cryptdll.vcxproj b/cryptdll.vcxproj index e082d29a..579b2777 100644 --- a/cryptdll.vcxproj +++ b/cryptdll.vcxproj @@ -895,6 +895,7 @@ IF %ERRORLEVEL% EQU 0 (echo mac done > "$(OutDir)"\cryptopp.mac.done) + diff --git a/cryptdll.vcxproj.filters b/cryptdll.vcxproj.filters index 10b6050b..7161f5f0 100644 --- a/cryptdll.vcxproj.filters +++ b/cryptdll.vcxproj.filters @@ -370,6 +370,9 @@ Header Files + + Header Files + Header Files diff --git a/cryptlib.cpp b/cryptlib.cpp index d2ecc01b..c1f6f63e 100644 --- a/cryptlib.cpp +++ b/cryptlib.cpp @@ -181,9 +181,9 @@ void SimpleKeyingInterface::GetNextIV(RandomNumberGenerator &rng, byte *IV) size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const { - assert(inBlocks); - assert(outBlocks); - assert(length); + CRYPTOPP_ASSERT(inBlocks); + CRYPTOPP_ASSERT(outBlocks); + CRYPTOPP_ASSERT(length); size_t blockSize = BlockSize(); size_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize; @@ -192,7 +192,7 @@ size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const by if (flags & BT_ReverseDirection) { - assert(length % blockSize == 0); + CRYPTOPP_ASSERT(length % blockSize == 0); inBlocks += length - blockSize; xorBlocks += length - blockSize; outBlocks += length - blockSize; @@ -206,7 +206,7 @@ size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const by if (flags & BT_XorInput) { // Coverity finding. However, xorBlocks is never NULL if BT_XorInput. - assert(xorBlocks); + CRYPTOPP_ASSERT(xorBlocks); #if defined(__COVERITY__) if (xorBlocks) #endif @@ -247,7 +247,7 @@ unsigned int HashTransformation::OptimalDataAlignment() const void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, size_t length) { - assert(MinLastBlockSize() == 0); // this function should be overriden otherwise + CRYPTOPP_ASSERT(MinLastBlockSize() == 0); // this function should be overriden otherwise if (length == MandatoryBlockSize()) ProcessData(outString, inString, length); @@ -320,7 +320,7 @@ word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max) // see https://github.com/weidai11/cryptopp/issues/38. // // According to Wei, RandomNumberGenerator is an interface, and it should not -// be instantiable. Its now spilt milk, and we are going to assert it in Debug +// be instantiable. Its now spilt milk, and we are going to CRYPTOPP_ASSERT it in Debug // builds to alert the programmer and throw in Release builds. Developers have // a reference implementation in case its needed. If a programmer // unintentionally lands here, then they should ensure use of a @@ -353,7 +353,7 @@ void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransform size_t len = UnsignedMin(buffer.size(), length); GenerateBlock(buffer, len); size_t rem = target.ChannelPut(channel, buffer, len); - CRYPTOPP_UNUSED(rem); assert(rem == 0); + CRYPTOPP_UNUSED(rem); CRYPTOPP_ASSERT(rem == 0); length -= len; } } @@ -439,21 +439,21 @@ void BufferedTransformation::GetWaitObjects(WaitObjectContainer &container, Call void BufferedTransformation::Initialize(const NameValuePairs ¶meters, int propagation) { CRYPTOPP_UNUSED(propagation); - assert(!AttachedTransformation()); + CRYPTOPP_ASSERT(!AttachedTransformation()); IsolatedInitialize(parameters); } bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking) { CRYPTOPP_UNUSED(propagation); - assert(!AttachedTransformation()); + CRYPTOPP_ASSERT(!AttachedTransformation()); return IsolatedFlush(hardFlush, blocking); } bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking) { CRYPTOPP_UNUSED(propagation); - assert(!AttachedTransformation()); + CRYPTOPP_ASSERT(!AttachedTransformation()); return IsolatedMessageSeriesEnd(blocking); } @@ -592,7 +592,7 @@ bool BufferedTransformation::GetNextMessage() return AttachedTransformation()->GetNextMessage(); else { - assert(!AnyMessages()); + CRYPTOPP_ASSERT(!AnyMessages()); return false; } } @@ -629,7 +629,7 @@ size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &targe return 1; bool result = GetNextMessage(); - CRYPTOPP_UNUSED(result); assert(result); + CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result); } return 0; } @@ -660,7 +660,7 @@ size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, co return AttachedTransformation()->TransferAllTo2(target, channel, blocking); else { - assert(!NumberOfMessageSeries()); + CRYPTOPP_ASSERT(!NumberOfMessageSeries()); unsigned int messageCount; do @@ -692,7 +692,7 @@ void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std AttachedTransformation()->CopyAllTo(target, channel); else { - assert(!NumberOfMessageSeries()); + CRYPTOPP_ASSERT(!NumberOfMessageSeries()); while (CopyMessagesTo(target, UINT_MAX, channel)) {} } } diff --git a/cryptlib.h b/cryptlib.h index 9e388e05..c1619e65 100644 --- a/cryptlib.h +++ b/cryptlib.h @@ -85,6 +85,11 @@ and getting us started on the manual. #include "config.h" #include "stdcpp.h" +#include "trap.h" + +#if defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE) +# include +#endif #if CRYPTOPP_MSC_VERSION # pragma warning(push) @@ -715,7 +720,7 @@ protected: //! \brief Validates the key length //! \param length the size of the keying material, in bytes inline void AssertValidKeyLength(size_t length) const - {CRYPTOPP_UNUSED(length); assert(IsValidKeyLength(length));} + {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));} }; //! \brief Interface for the data processing part of block ciphers @@ -895,11 +900,11 @@ public: //! \param pos position to seek //! \throws NotImplemented //! \details The base class implementation throws NotImplemented. The function - //! asserts IsRandomAccess() in debug builds. + //! \ref CRYPTOPP_ASSERT "asserts" IsRandomAccess() in debug builds. virtual void Seek(lword pos) { CRYPTOPP_UNUSED(pos); - assert(!IsRandomAccess()); + CRYPTOPP_ASSERT(!IsRandomAccess()); throw NotImplemented("StreamTransformation: this object doesn't support random access"); } @@ -2001,7 +2006,7 @@ public: //! \return the attached transformation //! \details AttachedTransformation() returns NULL if there is no attachment. The non-const //! version of AttachedTransformation() always returns NULL. - virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;} + virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return 0;} //! \brief Returns the object immediately attached to this object //! \return the attached transformation @@ -2017,7 +2022,7 @@ public: //! \details If a derived class does not override Detach, then the base class throws //! NotImplemented. virtual void Detach(BufferedTransformation *newAttachment = 0) { - CRYPTOPP_UNUSED(newAttachment); assert(!Attachable()); + CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable()); throw NotImplemented("BufferedTransformation: this object is not attachable"); } @@ -2128,7 +2133,7 @@ public: //! NotImplemented. //! \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation() virtual void Precompute(unsigned int precomputationStorage) { - CRYPTOPP_UNUSED(precomputationStorage); assert(!SupportsPrecomputation()); + CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation"); } @@ -2137,13 +2142,13 @@ public: //! \throws NotImplemented //! \sa SupportsPrecomputation(), Precompute() virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation) - {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} + {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} //! \brief Save precomputation for later use //! \param storedPrecomputation BufferedTransformation to write the precomputation //! \throws NotImplemented //! \sa SupportsPrecomputation(), Precompute() virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const - {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} + {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} //! \brief Perform a quick sanity check //! \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users. diff --git a/cryptlib.vcxproj b/cryptlib.vcxproj index 5fbf8d4e..ae355894 100644 --- a/cryptlib.vcxproj +++ b/cryptlib.vcxproj @@ -2391,6 +2391,7 @@ echo: >> adhoc.cpp.copied + diff --git a/cryptlib.vcxproj.filters b/cryptlib.vcxproj.filters index 13e713e7..bbfb85ca 100644 --- a/cryptlib.vcxproj.filters +++ b/cryptlib.vcxproj.filters @@ -768,6 +768,9 @@ Header Files + + Header Files + Header Files diff --git a/datatest.cpp b/datatest.cpp index 315b93da..7a2e64c9 100644 --- a/datatest.cpp +++ b/datatest.cpp @@ -300,12 +300,12 @@ void TestSignatureScheme(TestData &v) else if (test == "RandomSign") { SignalTestError(); - assert(false); // TODO: implement + CRYPTOPP_ASSERT(false); // TODO: implement } else { SignalTestError(); - assert(false); + CRYPTOPP_ASSERT(false); } } @@ -345,7 +345,7 @@ void TestAsymmetricCipher(TestData &v) else { SignalTestError(); - assert(false); + CRYPTOPP_ASSERT(false); } } @@ -443,7 +443,7 @@ void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters) while (ss.Pump(64)) {} ss.PumpAll(); for (int i=0; i::max(), '\n'); + file.ignore((std::numeric_limits::max)(), '\n'); if (file.peek() == '\n' || file.peek() == '\r') v.clear(); diff --git a/dlltest.cpp b/dlltest.cpp index 01906207..559084ba 100644 --- a/dlltest.cpp +++ b/dlltest.cpp @@ -133,7 +133,7 @@ void FIPS140_SampleApplication() // sign and verify byte signature[40]; DSA::Signer signer(dsaPrivateKey); - assert(signer.SignatureLength() == 40); + CRYPTOPP_ASSERT(signer.SignatureLength() == 40); signer.SignMessage(rng, message, 3, signature); DSA::Verifier verifier(dsaPublicKey); diff --git a/eax.cpp b/eax.cpp index cf836632..437b502f 100644 --- a/eax.cpp +++ b/eax.cpp @@ -34,7 +34,7 @@ size_t EAX_Base::AuthenticateBlocks(const byte *data, size_t len) void EAX_Base::AuthenticateLastHeaderBlock() { - assert(m_bufferedDataLength == 0); + CRYPTOPP_ASSERT(m_bufferedDataLength == 0); MessageAuthenticationCode &mac = AccessMAC(); unsigned int blockSize = mac.TagSize(); @@ -48,7 +48,7 @@ void EAX_Base::AuthenticateLastHeaderBlock() void EAX_Base::AuthenticateLastFooterBlock(byte *tag, size_t macSize) { - assert(m_bufferedDataLength == 0); + CRYPTOPP_ASSERT(m_bufferedDataLength == 0); MessageAuthenticationCode &mac = AccessMAC(); unsigned int blockSize = mac.TagSize(); diff --git a/ec2n.cpp b/ec2n.cpp index e00b53e7..33a9d454 100644 --- a/ec2n.cpp +++ b/ec2n.cpp @@ -71,11 +71,11 @@ bool EC2N::DecodePoint(EC2N::Point &P, BufferedTransformation &bt, size_t encode } FieldElement z = m_field->Square(P.x); - assert(P.x == m_field->SquareRoot(z)); + CRYPTOPP_ASSERT(P.x == m_field->SquareRoot(z)); P.y = m_field->Divide(m_field->Add(m_field->Multiply(z, m_field->Add(P.x, m_a)), m_b), z); - assert(P.x == m_field->Subtract(m_field->Divide(m_field->Subtract(m_field->Multiply(P.y, z), m_b), z), m_a)); + CRYPTOPP_ASSERT(P.x == m_field->Subtract(m_field->Divide(m_field->Subtract(m_field->Multiply(P.y, z), m_b), z), m_a)); z = m_field->SolveQuadraticEquation(P.y); - assert(m_field->Add(m_field->Square(z), z) == P.y); + CRYPTOPP_ASSERT(m_field->Add(m_field->Square(z), z) == P.y); z.SetCoefficient(0, type & 1); P.y = m_field->Multiply(z, P.x); @@ -119,7 +119,7 @@ void EC2N::EncodePoint(byte *encodedPoint, const Point &P, bool compressed) cons { ArraySink sink(encodedPoint, EncodedPointSize(compressed)); EncodePoint(sink, P, compressed); - assert(sink.TotalPutLength() == EncodedPointSize(compressed)); + CRYPTOPP_ASSERT(sink.TotalPutLength() == EncodedPointSize(compressed)); } EC2N::Point EC2N::BERDecodePoint(BufferedTransformation &bt) const diff --git a/eccrypto.cpp b/eccrypto.cpp index 6112e272..dd58bf4d 100644 --- a/eccrypto.cpp +++ b/eccrypto.cpp @@ -457,7 +457,7 @@ template void DL_GroupParameters_EC::Initialize(const OID &oid) this->SetSubgroupGenerator(G); // TODO: this fails in practice. Should it throw? - CRYPTOPP_UNUSED(result); assert(result); + CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result); StringSource ssN(param.n, true, new HexDecoder); m_n.Decode(ssN, (size_t)ssN.MaxRetrievable()); diff --git a/ecp.cpp b/ecp.cpp index c718a527..eae99eb1 100644 --- a/ecp.cpp +++ b/ecp.cpp @@ -140,7 +140,7 @@ void ECP::EncodePoint(byte *encodedPoint, const Point &P, bool compressed) const { ArraySink sink(encodedPoint, EncodedPointSize(compressed)); EncodePoint(sink, P, compressed); - assert(sink.TotalPutLength() == EncodedPointSize(compressed)); + CRYPTOPP_ASSERT(sink.TotalPutLength() == EncodedPointSize(compressed)); } ECP::Point ECP::BERDecodePoint(BufferedTransformation &bt) const @@ -384,7 +384,7 @@ void ECP::SimultaneousMultiply(ECP::Point *results, const ECP::Point &P, const I for (i=0; iNotNegative()); + CRYPTOPP_ASSERT(expBegin->NotNegative()); exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 5)); exponents[i].FindNextWindow(); } diff --git a/emsa2.cpp b/emsa2.cpp index 7da90516..fb387d2f 100644 --- a/emsa2.cpp +++ b/emsa2.cpp @@ -13,7 +13,7 @@ void EMSA2Pad::ComputeMessageRepresentative(RandomNumberGenerator& /*rng*/, byte *representative, size_t representativeBitLength) const { CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength), CRYPTOPP_UNUSED(representativeBitLength); - assert(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); + CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); if (representativeBitLength % 8 != 7) throw PK_SignatureScheme::InvalidKeyLength("EMSA2: EMSA2 requires a key length that is a multiple of 8"); diff --git a/eprecomp.cpp b/eprecomp.cpp index 78c8f4cf..3a021b66 100644 --- a/eprecomp.cpp +++ b/eprecomp.cpp @@ -27,8 +27,8 @@ template void DL_FixedBasePrecomputationImpl::SetBase(const DL_Grou template void DL_FixedBasePrecomputationImpl::Precompute(const DL_GroupPrecomputation &group, unsigned int maxExpBits, unsigned int storage) { - assert(m_bases.size() > 0); - assert(storage <= maxExpBits); + CRYPTOPP_ASSERT(m_bases.size() > 0); + CRYPTOPP_ASSERT(storage <= maxExpBits); if (storage > 1) { diff --git a/esign.cpp b/esign.cpp index 4d79ad59..7fef8082 100644 --- a/esign.cpp +++ b/esign.cpp @@ -125,7 +125,7 @@ void InvertibleESIGNFunction::GenerateRandom(RandomNumberGenerator &rng, const N m_n = m_p * m_p * m_q; - assert(m_n.BitCount() == (unsigned int)modulusSize); + CRYPTOPP_ASSERT(m_n.BitCount() == (unsigned int)modulusSize); } void InvertibleESIGNFunction::BERDecode(BufferedTransformation &bt) @@ -174,7 +174,7 @@ Integer InvertibleESIGNFunction::CalculateRandomizedInverse(RandomNumberGenerato ModularArithmetic modp(m_p); Integer t = modp.Divide(w0 * r % m_p, m_e * re % m_p); Integer s = r + t*pq; - assert(s < m_n); + CRYPTOPP_ASSERT(s < m_n); #if 0 using namespace std; cout << "f = " << x << endl; diff --git a/fhmqv.h b/fhmqv.h index 0e9a317b..b5eceb79 100644 --- a/fhmqv.h +++ b/fhmqv.h @@ -171,7 +171,7 @@ public: } else { - assert(0); + CRYPTOPP_ASSERT(0); return false; } @@ -248,7 +248,7 @@ protected: { HASH hash; size_t idx = 0, req = dlen; - size_t blk = std::min(dlen, (size_t)HASH::DIGESTSIZE); + size_t blk = STDMIN(dlen, (size_t)HASH::DIGESTSIZE); if(sigma) { @@ -272,7 +272,7 @@ protected: hash.Update(&digest[idx], (size_t)HASH::DIGESTSIZE); idx += (size_t)HASH::DIGESTSIZE; - blk = std::min(req, (size_t)HASH::DIGESTSIZE); + blk = STDMIN(req, (size_t)HASH::DIGESTSIZE); hash.TruncatedFinal(&digest[idx], blk); req -= blk; diff --git a/files.cpp b/files.cpp index 5ac45c6c..ff25dc7e 100644 --- a/files.cpp +++ b/files.cpp @@ -141,7 +141,7 @@ size_t FileStore::CopyRangeTo2(BufferedTransformation &target, lword &begin, lwo m_stream->seekg(newPosition); try { - assert(!m_waiting); + CRYPTOPP_ASSERT(!m_waiting); lword copyMax = end-begin; size_t blockedBytes = const_cast(this)->TransferTo2(target, copyMax, channel, blocking); begin += copyMax; diff --git a/filters.cpp b/filters.cpp index 80cd523b..9366ca79 100644 --- a/filters.cpp +++ b/filters.cpp @@ -188,7 +188,7 @@ size_t MeterFilter::PutMaybeModifiable(byte *begin, size_t length, int messageEn { FILTER_OUTPUT_MAYBE_MODIFIABLE(1, m_begin, t = (size_t)SaturatingSubtract(m_rangesToSkip.front().position, m_currentMessageBytes), false, modifiable); - assert(t < m_length); + CRYPTOPP_ASSERT(t < m_length); m_begin += t; m_length -= t; m_currentMessageBytes += t; @@ -199,7 +199,7 @@ size_t MeterFilter::PutMaybeModifiable(byte *begin, size_t length, int messageEn else { t = (size_t)SaturatingSubtract(m_rangesToSkip.front().position + m_rangesToSkip.front().size, m_currentMessageBytes); - assert(t <= m_length); + CRYPTOPP_ASSERT(t <= m_length); m_rangesToSkip.pop_front(); } @@ -303,7 +303,7 @@ void FilterWithBufferedInput::BlockQueue::Put(const byte *inString, size_t lengt // Avoid passing NULL pointer to memcpy if (!inString || !length) return; - assert(m_size + length <= m_buffer.size()); + CRYPTOPP_ASSERT(m_size + length <= m_buffer.size()); byte *end = (m_size < size_t(m_buffer.end()-m_begin)) ? m_begin + m_size : m_begin + m_size - m_buffer.size(); size_t len = STDMIN(length, size_t(m_buffer.end()-end)); memcpy(end, inString, len); @@ -368,7 +368,7 @@ size_t FilterWithBufferedInput::PutMaybeModifiable(byte *inString, size_t length size_t len = m_firstSize - m_queue.CurrentSize(); m_queue.Put(inString, len); FirstPut(m_queue.GetContigousBlocks(m_firstSize)); - assert(m_queue.CurrentSize() == 0); + CRYPTOPP_ASSERT(m_queue.CurrentSize() == 0); m_queue.ResetQueue(m_blockSize, (2*m_blockSize+m_lastSize-2)/m_blockSize); inString += len; @@ -406,7 +406,7 @@ size_t FilterWithBufferedInput::PutMaybeModifiable(byte *inString, size_t length if (newLength >= m_blockSize + m_lastSize && m_queue.CurrentSize() > 0) { - assert(m_queue.CurrentSize() < m_blockSize); + CRYPTOPP_ASSERT(m_queue.CurrentSize() < m_blockSize); size_t len = m_blockSize - m_queue.CurrentSize(); m_queue.Put(inString, len); inString += len; @@ -465,10 +465,10 @@ void FilterWithBufferedInput::ForceNextPut() void FilterWithBufferedInput::NextPutMultiple(const byte *inString, size_t length) { - assert(m_blockSize > 1); // m_blockSize = 1 should always override this function + CRYPTOPP_ASSERT(m_blockSize > 1); // m_blockSize = 1 should always override this function while (length > 0) { - assert(length >= m_blockSize); + CRYPTOPP_ASSERT(length >= m_blockSize); NextPutSingle(inString); inString += m_blockSize; length -= m_blockSize; @@ -590,7 +590,7 @@ StreamTransformationFilter::StreamTransformationFilter(StreamTransformation &c, : FilterWithBufferedInput(attachment) , m_cipher(c), m_padding(DEFAULT_PADDING), m_optimalBufferSize(0) { - assert(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize()); + CRYPTOPP_ASSERT(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize()); if (!allowAuthenticatedSymmetricCipher && dynamic_cast(&c) != 0) throw InvalidArgument("StreamTransformationFilter: please use AuthenticatedEncryptionFilter and AuthenticatedDecryptionFilter for AuthenticatedSymmetricCipher"); @@ -710,15 +710,15 @@ void StreamTransformationFilter::LastPut(const byte *inString, size_t length) case ONE_AND_ZEROS_PADDING: unsigned int s; s = m_cipher.MandatoryBlockSize(); - assert(s > 1); + CRYPTOPP_ASSERT(s > 1); space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, s, m_optimalBufferSize); if (m_cipher.IsForwardTransformation()) { - assert(length < s); + CRYPTOPP_ASSERT(length < s); if (inString) {memcpy(space, inString, length);} if (m_padding == PKCS_PADDING) { - assert(s < 256); + CRYPTOPP_ASSERT(s < 256); byte pad = byte(s-length); memset(space+length, pad, s-length); } @@ -754,7 +754,7 @@ void StreamTransformationFilter::LastPut(const byte *inString, size_t length) break; default: - assert(false); + CRYPTOPP_ASSERT(false); } } @@ -836,7 +836,7 @@ void HashVerificationFilter::LastPut(const byte *inString, size_t length) { if (m_flags & HASH_AT_BEGIN) { - assert(length == 0); + CRYPTOPP_ASSERT(length == 0); m_verified = m_hashModule.TruncatedVerify(m_expectedHash, m_digestSize); } else @@ -860,7 +860,7 @@ AuthenticatedEncryptionFilter::AuthenticatedEncryptionFilter(AuthenticatedSymmet : StreamTransformationFilter(c, attachment, padding, true) , m_hf(c, new OutputProxy(*this, false), putAAD, truncatedDigestSize, AAD_CHANNEL, macChannel) { - assert(c.IsForwardTransformation()); + CRYPTOPP_ASSERT(c.IsForwardTransformation()); } void AuthenticatedEncryptionFilter::IsolatedInitialize(const NameValuePairs ¶meters) @@ -904,7 +904,7 @@ AuthenticatedDecryptionFilter::AuthenticatedDecryptionFilter(AuthenticatedSymmet , m_hashVerifier(c, new OutputProxy(*this, false)) , m_streamFilter(c, new OutputProxy(*this, false), padding, true) { - assert(!c.IsForwardTransformation() || c.IsSelfInverting()); + CRYPTOPP_ASSERT(!c.IsForwardTransformation() || c.IsSelfInverting()); IsolatedInitialize(MakeParameters(Name::BlockPaddingScheme(), padding)(Name::AuthenticatedDecryptionFilterFlags(), flags)(Name::TruncatedDigestSize(), truncatedDigestSize)); } @@ -998,7 +998,7 @@ void SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameV m_flags = parameters.GetValueWithDefault(Name::SignatureVerificationFilterFlags(), (word32)DEFAULT_FLAGS); m_messageAccumulator.reset(m_verifier.NewVerificationAccumulator()); size_t size = m_verifier.SignatureLength(); - assert(size != 0); // TODO: handle recoverable signature scheme + CRYPTOPP_ASSERT(size != 0); // TODO: handle recoverable signature scheme m_verified = false; firstSize = m_flags & SIGNATURE_AT_BEGIN ? size : 0; blockSize = 1; @@ -1022,7 +1022,7 @@ void SignatureVerificationFilter::FirstPut(const byte *inString) } else { - assert(!m_verifier.SignatureUpfront()); + CRYPTOPP_ASSERT(!m_verifier.SignatureUpfront()); } } @@ -1037,7 +1037,7 @@ void SignatureVerificationFilter::LastPut(const byte *inString, size_t length) { if (m_flags & SIGNATURE_AT_BEGIN) { - assert(length == 0); + CRYPTOPP_ASSERT(length == 0); m_verifier.InputSignature(*m_messageAccumulator, m_signature, m_signature.size()); m_verified = m_verifier.VerifyAndRestart(*m_messageAccumulator); } diff --git a/filters.h b/filters.h index 1beba302..1336aad7 100644 --- a/filters.h +++ b/filters.h @@ -176,7 +176,7 @@ struct CRYPTOPP_DLL FilterPutSpaceHelper //! called \p m_tempSpace is resized and used for the caller. byte *HelpCreatePutSpace(BufferedTransformation &target, const std::string &channel, size_t minSize, size_t desiredSize, size_t &bufferSize) { - assert(desiredSize >= minSize && bufferSize >= minSize); + CRYPTOPP_ASSERT(desiredSize >= minSize && bufferSize >= minSize); if (m_tempSpace.size() < minSize) { byte *result = target.ChannelCreatePutSpace(channel, desiredSize); @@ -362,7 +362,7 @@ protected: virtual void FirstPut(const byte *inString) =0; // NextPut() is called if totalLength >= firstSize+blockSize+lastSize virtual void NextPutSingle(const byte *inString) - {CRYPTOPP_UNUSED(inString); assert(false);} + {CRYPTOPP_UNUSED(inString); CRYPTOPP_ASSERT(false);} // Same as NextPut() except length can be a multiple of blockSize // Either NextPut() or NextPutMultiple() must be overriden virtual void NextPutMultiple(const byte *inString, size_t length); @@ -387,7 +387,7 @@ protected: // This function should no longer be used, put this here to cause a compiler error // if someone tries to override NextPut(). virtual int NextPut(const byte *inString, size_t length) - {CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length); assert(false); return 0;} + {CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(false); return 0;} class BlockQueue { @@ -965,7 +965,7 @@ public: //! \brief Construct a StringSinkTemplate //! \param output std::basic_string type StringSinkTemplate(T &output) - : m_output(&output) {assert(sizeof(output[0])==1);} + : m_output(&output) {CRYPTOPP_ASSERT(sizeof(output[0])==1);} void IsolatedInitialize(const NameValuePairs ¶meters) {if (!parameters.GetValue("OutputStringPointer", m_output)) throw InvalidArgument("StringSink: OutputStringPointer not specified");} diff --git a/fips140.cpp b/fips140.cpp index a7e396d7..1c442e89 100644 --- a/fips140.cpp +++ b/fips140.cpp @@ -54,7 +54,7 @@ bool PowerUpSelfTestInProgressOnThisThread() #if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 return AccessPowerUpSelfTestInProgress().GetValue() != NULL; #else - assert(false); // should not be called + CRYPTOPP_ASSERT(false); // should not be called return false; #endif } diff --git a/fipsalgt.cpp b/fipsalgt.cpp index c0d0c628..d20a9b9e 100644 --- a/fipsalgt.cpp +++ b/fipsalgt.cpp @@ -262,7 +262,7 @@ protected: static inline void Xor(SecByteBlock &z, const SecByteBlock &x, const SecByteBlock &y) { - assert(x.size() == y.size()); + CRYPTOPP_ASSERT(x.size() == y.size()); z.resize(x.size()); xorbuf(z, x, y, x.size()); } @@ -637,7 +637,7 @@ protected: } else { - assert(m_test == "Gen"); + CRYPTOPP_ASSERT(m_test == "Gen"); int modLen = atol(m_bracketString.substr(6).c_str()); std::string &encodedKey = m_data["PrivKey"]; RSA::PrivateKey priv; @@ -1034,7 +1034,7 @@ protected: } else { - assert(m_test == "KAT"); + CRYPTOPP_ASSERT(m_test == "KAT"); SecByteBlock &input = m_data2[INPUT]; SecByteBlock result(input.size()); @@ -1097,7 +1097,7 @@ protected: if (m_line.substr(0, 2) == "H>") { - assert(m_test == "sha"); + CRYPTOPP_ASSERT(m_test == "sha"); m_bracketString = m_line.substr(2, m_line.size()-4); m_line = m_line.substr(0, 13) + "Hashes())); - assert(IsAlignedOn(b,GetAlignmentOf<__m128i>())); - assert(IsAlignedOn(c,GetAlignmentOf<__m128i>())); + CRYPTOPP_ASSERT(IsAlignedOn(a,GetAlignmentOf<__m128i>())); + CRYPTOPP_ASSERT(IsAlignedOn(b,GetAlignmentOf<__m128i>())); + CRYPTOPP_ASSERT(IsAlignedOn(c,GetAlignmentOf<__m128i>())); *(__m128i *)(void *)a = _mm_xor_si128(*(__m128i *)(void *)b, *(__m128i *)(void *)c); #else asm ("movdqa %1, %%xmm0; pxor %2, %%xmm0; movdqa %%xmm0, %0;" : "=m" (a[0]) : "m"(b[0]), "m"(c[0])); @@ -108,18 +108,18 @@ inline static void SSE2_Xor16(byte *a, const byte *b, const byte *c) #if CRYPTOPP_BOOL_NEON_INTRINSICS_AVAILABLE inline static void NEON_Xor16(byte *a, const byte *b, const byte *c) { - assert(IsAlignedOn(a,GetAlignmentOf())); - assert(IsAlignedOn(b,GetAlignmentOf())); - assert(IsAlignedOn(c,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(a,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(b,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(c,GetAlignmentOf())); *(uint64x2_t*)a = veorq_u64(*(uint64x2_t*)b, *(uint64x2_t*)c); } #endif inline static void Xor16(byte *a, const byte *b, const byte *c) { - assert(IsAlignedOn(a,GetAlignmentOf())); - assert(IsAlignedOn(b,GetAlignmentOf())); - assert(IsAlignedOn(c,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(a,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(b,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(c,GetAlignmentOf())); ((word64 *)(void *)a)[0] = ((word64 *)(void *)b)[0] ^ ((word64 *)(void *)c)[0]; ((word64 *)(void *)a)[1] = ((word64 *)(void *)b)[1] ^ ((word64 *)(void *)c)[1]; } @@ -641,7 +641,7 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len) typedef BlockGetAndPut Block; word64 *hashBuffer = (word64 *)(void *)HashBuffer(); - assert(IsAlignedOn(hashBuffer,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(hashBuffer,GetAlignmentOf())); switch (2*(m_buffer.size()>=64*1024) #if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE) diff --git a/gf2_32.cpp b/gf2_32.cpp index 929dac0d..084a1da3 100644 --- a/gf2_32.cpp +++ b/gf2_32.cpp @@ -52,7 +52,7 @@ GF2_32::Element GF2_32::MultiplicativeInverse(Element a) const word32 g0=m_modulus, g1=a, g2=a; word32 v0=0, v1=1, v2=1; - assert(g1); + CRYPTOPP_ASSERT(g1); while (!(g2 & 0x80000000)) { @@ -70,25 +70,25 @@ GF2_32::Element GF2_32::MultiplicativeInverse(Element a) const { if (g1 < g0 || ((g0^g1) < g0 && (g0^g1) < g1)) { - assert(BitPrecision(g1) <= BitPrecision(g0)); + CRYPTOPP_ASSERT(BitPrecision(g1) <= BitPrecision(g0)); g2 = g1; v2 = v1; } else { - assert(BitPrecision(g1) > BitPrecision(g0)); + CRYPTOPP_ASSERT(BitPrecision(g1) > BitPrecision(g0)); g2 = g0; g0 = g1; g1 = g2; v2 = v0; v0 = v1; v1 = v2; } while ((g0^g2) >= g2) { - assert(BitPrecision(g0) > BitPrecision(g2)); + CRYPTOPP_ASSERT(BitPrecision(g0) > BitPrecision(g2)); g2 <<= 1; v2 <<= 1; } - assert(BitPrecision(g0) == BitPrecision(g2)); + CRYPTOPP_ASSERT(BitPrecision(g0) == BitPrecision(g2)); g0 ^= g2; v0 ^= v2; } diff --git a/gf2n.cpp b/gf2n.cpp index 7c78fafd..f27a5401 100644 --- a/gf2n.cpp +++ b/gf2n.cpp @@ -27,7 +27,7 @@ PolynomialMod2::PolynomialMod2() PolynomialMod2::PolynomialMod2(word value, size_t bitLength) : reg(BitsToWords(bitLength)) { - assert(value==0 || reg.size()>0); + CRYPTOPP_ASSERT(value==0 || reg.size()>0); if (reg.size() > 0) { @@ -327,7 +327,7 @@ PolynomialMod2& PolynomialMod2::operator<<=(unsigned int n) { #if !defined(NDEBUG) int x; CRYPTOPP_UNUSED(x); - assert(SafeConvert(n,x)); + CRYPTOPP_ASSERT(SafeConvert(n,x)); #endif if (!reg.size()) @@ -561,7 +561,7 @@ GF2NP::Element GF2NP::SquareRoot(const Element &a) const GF2NP::Element GF2NP::HalfTrace(const Element &a) const { - assert(m%2 == 1); + CRYPTOPP_ASSERT(m%2 == 1); Element h = a; for (unsigned int i=1; i<=(m-1)/2; i++) h = Add(Square(Square(h)), a); @@ -600,7 +600,7 @@ GF2NT::GF2NT(unsigned int c0, unsigned int c1, unsigned int c2) , t0(c0), t1(c1) , result((word)0, m) { - assert(c0 > c1 && c1 > c2 && c2==0); + CRYPTOPP_ASSERT(c0 > c1 && c1 > c2 && c2==0); } const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const @@ -618,7 +618,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const SetWords(T, 0, 3*m_modulus.reg.size()); b[0]=1; - assert(a.reg.size() <= m_modulus.reg.size()); + CRYPTOPP_ASSERT(a.reg.size() <= m_modulus.reg.size()); CopyWords(f, a.reg, a.reg.size()); CopyWords(g, m_modulus.reg, m_modulus.reg.size()); @@ -630,7 +630,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const ShiftWordsRightByWords(f, fgLen, 1); if (c[bcLen-1]) bcLen++; - assert(bcLen <= m_modulus.reg.size()); + CRYPTOPP_ASSERT(bcLen <= m_modulus.reg.size()); ShiftWordsLeftByWords(c, bcLen, 1); k+=WORD_BITS; t=f[0]; @@ -661,7 +661,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const { c[bcLen] = t; bcLen++; - assert(bcLen <= m_modulus.reg.size()); + CRYPTOPP_ASSERT(bcLen <= m_modulus.reg.size()); } if (f[fgLen-1]==0 && g[fgLen-1]==0) @@ -717,7 +717,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const for (unsigned int j=0; j> j) & 1) << (t1 + j); } } @@ -811,7 +811,7 @@ const GF2NT::Element& GF2NT::Reduced(const Element &a) const if ((t0-t1)%WORD_BITS > t0%WORD_BITS) b[i-(t0-t1)/WORD_BITS-1] ^= temp << (WORD_BITS - (t0-t1)%WORD_BITS); else - assert(temp << (WORD_BITS - (t0-t1)%WORD_BITS) == 0); + CRYPTOPP_ASSERT(temp << (WORD_BITS - (t0-t1)%WORD_BITS) == 0); } else b[i-(t0-t1)/WORD_BITS] ^= temp; diff --git a/gf2n.h b/gf2n.h index 867b7590..bfd19027 100644 --- a/gf2n.h +++ b/gf2n.h @@ -286,16 +286,16 @@ public: virtual GF2NP * Clone() const {return new GF2NP(*this);} virtual void DEREncode(BufferedTransformation &bt) const - {CRYPTOPP_UNUSED(bt); assert(false);} // no ASN.1 syntax yet for general polynomial basis + {CRYPTOPP_UNUSED(bt); CRYPTOPP_ASSERT(false);} // no ASN.1 syntax yet for general polynomial basis void DEREncodeElement(BufferedTransformation &out, const Element &a) const; void BERDecodeElement(BufferedTransformation &in, Element &a) const; bool Equal(const Element &a, const Element &b) const - {assert(a.Degree() < m_modulus.Degree() && b.Degree() < m_modulus.Degree()); return a.Equals(b);} + {CRYPTOPP_ASSERT(a.Degree() < m_modulus.Degree() && b.Degree() < m_modulus.Degree()); return a.Equals(b);} bool IsUnit(const Element &a) const - {assert(a.Degree() < m_modulus.Degree()); return !!a;} + {CRYPTOPP_ASSERT(a.Degree() < m_modulus.Degree()); return !!a;} unsigned int MaxElementBitLength() const {return m;} diff --git a/gfpcrypt.cpp b/gfpcrypt.cpp index 2a3b6974..8edd8553 100644 --- a/gfpcrypt.cpp +++ b/gfpcrypt.cpp @@ -82,8 +82,8 @@ void DL_SignatureMessageEncodingMethod_DSA::ComputeMessageRepresentative(RandomN { CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength); CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier); - assert(recoverableMessageLength == 0); - assert(hashIdentifier.second == 0); + CRYPTOPP_ASSERT(recoverableMessageLength == 0); + CRYPTOPP_ASSERT(hashIdentifier.second == 0); const size_t representativeByteLength = BitsToBytes(representativeBitLength); const size_t digestSize = hash.DigestSize(); @@ -109,8 +109,8 @@ void DL_SignatureMessageEncodingMethod_NR::ComputeMessageRepresentative(RandomNu CRYPTOPP_UNUSED(hash); CRYPTOPP_UNUSED(hashIdentifier); CRYPTOPP_UNUSED(messageEmpty); CRYPTOPP_UNUSED(representative); CRYPTOPP_UNUSED(representativeBitLength); - assert(recoverableMessageLength == 0); - assert(hashIdentifier.second == 0); + CRYPTOPP_ASSERT(recoverableMessageLength == 0); + CRYPTOPP_ASSERT(hashIdentifier.second == 0); const size_t representativeByteLength = BitsToBytes(representativeBitLength); const size_t digestSize = hash.DigestSize(); const size_t paddingLength = SaturatingSubtract(representativeByteLength, digestSize); diff --git a/gfpcrypt.h b/gfpcrypt.h index 7fb7ec27..4cdf3b06 100644 --- a/gfpcrypt.h +++ b/gfpcrypt.h @@ -193,7 +193,7 @@ public: r %= q; Integer kInv = k.InverseMod(q); s = (kInv * (x*r + e)) % q; - assert(!!r && !!s); + CRYPTOPP_ASSERT(!!r && !!s); } bool Verify(const DL_GroupParameters ¶ms, const DL_PublicKey &publicKey, const Integer &e, const Integer &r, const Integer &s) const @@ -228,7 +228,7 @@ public: const Integer &q = params.GetSubgroupOrder(); r = (r + e) % q; s = (k - x*r) % q; - assert(!!r); + CRYPTOPP_ASSERT(!!r); } bool Verify(const DL_GroupParameters ¶ms, const DL_PublicKey &publicKey, const Integer &e, const Integer &r, const Integer &s) const diff --git a/hkdf.h b/hkdf.h index 447d15dc..a7903f60 100644 --- a/hkdf.h +++ b/hkdf.h @@ -62,9 +62,9 @@ unsigned int HKDF::DeriveKey(byte *derived, size_t derivedLen, const byte *se static const size_t DIGEST_SIZE = static_cast(T::DIGESTSIZE); const unsigned int req = static_cast(derivedLen); - assert(secret && secretLen); - assert(derived && derivedLen); - assert(derivedLen <= MaxDerivedKeyLength()); + CRYPTOPP_ASSERT(secret && secretLen); + CRYPTOPP_ASSERT(derived && derivedLen); + CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength()); if (derivedLen > MaxDerivedKeyLength()) throw InvalidArgument("HKDF: derivedLen must be less than or equal to MaxDerivedKeyLength"); diff --git a/hmac.cpp b/hmac.cpp index a25eb749..bb0d9e52 100644 --- a/hmac.cpp +++ b/hmac.cpp @@ -30,7 +30,7 @@ void HMAC_Base::UncheckedSetKey(const byte *userKey, unsigned int keylength, con keylength = hash.DigestSize(); } - assert(keylength <= blockSize); + CRYPTOPP_ASSERT(keylength <= blockSize); memset(AccessIpad()+keylength, 0, blockSize-keylength); for (unsigned int i=0; i #endif -#include +#include "trap.h" NAMESPACE_BEGIN(CryptoPP) @@ -53,7 +53,7 @@ double TimerBase::ConvertTo(TimerWord t, Unit unit) static unsigned long unitsPerSecondTable[] = {1, 1000, 1000*1000, 1000*1000*1000}; // When 'unit' is an enum 'Unit', a Clang warning is generated. - assert(static_cast(unit) < COUNTOF(unitsPerSecondTable)); + CRYPTOPP_ASSERT(static_cast(unit) < COUNTOF(unitsPerSecondTable)); return (double)CRYPTOPP_VC6_INT64 t * unitsPerSecondTable[unit] / CRYPTOPP_VC6_INT64 TicksPerSecond(); } @@ -83,7 +83,7 @@ double TimerBase::ElapsedTimeAsDouble() unsigned long TimerBase::ElapsedTime() { double elapsed = ElapsedTimeAsDouble(); - assert(elapsed <= (double)ULONG_MAX); + CRYPTOPP_ASSERT(elapsed <= (double)ULONG_MAX); return (unsigned long)elapsed; } diff --git a/ida.cpp b/ida.cpp index 3c04ce61..64bcf968 100644 --- a/ida.cpp +++ b/ida.cpp @@ -22,7 +22,7 @@ void RawIDA::IsolatedInitialize(const NameValuePairs ¶meters) if (!parameters.GetIntValue("RecoveryThreshold", m_threshold)) throw InvalidArgument("RawIDA: missing RecoveryThreshold argument"); - assert(m_threshold > 0); + CRYPTOPP_ASSERT(m_threshold > 0); if (m_threshold <= 0) throw InvalidArgument("RawIDA: RecoveryThreshold must be greater than 0"); @@ -43,7 +43,7 @@ void RawIDA::IsolatedInitialize(const NameValuePairs ¶meters) else { int nShares = parameters.GetIntValueWithDefault("NumberOfShares", m_threshold); - assert(nShares > 0); + CRYPTOPP_ASSERT(nShares > 0); if (nShares <= 0) {nShares = m_threshold;} for (unsigned int i=0; i< (unsigned int)(nShares); i++) AddOutputChannel(i); @@ -152,7 +152,7 @@ void RawIDA::AddOutputChannel(word32 channelId) void RawIDA::PrepareInterpolation() { - assert(m_inputChannelIds.size() == size_t(m_threshold)); + CRYPTOPP_ASSERT(m_inputChannelIds.size() == size_t(m_threshold)); PrepareBulkPolynomialInterpolation(field, m_w.begin(), &(m_inputChannelIds[0]), (unsigned int)(m_threshold)); for (unsigned int i=0; i= 2); // should use an inline function but macros are still faster in MSVC 4.0 #define DirectMUL(a,b) \ { \ - assert(b <= 0xffff); \ + CRYPTOPP_ASSERT(b <= 0xffff); \ \ word32 p=(word32)low16(a)*b; \ \ diff --git a/integer.cpp b/integer.cpp index bb41088f..457f3976 100644 --- a/integer.cpp +++ b/integer.cpp @@ -90,7 +90,7 @@ inline static int Compare(const word *A, const word *B, size_t N) inline static int Increment(word *A, size_t N, word B=1) { - assert(N); + CRYPTOPP_ASSERT(N); word t = A[0]; A[0] = t+B; if (A[0] >= t) @@ -103,7 +103,7 @@ inline static int Increment(word *A, size_t N, word B=1) inline static int Decrement(word *A, size_t N, word B=1) { - assert(N); + CRYPTOPP_ASSERT(N); word t = A[0]; A[0] = t-B; if (A[0] <= t) @@ -123,14 +123,14 @@ static void TwosComplement(word *A, size_t N) static word AtomicInverseModPower2(word A) { - assert(A%2==1); + CRYPTOPP_ASSERT(A%2==1); word R=A%8; for (unsigned i=3; i=2 && N%2==0); + CRYPTOPP_ASSERT(N>=2 && N%2==0); if (N <= s_recursionLimit) s_pMul[N/4](R, A, B); @@ -2202,7 +2202,7 @@ void RecursiveMultiply(word *R, word *T, const word *A, const word *B, size_t N) c3 += Add(R1, R1, T0, N); c3 += Increment(R2, N2, c2); - assert (c3 >= 0 && c3 <= 2); + CRYPTOPP_ASSERT (c3 >= 0 && c3 <= 2); Increment(R3, N2, c3); } } @@ -2213,7 +2213,7 @@ void RecursiveMultiply(word *R, word *T, const word *A, const word *B, size_t N) void RecursiveSquare(word *R, word *T, const word *A, size_t N) { - assert(N && N%2==0); + CRYPTOPP_ASSERT(N && N%2==0); if (N <= s_recursionLimit) s_pSqu[N/4](R, A); @@ -2238,7 +2238,7 @@ void RecursiveSquare(word *R, word *T, const word *A, size_t N) void RecursiveMultiplyBottom(word *R, word *T, const word *A, const word *B, size_t N) { - assert(N>=2 && N%2==0); + CRYPTOPP_ASSERT(N>=2 && N%2==0); if (N <= s_recursionLimit) s_pBot[N/4](R, A, B); @@ -2262,7 +2262,7 @@ void RecursiveMultiplyBottom(word *R, word *T, const word *A, const word *B, siz void MultiplyTop(word *R, word *T, const word *L, const word *A, const word *B, size_t N) { - assert(N>=2 && N%2==0); + CRYPTOPP_ASSERT(N>=2 && N%2==0); if (N <= s_recursionLimit) s_pTop[N/4](R, A, B, L[N-1]); @@ -2304,7 +2304,7 @@ void MultiplyTop(word *R, word *T, const word *L, const word *A, const word *B, c3 -= Decrement(T2, N2, -c2); c3 += Add(R0, T2, R1, N2); - assert (c3 >= 0 && c3 <= 2); + CRYPTOPP_ASSERT (c3 >= 0 && c3 <= 2); Increment(R1, N2, c3); } } @@ -2347,7 +2347,7 @@ void AsymmetricMultiply(word *R, word *T, const word *A, size_t NA, const word * std::swap(NA, NB); } - assert(NB % NA == 0); + CRYPTOPP_ASSERT(NB % NA == 0); if (NA==2 && !A[1]) { @@ -2433,7 +2433,7 @@ void MontgomeryReduce(word *R, word *T, word *X, const word *M, const word *U, s word borrow = Subtract(T, X+N, T, N); // defend against timing attack by doing this Add even when not needed word carry = Add(T+N, T, M, N); - assert(carry | !borrow); + CRYPTOPP_ASSERT(carry | !borrow); CRYPTOPP_UNUSED(carry), CRYPTOPP_UNUSED(borrow); CopyWords(R, T + ((0-borrow) & N), N); #elif 0 @@ -2501,7 +2501,7 @@ void MontgomeryReduce(word *R, word *T, word *X, const word *M, const word *U, s void HalfMontgomeryReduce(word *R, word *T, const word *X, const word *M, const word *U, const word *V, size_t N) { - assert(N%2==0 && N>=4); + CRYPTOPP_ASSERT(N%2==0 && N>=4); #define M0 M #define M1 (M+N2) @@ -2530,7 +2530,7 @@ void HalfMontgomeryReduce(word *R, word *T, const word *X, const word *M, const else if (c2<0) c3 -= Decrement(R1, N2, -c2); - assert(c3>=-1 && c3<=1); + CRYPTOPP_ASSERT(c3>=-1 && c3<=1); if (c3>0) Subtract(R, R, M, N); else if (c3<0) @@ -2566,8 +2566,8 @@ void HalfMontgomeryReduce(word *R, word *T, const word *X, const word *M, const // do a 3 word by 2 word divide, returns quotient and leaves remainder in A static word SubatomicDivide(word *A, word B0, word B1) { - // assert {A[2],A[1]} < {B1,B0}, so quotient can fit in a word - assert(A[2] < B1 || (A[2]==B1 && A[1] < B0)); + // CRYPTOPP_ASSERT {A[2],A[1]} < {B1,B0}, so quotient can fit in a word + CRYPTOPP_ASSERT(A[2] < B1 || (A[2]==B1 && A[1] < B0)); // estimate the quotient: do a 2 word by 1 word divide word Q; @@ -2593,7 +2593,7 @@ static word SubatomicDivide(word *A, word B0, word B1) A[1] = u.GetLowHalf(); A[2] += u.GetHighHalf(); Q++; - assert(Q); // shouldn't overflow + CRYPTOPP_ASSERT(Q); // shouldn't overflow } return Q; @@ -2616,11 +2616,11 @@ static inline void AtomicDivide(word *Q, const word *A, const word *B) #ifndef NDEBUG // multiply quotient and divisor and add remainder, make sure it equals dividend - assert(!T[2] && !T[3] && (T[1] < B[1] || (T[1]==B[1] && T[0]= 0) { R[N] -= Subtract(R, R, B, N); Q[1] += (++Q[0]==0); - assert(Q[0] || Q[1]); // no overflow + CRYPTOPP_ASSERT(Q[0] || Q[1]); // no overflow } } @@ -2673,9 +2673,9 @@ static void CorrectQuotientEstimate(word *R, word *T, word *Q, const word *B, si void Divide(word *R, word *Q, word *T, const word *A, size_t NA, const word *B, size_t NB) { - assert(NA && NB && NA%2==0 && NB%2==0); - assert(B[NB-1] || B[NB-2]); - assert(NB <= NA); + CRYPTOPP_ASSERT(NA && NB && NA%2==0 && NB%2==0); + CRYPTOPP_ASSERT(B[NB-1] || B[NB-2]); + CRYPTOPP_ASSERT(NB <= NA); // set up temporary work space word *const TA=T; @@ -2687,7 +2687,7 @@ void Divide(word *R, word *Q, word *T, const word *A, size_t NA, const word *B, TB[0] = TB[NB-1] = 0; CopyWords(TB+shiftWords, B, NB-shiftWords); unsigned shiftBits = WORD_BITS - BitPrecision(TB[NB-1]); - assert(shiftBits < WORD_BITS); + CRYPTOPP_ASSERT(shiftBits < WORD_BITS); ShiftWordsLeftByBits(TB, NB, shiftBits); // copy A into TA and normalize it @@ -2707,7 +2707,7 @@ void Divide(word *R, word *Q, word *T, const word *A, size_t NA, const word *B, else { NA+=2; - assert(Compare(TA+NA-NB, TB, NB) < 0); + CRYPTOPP_ASSERT(Compare(TA+NA-NB, TB, NB) < 0); } word BT[2]; @@ -2741,7 +2741,7 @@ static inline size_t EvenWordCount(const word *X, size_t N) unsigned int AlmostInverse(word *R, word *T, const word *A, size_t NA, const word *M, size_t N) { - assert(NA<=N && N && N%2==0); + CRYPTOPP_ASSERT(NA<=N && N && N%2==0); word *b = T; word *c = T+N; @@ -2769,7 +2769,7 @@ unsigned int AlmostInverse(word *R, word *T, const word *A, size_t NA, const wor ShiftWordsRightByWords(f, fgLen, 1); bcLen += 2 * (c[bcLen-1] != 0); - assert(bcLen <= N); + CRYPTOPP_ASSERT(bcLen <= N); ShiftWordsLeftByWords(c, bcLen, 1); k+=WORD_BITS; t=f[0]; @@ -2793,7 +2793,7 @@ unsigned int AlmostInverse(word *R, word *T, const word *A, size_t NA, const wor t = ShiftWordsLeftByBits(c, bcLen, i); c[bcLen] += t; bcLen += 2 * (t!=0); - assert(bcLen <= N); + CRYPTOPP_ASSERT(bcLen <= N); bool swap = Compare(f, g, fgLen)==-1; ConditionalSwapPointers(swap, f, g); @@ -2806,7 +2806,7 @@ unsigned int AlmostInverse(word *R, word *T, const word *A, size_t NA, const wor t = Add(b, b, c, bcLen); b[bcLen] += t; bcLen += 2*t; - assert(bcLen <= N); + CRYPTOPP_ASSERT(bcLen <= N); } } @@ -2926,7 +2926,7 @@ bool Integer::IsConvertableToLong() const signed long Integer::ConvertToLong() const { - assert(IsConvertableToLong()); + CRYPTOPP_ASSERT(IsConvertableToLong()); unsigned long value = (unsigned long)reg[0]; value += SafeLeftShift((unsigned long)reg[1]); @@ -2935,7 +2935,7 @@ signed long Integer::ConvertToLong() const Integer::Integer(BufferedTransformation &encodedInteger, size_t byteCount, Signedness s, ByteOrder o) { - assert(o == BIG_ENDIAN_ORDER || o == LITTLE_ENDIAN_ORDER); + CRYPTOPP_ASSERT(o == BIG_ENDIAN_ORDER || o == LITTLE_ENDIAN_ORDER); if(o == LITTLE_ENDIAN_ORDER) { @@ -2952,7 +2952,7 @@ Integer::Integer(BufferedTransformation &encodedInteger, size_t byteCount, Signe Integer::Integer(const byte *encodedInteger, size_t byteCount, Signedness s, ByteOrder o) { - assert(o == BIG_ENDIAN_ORDER || o == LITTLE_ENDIAN_ORDER); + CRYPTOPP_ASSERT(o == BIG_ENDIAN_ORDER || o == LITTLE_ENDIAN_ORDER); if(o == LITTLE_ENDIAN_ORDER) { @@ -3074,7 +3074,7 @@ void Integer::SetByte(size_t n, byte value) lword Integer::GetBits(size_t i, size_t n) const { lword v = 0; - assert(n <= sizeof(v)*8); + CRYPTOPP_ASSERT(n <= sizeof(v)*8); for (unsigned int j=0; j static Integer StringToInteger(const T *str, ByteOrder order) { - assert( order == BIG_ENDIAN_ORDER || order == LITTLE_ENDIAN_ORDER ); + CRYPTOPP_ASSERT( order == BIG_ENDIAN_ORDER || order == LITTLE_ENDIAN_ORDER ); int radix, sign = 1; // GCC workaround @@ -3285,7 +3285,7 @@ void Integer::Decode(const byte *input, size_t inputLen, Signedness s) void Integer::Decode(BufferedTransformation &bt, size_t inputLen, Signedness s) { - assert(bt.MaxRetrievable() >= inputLen); + CRYPTOPP_ASSERT(bt.MaxRetrievable() >= inputLen); byte b; bt.Peek(b); @@ -3302,7 +3302,7 @@ void Integer::Decode(BufferedTransformation &bt, size_t inputLen, Signedness s) const size_t size = RoundupSize(BytesToWords(inputLen)); reg.CleanNew(size); - assert(reg.SizeInBytes() >= inputLen); + CRYPTOPP_ASSERT(reg.SizeInBytes() >= inputLen); for (size_t i=inputLen; i > 0; i--) { bt.Get(b); @@ -3331,7 +3331,7 @@ size_t Integer::MinEncodedSize(Signedness signedness) const void Integer::Encode(byte *output, size_t outputLen, Signedness signedness) const { - assert(output && outputLen); + CRYPTOPP_ASSERT(output && outputLen); ArraySink sink(output, outputLen); Encode(sink, outputLen, signedness); } @@ -3669,7 +3669,7 @@ Integer& Integer::operator++() else { word borrow = Decrement(reg, reg.size()); - assert(!borrow); + CRYPTOPP_ASSERT(!borrow); CRYPTOPP_UNUSED(borrow); if (WordCount()==0) @@ -3747,7 +3747,7 @@ void PositiveSubtract(Integer &diff, const Integer &a, const Integer& b) word borrow = Subtract(diff.reg, a.reg, b.reg, bSize); CopyWords(diff.reg+bSize, a.reg+bSize, aSize-bSize); borrow = Decrement(diff.reg+bSize, aSize-bSize, borrow); - assert(!borrow); + CRYPTOPP_ASSERT(!borrow); diff.sign = Integer::POSITIVE; } else @@ -3755,7 +3755,7 @@ void PositiveSubtract(Integer &diff, const Integer &a, const Integer& b) word borrow = Subtract(diff.reg, b.reg, a.reg, aSize); CopyWords(diff.reg+aSize, b.reg+aSize, bSize-aSize); borrow = Decrement(diff.reg+aSize, bSize-aSize, borrow); - assert(!borrow); + CRYPTOPP_ASSERT(!borrow); diff.sign = Integer::NEGATIVE; } } @@ -4027,7 +4027,7 @@ void Integer::Divide(word &remainder, Integer "ient, const Integer ÷nd if (!divisor) throw Integer::DivideByZero(); - assert(divisor); + CRYPTOPP_ASSERT(divisor); if ((divisor & (divisor-1)) == 0) // divisor is a power of 2 { @@ -4071,7 +4071,7 @@ word Integer::Modulo(word divisor) const if (!divisor) throw Integer::DivideByZero(); - assert(divisor); + CRYPTOPP_ASSERT(divisor); word remainder; @@ -4143,7 +4143,7 @@ Integer Integer::SquareRoot() const // overestimate square root Integer x, y = Power2((BitCount()+1)/2); - assert(y*y >= *this); + CRYPTOPP_ASSERT(y*y >= *this); do { @@ -4188,7 +4188,7 @@ Integer Integer::Gcd(const Integer &a, const Integer &b) Integer Integer::InverseMod(const Integer &m) const { - assert(m.NotNegative()); + CRYPTOPP_ASSERT(m.NotNegative()); if (IsNegative()) return Modulo(m).InverseMod(m); @@ -4404,7 +4404,7 @@ const Integer& MontgomeryRepresentation::Multiply(const Integer &a, const Intege word *const T = m_workspace.begin(); word *const R = m_result.reg.begin(); const size_t N = m_modulus.reg.size(); - assert(a.reg.size()<=N && b.reg.size()<=N); + CRYPTOPP_ASSERT(a.reg.size()<=N && b.reg.size()<=N); AsymmetricMultiply(T, T+2*N, a.reg, a.reg.size(), b.reg, b.reg.size()); SetWords(T+a.reg.size()+b.reg.size(), 0, 2*N-a.reg.size()-b.reg.size()); @@ -4417,7 +4417,7 @@ const Integer& MontgomeryRepresentation::Square(const Integer &a) const word *const T = m_workspace.begin(); word *const R = m_result.reg.begin(); const size_t N = m_modulus.reg.size(); - assert(a.reg.size()<=N); + CRYPTOPP_ASSERT(a.reg.size()<=N); CryptoPP::Square(T, T+2*N, a.reg, a.reg.size()); SetWords(T+2*a.reg.size(), 0, 2*N-2*a.reg.size()); @@ -4430,7 +4430,7 @@ Integer MontgomeryRepresentation::ConvertOut(const Integer &a) const word *const T = m_workspace.begin(); word *const R = m_result.reg.begin(); const size_t N = m_modulus.reg.size(); - assert(a.reg.size()<=N); + CRYPTOPP_ASSERT(a.reg.size()<=N); CopyWords(T, a.reg, a.reg.size()); SetWords(T+a.reg.size(), 0, 2*N-a.reg.size()); @@ -4444,7 +4444,7 @@ const Integer& MontgomeryRepresentation::MultiplicativeInverse(const Integer &a) word *const T = m_workspace.begin(); word *const R = m_result.reg.begin(); const size_t N = m_modulus.reg.size(); - assert(a.reg.size()<=N); + CRYPTOPP_ASSERT(a.reg.size()<=N); CopyWords(T, a.reg, a.reg.size()); SetWords(T+a.reg.size(), 0, 2*N-a.reg.size()); @@ -4474,7 +4474,7 @@ std::string IntToString(Integer value, unsigned int base) const char CH = UPPER ? 'A' : 'a'; base &= ~(BIT_32|BIT_31); - assert(base >= 2 && base <= 32); + CRYPTOPP_ASSERT(base >= 2 && base <= 32); if (value == 0) return "0"; @@ -4537,7 +4537,7 @@ std::string IntToString(word64 value, unsigned int base) const char CH = !!(base & HIGH_BIT) ? 'A' : 'a'; base &= ~HIGH_BIT; - assert(base >= 2); + CRYPTOPP_ASSERT(base >= 2); if (value == 0) return "0"; diff --git a/iterhash.cpp b/iterhash.cpp index e324c442..a757a3e6 100644 --- a/iterhash.cpp +++ b/iterhash.cpp @@ -23,7 +23,7 @@ template void IteratedHashBase::Update(const byte T* dataBuf = this->DataBuf(); byte* data = (byte *)dataBuf; - assert(dataBuf && data); + CRYPTOPP_ASSERT(dataBuf && data); if (num != 0) // process left over data { @@ -48,7 +48,7 @@ template void IteratedHashBase::Update(const byte { if (input == data) { - assert(len == blockSize); + CRYPTOPP_ASSERT(len == blockSize); HashBlock(dataBuf); return; } diff --git a/keccak.cpp b/keccak.cpp index 452df6d6..14a08db8 100644 --- a/keccak.cpp +++ b/keccak.cpp @@ -251,7 +251,7 @@ static void KeccakF1600(word64 *state) void Keccak::Update(const byte *input, size_t length) { - assert((input && length) || !(input || length)); + CRYPTOPP_ASSERT((input && length) || !(input || length)); if (!length) return; diff --git a/luc.h b/luc.h index bac96f2b..45be09cf 100644 --- a/luc.h +++ b/luc.h @@ -134,7 +134,7 @@ typedef LUCSS::Verifier LUCSSA_PKCS1v15_SHA_Verifier; class DL_GroupPrecomputation_LUC : public DL_GroupPrecomputation { public: - const AbstractGroup & GetGroup() const {assert(false); throw 0;} + const AbstractGroup & GetGroup() const {CRYPTOPP_ASSERT(false); throw 0;} Element BERDecodeElement(BufferedTransformation &bt) const {return Integer(bt);} void DEREncodeElement(BufferedTransformation &bt, const Element &v) const {v.DEREncode(bt);} diff --git a/mersenne.h b/mersenne.h index ca2362b8..5bb78f80 100644 --- a/mersenne.h +++ b/mersenne.h @@ -84,7 +84,7 @@ public: case 2: output[1] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 2); /* fall through */ case 1: output[0] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 3); break; - default: assert(0); ;; + default: CRYPTOPP_ASSERT(0); ;; } // Wipe temp @@ -148,7 +148,7 @@ protected: static const unsigned long magic[2]={0x0UL, K}; word32 kk, temp; - assert(N >= M); + CRYPTOPP_ASSERT(N >= M); for (kk=0;kk 0); + CRYPTOPP_ASSERT(buf != NULL); + CRYPTOPP_ASSERT(mask != NULL); + CRYPTOPP_ASSERT(count > 0); size_t i=0; if (IsAligned(buf) && IsAligned(mask)) @@ -60,9 +60,9 @@ void xorbuf(byte *buf, const byte *mask, size_t count) void xorbuf(byte *output, const byte *input, const byte *mask, size_t count) { - assert(output != NULL); - assert(input != NULL); - assert(count > 0); + CRYPTOPP_ASSERT(output != NULL); + CRYPTOPP_ASSERT(input != NULL); + CRYPTOPP_ASSERT(count > 0); size_t i=0; if (IsAligned(output) && IsAligned(input) && IsAligned(mask)) @@ -95,9 +95,9 @@ void xorbuf(byte *output, const byte *input, const byte *mask, size_t count) bool VerifyBufsEqual(const byte *buf, const byte *mask, size_t count) { - assert(buf != NULL); - assert(mask != NULL); - assert(count > 0); + CRYPTOPP_ASSERT(buf != NULL); + CRYPTOPP_ASSERT(mask != NULL); + CRYPTOPP_ASSERT(count > 0); size_t i=0; byte acc8 = 0; @@ -136,7 +136,7 @@ bool VerifyBufsEqual(const byte *buf, const byte *mask, size_t count) #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 std::string StringNarrow(const wchar_t *str, bool throwOnError) { - assert(str); + CRYPTOPP_ASSERT(str); std::string result; // Safer functions on Windows for C&A, https://github.com/weidai11/cryptopp/issues/55 @@ -149,12 +149,12 @@ std::string StringNarrow(const wchar_t *str, bool throwOnError) len = wcslen(str)+1; err = wcstombs_s(&size, NULL, 0, str, len*sizeof(wchar_t)); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); if (err != 0) {goto CONVERSION_ERROR;} result.resize(size); err = wcstombs_s(&size, &result[0], size, str, len*sizeof(wchar_t)); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); if (err != 0) { @@ -170,12 +170,12 @@ CONVERSION_ERROR: result.erase(size - 1); #else size_t size = wcstombs(NULL, str, 0); - assert(size != (size_t)-1); + CRYPTOPP_ASSERT(size != (size_t)-1); if (size == (size_t)-1) {goto CONVERSION_ERROR;} result.resize(size); size = wcstombs(&result[0], str, size); - assert(size != (size_t)-1); + CRYPTOPP_ASSERT(size != (size_t)-1); if (size == (size_t)-1) { @@ -232,7 +232,7 @@ void * AlignedAllocate(size_t size) p[-1] = (byte)adjustment; #endif - assert(IsAlignedOn(p, 16)); + CRYPTOPP_ASSERT(IsAlignedOn(p, 16)); return p; } diff --git a/misc.h b/misc.h index 23ef0999..61833034 100644 --- a/misc.h +++ b/misc.h @@ -114,10 +114,10 @@ NAMESPACE_BEGIN(CryptoPP) // Forward declaration for IntToString specialization class Integer; -// ************** compile-time assertion *************** +// ************** compile-time CRYPTOPP_ASSERTion *************** #if CRYPTOPP_DOXYGEN_PROCESSING -//! \brief Compile time assertion +//! \brief Compile time CRYPTOPP_ASSERTion //! \param expr the expression to evaluate //! \details Asserts the expression expr though a dummy struct. #define CRYPTOPP_COMPILE_ASSERT(expr) ... @@ -129,18 +129,18 @@ struct CompileAssert }; //! \endif -#define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__) +#define CRYPTOPP_COMPILE_ASSERT(CRYPTOPP_ASSERTion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(CRYPTOPP_ASSERTion, __LINE__) #if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS) -#define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) +#define CRYPTOPP_COMPILE_ASSERT_INSTANCE(CRYPTOPP_ASSERTion, instance) #else # if defined(__GNUC__) -# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \ - static CompileAssert<(assertion)> \ - CRYPTOPP_ASSERT_JOIN(cryptopp_assert_, instance) __attribute__ ((unused)) +# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(CRYPTOPP_ASSERTion, instance) \ + static CompileAssert<(CRYPTOPP_ASSERTion)> \ + CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused)) # else -# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \ - static CompileAssert<(assertion)> \ - CRYPTOPP_ASSERT_JOIN(cryptopp_assert_, instance) +# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(CRYPTOPP_ASSERTion, instance) \ + static CompileAssert<(CRYPTOPP_ASSERTion)> \ + CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) # endif // __GNUC__ #endif #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y) @@ -331,6 +331,88 @@ const T & Singleton::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const } #endif +#if defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) +//! \brief Signal handler function pointer +//! \sa SignalHandler +extern "C" { + typedef void (*SignalHandlerFn) (int); +}; + +//! Signal handler for Linux and Unix compatibles +//! \tparam S Signal number +//! \tparam O Flag indicating exsting handler should be overwriiten +//! \details SignalHandler() can be used to install a signal handler with the signature +//! void handler_fn(int). If SignalHandlerFn is not NULL, then +//! the sigaction is set to the function and the sigaction flags is set to the flags. +//! If SignalHandlerFn is NULL, then a default handler is installed +//! using sigaction flags set to 0. The default handler only returns from the call. +//! \details Upon destruction the previous signal handler is restored. +//! \warning Do not use SignalHandler in a code block that uses setjmp or longjmp +//! because the destructor may not run. +//! \since Crypto++ 5.6.5 +//! \sa SignalHandlerFn, \ref CRYPTOPP_ASSERT "CRYPTOPP_ASSERT", DebugTrapHandler +template +struct SignalHandler : private NotCopyable +{ + //! \brief Construct a signal handler + //! \param pfn Pointer to a signal handler function + //! \param flags Flags to use with the signal handler + //! \details SignalHandler() installs a signal handler with the signature + //! void handler_fn(int). If SignalHandlerFn is not NULL, then + //! the sigaction is set to the function and the sigaction flags is set to the flags. + //! If SignalHandlerFn is NULL, then a default handler is installed + //! using sigaction flags set to 0. The default handler only returns from the call. + //! \details Upon destruction the previous signal handler is restored. + //! \warning Do not use SignalHandler in a code block that uses setjmp or longjmp + //! because the destructor may not run. + //! \since Crypto++ 5.6.5 + SignalHandler(SignalHandlerFn pfn = 0, int flags = 0) : m_installed(false) + { + // http://pubs.opengroup.org/onlinepubs/007908799/xsh/sigaction.html + struct sigaction new_handler; + // memset(&new_handler, 0x00, sizeof(new_handler)); + + do + { + int ret = 0; + + ret = sigaction (S, 0, &m_old); + if (ret != 0) break; // Failed + + // Don't step on another's handler if Overwrite=false + if (m_old.sa_handler != 0 && !O) break; + + // Set up the structure to specify the action. + new_handler.sa_handler = (pfn ? pfn : &SignalHandler::NullHandler); + new_handler.sa_flags = (pfn ? flags : 0); + + ret = sigemptyset (&new_handler.sa_mask); + if (ret != 0) break; // Failed + + // Install it + ret = sigaction (S, &new_handler, 0); + if (ret != 0) break; // Failed + + m_installed = true; + + } while(0); + } + + ~SignalHandler() + { + if (m_installed) + sigaction (S, &m_old, 0); + } + +private: + + struct sigaction m_old; + bool m_installed; + + static void NullHandler(int /*unused*/) { } +}; +#endif + // ************** misc functions *************** #if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB) @@ -351,16 +433,16 @@ const T & Singleton::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const //! makes memcpy_s() and memmove_s() available. The library will also optionally //! make the symbols available if CRYPTOPP_WANT_SECURE_LIB is defined. //! CRYPTOPP_WANT_SECURE_LIB is in config.h, but it is disabled by default. -//! \details memcpy_s() will assert the pointers src and dest are not NULL +//! \details memcpy_s() will CRYPTOPP_ASSERT the pointers src and dest are not NULL //! in debug builds. Passing NULL for either pointer is undefined behavior. inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count) { // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55 // Pointers must be valid; otherwise undefined behavior - assert(dest != NULL); assert(src != NULL); + CRYPTOPP_ASSERT(dest != NULL); CRYPTOPP_ASSERT(src != NULL); // Destination buffer must be large enough to satsify request - assert(sizeInBytes >= count); + CRYPTOPP_ASSERT(sizeInBytes >= count); if (count > sizeInBytes) throw InvalidArgument("memcpy_s: buffer overflow"); @@ -393,16 +475,16 @@ inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t cou //! makes memcpy_s() and memmove_s() available. The library will also optionally //! make the symbols available if CRYPTOPP_WANT_SECURE_LIB is defined. //! CRYPTOPP_WANT_SECURE_LIB is in config.h, but it is disabled by default. -//! \details memmove_s() will assert the pointers src and dest are not NULL +//! \details memmove_s() will CRYPTOPP_ASSERT the pointers src and dest are not NULL //! in debug builds. Passing NULL for either pointer is undefined behavior. inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count) { // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55 // Pointers must be valid; otherwise undefined behavior - assert(dest != NULL); assert(src != NULL); + CRYPTOPP_ASSERT(dest != NULL); CRYPTOPP_ASSERT(src != NULL); // Destination buffer must be large enough to satsify request - assert(sizeInBytes >= count); + CRYPTOPP_ASSERT(sizeInBytes >= count); if (count > sizeInBytes) throw InvalidArgument("memmove_s: buffer overflow"); @@ -534,7 +616,7 @@ std::string IntToString(T value, unsigned int base = 10) const char CH = !!(base & HIGH_BIT) ? 'A' : 'a'; base &= ~HIGH_BIT; - assert(base >= 2); + CRYPTOPP_ASSERT(base >= 2); if (value == 0) return "0"; @@ -672,7 +754,7 @@ inline unsigned int TrailingZeros(word32 v) // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors // We don't enable for Microsoft because it requires a runtime check. // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx - assert(v != 0); + CRYPTOPP_ASSERT(v != 0); #if defined(__GNUC__) && defined(__BMI__) return (unsigned int)_tzcnt_u32(v); #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400) @@ -703,7 +785,7 @@ inline unsigned int TrailingZeros(word64 v) // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors // We don't enable for Microsoft because it requires a runtime check. // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx - assert(v != 0); + CRYPTOPP_ASSERT(v != 0); #if defined(__GNUC__) && defined(__BMI__) && defined(__x86_64__) return (unsigned int)_tzcnt_u64(v); #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400) @@ -835,7 +917,7 @@ inline bool IsPowerOf2(const word64 &value) template inline T2 ModPowerOf2(const T1 &a, const T2 &b) { - assert(IsPowerOf2(b)); + CRYPTOPP_ASSERT(IsPowerOf2(b)); return T2(a) & (b-1); } @@ -1020,7 +1102,7 @@ CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler(); //! \note The function is not constant time because it stops processing when the carry is 0. inline void IncrementCounterByOne(byte *inout, unsigned int size) { - assert(inout != NULL); assert(size < INT_MAX); + CRYPTOPP_ASSERT(inout != NULL); CRYPTOPP_ASSERT(size < INT_MAX); for (int i=int(size-1), carry=1; i>=0 && carry; i--) carry = !++inout[i]; } @@ -1034,7 +1116,7 @@ inline void IncrementCounterByOne(byte *inout, unsigned int size) //! \details The function is \a close to near-constant time because it operates on all the bytes in the blocks. inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size) { - assert(output != NULL); assert(input != NULL); assert(size < INT_MAX); + CRYPTOPP_ASSERT(output != NULL); CRYPTOPP_ASSERT(input != NULL); CRYPTOPP_ASSERT(size < INT_MAX); int i, carry; for (i=int(size-1), carry=1; i>=0 && carry; i--) @@ -1210,7 +1292,7 @@ std::string StringNarrow(const wchar_t *str, bool throwOnError = true); #else static std::string StringNarrow(const wchar_t *str, bool throwOnError = true) { - assert(str); + CRYPTOPP_ASSERT(str); std::string result; // Safer functions on Windows for C&A, https://github.com/weidai11/cryptopp/issues/55 @@ -1223,12 +1305,12 @@ static std::string StringNarrow(const wchar_t *str, bool throwOnError = true) len = wcslen(str)+1; err = wcstombs_s(&size, NULL, 0, str, len*sizeof(wchar_t)); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); if (err != 0) {goto CONVERSION_ERROR;} result.resize(size); err = wcstombs_s(&size, &result[0], size, str, len*sizeof(wchar_t)); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); if (err != 0) { @@ -1244,12 +1326,12 @@ CONVERSION_ERROR: result.erase(size - 1); #else size_t size = wcstombs(NULL, str, 0); - assert(size != (size_t)-1); + CRYPTOPP_ASSERT(size != (size_t)-1); if (size == (size_t)-1) {goto CONVERSION_ERROR;} result.resize(size); size = wcstombs(&result[0], str, size); - assert(size != (size_t)-1); + CRYPTOPP_ASSERT(size != (size_t)-1); if (size == (size_t)-1) { @@ -1318,7 +1400,7 @@ template inline T rotlFixed(T x, unsigned int y) // and https://llvm.org/bugs/show_bug.cgi?id=24226 static const unsigned int THIS_SIZE = sizeof(T)*8; static const unsigned int MASK = THIS_SIZE-1; - assert(y < THIS_SIZE); + CRYPTOPP_ASSERT(y < THIS_SIZE); return T((x<>(-y&MASK))); } @@ -1340,7 +1422,7 @@ template inline T rotrFixed(T x, unsigned int y) // and https://llvm.org/bugs/show_bug.cgi?id=24226 static const unsigned int THIS_SIZE = sizeof(T)*8; static const unsigned int MASK = THIS_SIZE-1; - assert(y < THIS_SIZE); + CRYPTOPP_ASSERT(y < THIS_SIZE); return T((x >> y)|(x<<(-y&MASK))); } @@ -1358,7 +1440,7 @@ template inline T rotlVariable(T x, unsigned int y) { static const unsigned int THIS_SIZE = sizeof(T)*8; static const unsigned int MASK = THIS_SIZE-1; - assert(y < THIS_SIZE); + CRYPTOPP_ASSERT(y < THIS_SIZE); return T((x<>(-y&MASK))); } @@ -1376,7 +1458,7 @@ template inline T rotrVariable(T x, unsigned int y) { static const unsigned int THIS_SIZE = sizeof(T)*8; static const unsigned int MASK = THIS_SIZE-1; - assert(y < THIS_SIZE); + CRYPTOPP_ASSERT(y < THIS_SIZE); return T((x>>y)|(x<<(-y&MASK))); } @@ -1417,11 +1499,11 @@ template inline T rotrMod(T x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotl provided by //! . The value x to be rotated is 32-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotlFixed will assert in Debug builds if is outside the allowed range. +//! \note rotlFixed will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word32 rotlFixed(word32 x, unsigned int y) { // Uses Microsoft call, bound to C/C++ language rules. - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _lrotl(x, static_cast(y)) : x; } @@ -1432,11 +1514,11 @@ template<> inline word32 rotlFixed(word32 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotr provided by //! . The value x to be rotated is 32-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotrFixed will assert in Debug builds if is outside the allowed range. +//! \note rotrFixed will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word32 rotrFixed(word32 x, unsigned int y) { // Uses Microsoft call, bound to C/C++ language rules. - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _lrotr(x, static_cast(y)) : x; } @@ -1447,10 +1529,10 @@ template<> inline word32 rotrFixed(word32 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotl provided by //! . The value x to be rotated is 32-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotlVariable will assert in Debug builds if is outside the allowed range. +//! \note rotlVariable will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word32 rotlVariable(word32 x, unsigned int y) { - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return _lrotl(x, static_cast(y)); } @@ -1461,10 +1543,10 @@ template<> inline word32 rotlVariable(word32 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotr provided by //! . The value x to be rotated is 32-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotrVariable will assert in Debug builds if is outside the allowed range. +//! \note rotrVariable will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word32 rotrVariable(word32 x, unsigned int y) { - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return _lrotr(x, static_cast(y)); } @@ -1506,11 +1588,11 @@ template<> inline word32 rotrMod(word32 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotl provided by //! . The value x to be rotated is 64-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotrFixed will assert in Debug builds if is outside the allowed range. +//! \note rotrFixed will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word64 rotlFixed(word64 x, unsigned int y) { // Uses Microsoft call, bound to C/C++ language rules. - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _rotl64(x, static_cast(y)) : x; } @@ -1521,11 +1603,11 @@ template<> inline word64 rotlFixed(word64 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotr provided by //! . The value x to be rotated is 64-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotrFixed will assert in Debug builds if is outside the allowed range. +//! \note rotrFixed will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word64 rotrFixed(word64 x, unsigned int y) { // Uses Microsoft call, bound to C/C++ language rules. - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _rotr64(x, static_cast(y)) : x; } @@ -1536,10 +1618,10 @@ template<> inline word64 rotrFixed(word64 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotl provided by //! . The value x to be rotated is 64-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotlVariable will assert in Debug builds if is outside the allowed range. +//! \note rotlVariable will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word64 rotlVariable(word64 x, unsigned int y) { - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return _rotl64(x, static_cast(y)); } @@ -1550,10 +1632,10 @@ template<> inline word64 rotlVariable(word64 x, unsigned int y) //! \details This is a Microsoft specific implementation using _lrotr provided by //! . The value x to be rotated is 64-bits. y must be in the range //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. -//! \note rotrVariable will assert in Debug builds if is outside the allowed range. +//! \note rotrVariable will CRYPTOPP_ASSERT in Debug builds if is outside the allowed range. template<> inline word64 rotrVariable(word64 x, unsigned int y) { - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _rotr64(x, static_cast(y)) : x; } @@ -1566,7 +1648,7 @@ template<> inline word64 rotrVariable(word64 x, unsigned int y) //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. template<> inline word64 rotlMod(word64 x, unsigned int y) { - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _rotl64(x, static_cast(y)) : x; } @@ -1579,7 +1661,7 @@ template<> inline word64 rotlMod(word64 x, unsigned int y) //! [0, sizeof(T)*8 - 1] to avoid undefined behavior. template<> inline word64 rotrMod(word64 x, unsigned int y) { - assert(y < 8*sizeof(x)); + CRYPTOPP_ASSERT(y < 8*sizeof(x)); return y ? _rotr64(x, static_cast(y)) : x; } @@ -1658,25 +1740,25 @@ template<> inline byte rotrMod(byte x, unsigned int y) template<> inline word32 rotlFixed(word32 x, unsigned int y) { - assert(y < 32); + CRYPTOPP_ASSERT(y < 32); return y ? __rlwinm(x,y,0,31) : x; } template<> inline word32 rotrFixed(word32 x, unsigned int y) { - assert(y < 32); + CRYPTOPP_ASSERT(y < 32); return y ? __rlwinm(x,32-y,0,31) : x; } template<> inline word32 rotlVariable(word32 x, unsigned int y) { - assert(y < 32); + CRYPTOPP_ASSERT(y < 32); return (__rlwnm(x,y,0,31)); } template<> inline word32 rotrVariable(word32 x, unsigned int y) { - assert(y < 32); + CRYPTOPP_ASSERT(y < 32); return (__rlwnm(x,32-y,0,31)); } @@ -1841,7 +1923,7 @@ inline T BitReverse(T value) return (T)BitReverse((word32)value); else { - assert(sizeof(T) == 8); + CRYPTOPP_ASSERT(sizeof(T) == 8); return (T)BitReverse((word64)value); } } @@ -1897,7 +1979,7 @@ inline T ConditionalByteReverse(ByteOrder order, T value) template void ByteReverse(T *out, const T *in, size_t byteCount) { - assert(byteCount % sizeof(T) == 0); + CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0); size_t count = byteCount/sizeof(T); for (size_t i=0; i inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen) { const size_t U = sizeof(T); - assert(inlen <= outlen*U); + CRYPTOPP_ASSERT(inlen <= outlen*U); memcpy_s(out, outlen*U, in, inlen); memset_z((byte *)out+inlen, 0, outlen*U-inlen); ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U)); @@ -2114,7 +2196,7 @@ inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block) //#ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS // if (!assumeAligned) // return UnalignedGetWordNonTemplate(order, block, (T*)NULL); -// assert(IsAligned(block)); +// CRYPTOPP_ASSERT(IsAligned(block)); //#endif // return ConditionalByteReverse(order, *reinterpret_cast(block)); CRYPTOPP_UNUSED(assumeAligned); @@ -2139,8 +2221,8 @@ inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, c //#ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS // if (!assumeAligned) // return UnalignedbyteNonTemplate(order, block, value, xorBlock); -// assert(IsAligned(block)); -// assert(IsAligned(xorBlock)); +// CRYPTOPP_ASSERT(IsAligned(block)); +// CRYPTOPP_ASSERT(IsAligned(xorBlock)); //#endif // *reinterpret_cast(block) = ConditionalByteReverse(order, value) ^ (xorBlock ? *reinterpret_cast(xorBlock) : 0); CRYPTOPP_UNUSED(assumeAligned); diff --git a/modes.cpp b/modes.cpp index ed2b3224..09d6fd13 100644 --- a/modes.cpp +++ b/modes.cpp @@ -35,10 +35,10 @@ void CipherModeBase::ResizeBuffers() void CFB_ModePolicy::Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount) { - assert(input); - assert(output); - assert(m_cipher->IsForwardTransformation()); // CFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt - assert(m_feedbackSize == BlockSize()); + CRYPTOPP_ASSERT(input); + CRYPTOPP_ASSERT(output); + CRYPTOPP_ASSERT(m_cipher->IsForwardTransformation()); // CFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt + CRYPTOPP_ASSERT(m_feedbackSize == BlockSize()); const unsigned int s = BlockSize(); if (dir == ENCRYPTION) @@ -60,7 +60,7 @@ void CFB_ModePolicy::Iterate(byte *output, const byte *input, CipherDir dir, siz void CFB_ModePolicy::TransformRegister() { - assert(m_cipher->IsForwardTransformation()); // CFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt + CRYPTOPP_ASSERT(m_cipher->IsForwardTransformation()); // CFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt m_cipher->ProcessBlock(m_register, m_temp); unsigned int updateSize = BlockSize()-m_feedbackSize; memmove_s(m_register, m_register.size(), m_register+m_feedbackSize, updateSize); @@ -69,7 +69,7 @@ void CFB_ModePolicy::TransformRegister() void CFB_ModePolicy::CipherResynchronize(const byte *iv, size_t length) { - assert(length == BlockSize()); + CRYPTOPP_ASSERT(length == BlockSize()); CopyOrZero(m_register, iv, length); TransformRegister(); } @@ -89,7 +89,7 @@ void CFB_ModePolicy::ResizeBuffers() void OFB_ModePolicy::WriteKeystream(byte *keystreamBuffer, size_t iterationCount) { - assert(m_cipher->IsForwardTransformation()); // OFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt + CRYPTOPP_ASSERT(m_cipher->IsForwardTransformation()); // OFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt unsigned int s = BlockSize(); m_cipher->ProcessBlock(m_register, keystreamBuffer); if (iterationCount > 1) @@ -100,7 +100,7 @@ void OFB_ModePolicy::WriteKeystream(byte *keystreamBuffer, size_t iterationCount void OFB_ModePolicy::CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length); - assert(length == BlockSize()); + CRYPTOPP_ASSERT(length == BlockSize()); CopyOrZero(m_register, iv, length); } @@ -124,7 +124,7 @@ void CTR_ModePolicy::IncrementCounterBy256() void CTR_ModePolicy::OperateKeystream(KeystreamOperation /*operation*/, byte *output, const byte *input, size_t iterationCount) { - assert(m_cipher->IsForwardTransformation()); // CTR mode needs the "encrypt" direction of the underlying block cipher, even to decrypt + CRYPTOPP_ASSERT(m_cipher->IsForwardTransformation()); // CTR mode needs the "encrypt" direction of the underlying block cipher, even to decrypt unsigned int s = BlockSize(); unsigned int inputIncrement = input ? s : 0; @@ -145,7 +145,7 @@ void CTR_ModePolicy::OperateKeystream(KeystreamOperation /*operation*/, byte *ou void CTR_ModePolicy::CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length); - assert(length == BlockSize()); + CRYPTOPP_ASSERT(length == BlockSize()); CopyOrZero(m_register, iv, length); m_counterArray = m_register; @@ -174,7 +174,7 @@ void BlockOrientedCipherModeBase::ResizeBuffers() void ECB_OneWay::ProcessData(byte *outString, const byte *inString, size_t length) { - assert(length%BlockSize()==0); + CRYPTOPP_ASSERT(length%BlockSize()==0); m_cipher->AdvancedProcessBlocks(inString, NULL, outString, length, BlockTransformation::BT_AllowParallel); } @@ -182,7 +182,7 @@ void CBC_Encryption::ProcessData(byte *outString, const byte *inString, size_t l { if (!length) return; - assert(length%BlockSize()==0); + CRYPTOPP_ASSERT(length%BlockSize()==0); unsigned int blockSize = BlockSize(); m_cipher->AdvancedProcessBlocks(inString, m_register, outString, blockSize, BlockTransformation::BT_XorInput); @@ -231,7 +231,7 @@ void CBC_Decryption::ProcessData(byte *outString, const byte *inString, size_t l { if (!length) return; - assert(length%BlockSize()==0); + CRYPTOPP_ASSERT(length%BlockSize()==0); unsigned int blockSize = BlockSize(); memcpy(m_temp, inString+length-blockSize, blockSize); // save copy now in case of in-place decryption diff --git a/modes.h b/modes.h index 01ea4bfe..ceac7ce2 100644 --- a/modes.h +++ b/modes.h @@ -66,7 +66,7 @@ public: protected: CipherModeBase() : m_cipher(NULL) {} - inline unsigned int BlockSize() const {assert(m_register.size() > 0); return (unsigned int)m_register.size();} + inline unsigned int BlockSize() const {CRYPTOPP_ASSERT(m_register.size() > 0); return (unsigned int)m_register.size();} virtual void SetFeedbackSize(unsigned int feedbackSize) { if (!(feedbackSize == 0 || feedbackSize == BlockSize())) diff --git a/nbtheory.cpp b/nbtheory.cpp index 6e2d33a3..d7a4a159 100644 --- a/nbtheory.cpp +++ b/nbtheory.cpp @@ -75,7 +75,7 @@ bool TrialDivision(const Integer &p, unsigned bound) unsigned int primeTableSize; const word16 * primeTable = GetPrimeTable(primeTableSize); - assert(primeTable[primeTableSize-1] >= bound); + CRYPTOPP_ASSERT(primeTable[primeTableSize-1] >= bound); unsigned int i; for (i = 0; primeTable[i]3 && b>1 && b3 && b>1 && b3 && b>1 && b3 && b>1 && b3); + CRYPTOPP_ASSERT(n>3); Integer b; for (unsigned int i=0; i2); + CRYPTOPP_ASSERT(n>2); Integer b=3; unsigned int i=0; @@ -189,7 +189,7 @@ bool IsStrongLucasProbablePrime(const Integer &n) if (n.IsEven()) return n==2; - assert(n>2); + CRYPTOPP_ASSERT(n>2); Integer b=3; unsigned int i=0; @@ -310,7 +310,7 @@ PrimeSieve::PrimeSieve(const Integer &first, const Integer &last, const Integer bool PrimeSieve::NextCandidate(Integer &c) { bool safe = SafeConvert(std::find(m_sieve.begin()+m_next, m_sieve.end(), false) - m_sieve.begin(), m_next); - CRYPTOPP_UNUSED(safe); assert(safe); + CRYPTOPP_UNUSED(safe); CRYPTOPP_ASSERT(safe); if (m_next == m_sieve.size()) { m_first += long(m_sieve.size())*m_step; @@ -363,7 +363,7 @@ void PrimeSieve::DoSieve() } else { - assert(m_step%2==0); + CRYPTOPP_ASSERT(m_step%2==0); Integer qFirst = (m_first-m_delta) >> 1; Integer halfStep = m_step >> 1; for (unsigned int i = 0; i < primeTableSize; ++i) @@ -380,7 +380,7 @@ void PrimeSieve::DoSieve() bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector) { - assert(!equiv.IsNegative() && equiv < mod); + CRYPTOPP_ASSERT(!equiv.IsNegative() && equiv < mod); Integer gcd = GCD(equiv, mod); if (gcd != Integer::One()) @@ -420,7 +420,7 @@ bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Inte p = primeTable[primeTableSize-1]+1; } - assert(p > primeTable[primeTableSize-1]); + CRYPTOPP_ASSERT(p > primeTable[primeTableSize-1]); if (mod.IsOdd()) return FirstPrime(p, max, CRT(equiv, mod, 1, 2, 1), mod<<1, pSelector); @@ -444,8 +444,8 @@ bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Inte // the following two functions are based on code and comments provided by Preda Mihailescu static bool ProvePrime(const Integer &p, const Integer &q) { - assert(p < q*q*q); - assert(p % q == 1); + CRYPTOPP_ASSERT(p < q*q*q); + CRYPTOPP_ASSERT(p % q == 1); // this is the Quisquater test. Numbers p having passed the Lucas - Lehmer test // for q and verifying p < q^3 can only be built up of two factors, both = 1 mod q, @@ -459,7 +459,7 @@ static bool ProvePrime(const Integer &p, const Integer &q) unsigned int primeTableSize; const word16 * primeTable = GetPrimeTable(primeTableSize); - assert(primeTableSize >= 50); + CRYPTOPP_ASSERT(primeTableSize >= 50); for (int i=0; i<50; i++) { Integer b = a_exp_b_mod_c(primeTable[i], r, p); @@ -616,7 +616,7 @@ Integer ModularSquareRoot(const Integer &a, const Integer &p) b = tempb*y%p; } - assert(x.Squared()%p == a); + CRYPTOPP_ASSERT(x.Squared()%p == a); return x; } @@ -626,21 +626,21 @@ bool SolveModularQuadraticEquation(Integer &r1, Integer &r2, const Integer &a, c switch (Jacobi(D, p)) { default: - assert(false); // not reached + CRYPTOPP_ASSERT(false); // not reached return false; case -1: return false; case 0: r1 = r2 = (-b*(a+a).InverseMod(p)) % p; - assert(((r1.Squared()*a + r1*b + c) % p).IsZero()); + CRYPTOPP_ASSERT(((r1.Squared()*a + r1*b + c) % p).IsZero()); return true; case 1: Integer s = ModularSquareRoot(D, p); Integer t = (a+a).InverseMod(p); r1 = (s-b)*t % p; r2 = (-s-b)*t % p; - assert(((r1.Squared()*a + r1*b + c) % p).IsZero()); - assert(((r2.Squared()*a + r2*b + c) % p).IsZero()); + CRYPTOPP_ASSERT(((r1.Squared()*a + r1*b + c) % p).IsZero()); + CRYPTOPP_ASSERT(((r2.Squared()*a + r2*b + c) % p).IsZero()); return true; } } @@ -666,7 +666,7 @@ Integer ModularRoot(const Integer &a, const Integer &e, Integer dp = EuclideanMultiplicativeInverse(e, p-1); Integer dq = EuclideanMultiplicativeInverse(e, q-1); Integer u = EuclideanMultiplicativeInverse(p, q); - assert(!!dp && !!dq && !!u); + CRYPTOPP_ASSERT(!!dp && !!dq && !!u); return ModularRoot(a, dp, dq, p, q, u); } @@ -676,7 +676,7 @@ Integer GCDI(const Integer &x, const Integer &y) Integer a=x, b=y; unsigned k=0; - assert(!!a && !!b); + CRYPTOPP_ASSERT(!!a && !!b); while (a[0]==0 && b[0]==0) { @@ -711,14 +711,14 @@ Integer GCDI(const Integer &x, const Integer &y) break; default: - assert(false); + CRYPTOPP_ASSERT(false); } } } Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b) { - assert(b.Positive()); + CRYPTOPP_ASSERT(b.Positive()); if (a.Negative()) return EuclideanMultiplicativeInverse(a%b, b); @@ -786,7 +786,7 @@ Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b) int Jacobi(const Integer &aIn, const Integer &bIn) { - assert(bIn.IsOdd()); + CRYPTOPP_ASSERT(bIn.IsOdd()); Integer b = bIn, a = aIn%bIn; int result = 1; @@ -979,7 +979,7 @@ Integer Lucas(const Integer &n, const Integer &P, const Integer &modulus) continue; } - assert(em2 == 0); + CRYPTOPP_ASSERT(em2 == 0); // #9 e >>= 1; C = f(C, B, A); @@ -1038,8 +1038,8 @@ unsigned int DiscreteLogWorkFactor(unsigned int n) void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned int qbits) { // no prime exists for delta = -1, qbits = 4, and pbits = 5 - assert(qbits > 4); - assert(pbits > qbits); + CRYPTOPP_ASSERT(qbits > 4); + CRYPTOPP_ASSERT(pbits > qbits); if (qbits+1 == pbits) { @@ -1054,9 +1054,9 @@ void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, u while (sieve.NextCandidate(p)) { - assert(IsSmallPrime(p) || SmallDivisorsTest(p)); + CRYPTOPP_ASSERT(IsSmallPrime(p) || SmallDivisorsTest(p)); q = (p-delta) >> 1; - assert(IsSmallPrime(q) || SmallDivisorsTest(q)); + CRYPTOPP_ASSERT(IsSmallPrime(q) || SmallDivisorsTest(q)); if (FastProbablePrimeTest(q) && FastProbablePrimeTest(p) && IsPrime(q) && IsPrime(p)) { success = true; @@ -1071,11 +1071,11 @@ void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, u // g=4 always works, but this way we get the smallest quadratic residue (other than 1) for (g=2; Jacobi(g, p) != 1; ++g) {} // contributed by Walt Tuvell: g should be the following according to the Law of Quadratic Reciprocity - assert((p%8==1 || p%8==7) ? g==2 : (p%12==1 || p%12==11) ? g==3 : g==4); + CRYPTOPP_ASSERT((p%8==1 || p%8==7) ? g==2 : (p%12==1 || p%12==11) ? g==3 : g==4); } else { - assert(delta == -1); + CRYPTOPP_ASSERT(delta == -1); // find g such that g*g-4 is a quadratic non-residue, // and such that g has order q for (g=3; ; ++g) @@ -1103,11 +1103,11 @@ void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, u Integer h(rng, 2, p-2, Integer::ANY); g = a_exp_b_mod_c(h, (p-1)/q, p); } while (g <= 1); - assert(a_exp_b_mod_c(g, q, p)==1); + CRYPTOPP_ASSERT(a_exp_b_mod_c(g, q, p)==1); } else { - assert(delta==-1); + CRYPTOPP_ASSERT(delta==-1); do { Integer h(rng, 3, p-1, Integer::ANY); @@ -1115,7 +1115,7 @@ void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, u continue; g = Lucas((p+1)/q, h, p); } while (g <= 2); - assert(Lucas(q, g, p) == 2); + CRYPTOPP_ASSERT(Lucas(q, g, p) == 2); } } } diff --git a/network.cpp b/network.cpp index f1233250..70d98339 100644 --- a/network.cpp +++ b/network.cpp @@ -435,7 +435,7 @@ size_t NetworkSink::Put2(const byte *inString, size_t length, int messageEnd, bo { if (m_skipBytes) { - assert(length >= m_skipBytes); + CRYPTOPP_ASSERT(length >= m_skipBytes); inString += m_skipBytes; length -= m_skipBytes; } @@ -451,7 +451,7 @@ size_t NetworkSink::Put2(const byte *inString, size_t length, int messageEnd, bo if (m_buffer.CurrentSize() > targetSize) { - assert(!blocking); + CRYPTOPP_ASSERT(!blocking); m_wasBlocked = true; m_skipBytes += length; size_t blockedBytes = UnsignedMin(length, m_buffer.CurrentSize() - targetSize); diff --git a/oaep.cpp b/oaep.cpp index 64984f87..d2be610e 100644 --- a/oaep.cpp +++ b/oaep.cpp @@ -19,7 +19,7 @@ size_t OAEP_Base::MaxUnpaddedLength(size_t paddedLength) const void OAEP_Base::Pad(RandomNumberGenerator &rng, const byte *input, size_t inputLength, byte *oaepBlock, size_t oaepBlockLen, const NameValuePairs ¶meters) const { - assert (inputLength <= MaxUnpaddedLength(oaepBlockLen)); + CRYPTOPP_ASSERT (inputLength <= MaxUnpaddedLength(oaepBlockLen)); // convert from bit length to byte length if (oaepBlockLen % 8 != 0) diff --git a/panama.cpp b/panama.cpp index f10edbdc..32615c65 100644 --- a/panama.cpp +++ b/panama.cpp @@ -326,7 +326,7 @@ void CRYPTOPP_NOINLINE Panama_SSE2_Pull(size_t count, word32 *state, word32 *z, template void Panama::Iterate(size_t count, const word32 *p, byte *output, const byte *input, KeystreamOperation operation) { - assert(IsAlignedOn(m_state,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_state,GetAlignmentOf())); word32 bstart = m_state[17]; word32 *const aPtr = m_state; word32 cPtr[17]; @@ -452,7 +452,7 @@ template void PanamaCipherPolicy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length) { CRYPTOPP_UNUSED(params); CRYPTOPP_UNUSED(length); - assert(length==32); + CRYPTOPP_ASSERT(length==32); memcpy(m_key, key, 32); } @@ -460,8 +460,8 @@ template void PanamaCipherPolicy::CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer); CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(length); - assert(IsAlignedOn(iv,GetAlignmentOf())); - assert(length==32); + CRYPTOPP_ASSERT(IsAlignedOn(iv,GetAlignmentOf())); + CRYPTOPP_ASSERT(length==32); this->Reset(); this->Iterate(1, m_key); @@ -500,7 +500,7 @@ template void PanamaCipherPolicy::OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount) { #if (CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_PANAMA_ASM) - // No need for alignment assert. Panama_SSE2_Pull is ASM, and its not bound by C alignment requirements. + // No need for alignment CRYPTOPP_ASSERT. Panama_SSE2_Pull is ASM, and its not bound by C alignment requirements. if (B::ToEnum() == LITTLE_ENDIAN_ORDER && HasSSE2()) Panama_SSE2_Pull(iterationCount, this->m_state, (word32 *)(void *)output, (const word32 *)(void *)input); else diff --git a/pkcspad.cpp b/pkcspad.cpp index 85eac6ae..7716256f 100644 --- a/pkcspad.cpp +++ b/pkcspad.cpp @@ -7,7 +7,7 @@ #include "pkcspad.h" #include "misc.h" -#include +#include "trap.h" NAMESPACE_BEGIN(CryptoPP) @@ -32,7 +32,7 @@ size_t PKCS_EncryptionPaddingScheme::MaxUnpaddedLength(size_t paddedLength) cons void PKCS_EncryptionPaddingScheme::Pad(RandomNumberGenerator& rng, const byte *input, size_t inputLen, byte *pkcsBlock, size_t pkcsBlockLen, const NameValuePairs& parameters) const { CRYPTOPP_UNUSED(parameters); - assert (inputLen <= MaxUnpaddedLength(pkcsBlockLen)); // this should be checked by caller + CRYPTOPP_ASSERT (inputLen <= MaxUnpaddedLength(pkcsBlockLen)); // this should be checked by caller // convert from bit length to byte length if (pkcsBlockLen % 8 != 0) @@ -73,7 +73,7 @@ DecodingResult PKCS_EncryptionPaddingScheme::Unpad(const byte *pkcsBlock, size_t size_t i=1; while (i maxOutputLen) || invalid; @@ -96,7 +96,7 @@ void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(Rando { CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength); CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier); - assert(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); + CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); size_t pkcsBlockLen = representativeBitLength; // convert from bit length to byte length diff --git a/polynomi.cpp b/polynomi.cpp index bf8904c0..b88545bc 100644 --- a/polynomi.cpp +++ b/polynomi.cpp @@ -475,7 +475,7 @@ void RingOfPolynomialsOver::CalculateAlpha(std::vector &alph template typename RingOfPolynomialsOver::Element RingOfPolynomialsOver::Interpolate(const CoefficientType x[], const CoefficientType y[], unsigned int n) const { - assert(n > 0); + CRYPTOPP_ASSERT(n > 0); std::vector alpha(n); CalculateAlpha(alpha, x, y, n); @@ -497,7 +497,7 @@ typename RingOfPolynomialsOver::Element RingOfPolynomialsOver::Interpolate template typename RingOfPolynomialsOver::CoefficientType RingOfPolynomialsOver::InterpolateAt(const CoefficientType &position, const CoefficientType x[], const CoefficientType y[], unsigned int n) const { - assert(n > 0); + CRYPTOPP_ASSERT(n > 0); std::vector alpha(n); CalculateAlpha(alpha, x, y, n); @@ -527,7 +527,7 @@ void PrepareBulkPolynomialInterpolation(const Ring &ring, Element *w, const Elem template void PrepareBulkPolynomialInterpolationAt(const Ring &ring, Element *v, const Element &position, const Element x[], const Element w[], unsigned int n) { - assert(n > 0); + CRYPTOPP_ASSERT(n > 0); std::vector a(2*n-1); unsigned int i; diff --git a/pssr.cpp b/pssr.cpp index 4f9339ff..559408da 100644 --- a/pssr.cpp +++ b/pssr.cpp @@ -51,7 +51,7 @@ void PSSR_MEM_Base::ComputeMessageRepresentative(RandomNumberGenerator &rng, { CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength); CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier); - assert(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); + CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); const size_t u = hashIdentifier.second + 1; const size_t representativeByteLength = BitsToBytes(representativeBitLength); @@ -99,7 +99,7 @@ DecodingResult PSSR_MEM_Base::RecoverMessageFromRepresentative( byte *recoverableMessage) const { CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier); - assert(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); + CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); const size_t u = hashIdentifier.second + 1; const size_t representativeByteLength = BitsToBytes(representativeBitLength); diff --git a/pubkey.h b/pubkey.h index 7f4cbb3c..a2032612 100644 --- a/pubkey.h +++ b/pubkey.h @@ -29,7 +29,7 @@ //! //! //! \details The \p TF_ prefix means an implementation using trapdoor functions on integers. -//! \details The \p DL_ prefix means an implementation using group operations (in groups where discrete log is hard). +//! \details The \p DL_ prefix means an implementation using group operations in groups where discrete log is hard. #ifndef CRYPTOPP_PUBKEY_H #define CRYPTOPP_PUBKEY_H @@ -56,9 +56,9 @@ #undef INTERFACE #if defined(__SUNPRO_CC) -# define MAYBE_RETURN_FOR_SOLARIS(x) return x +# define MAYBE_RETURN(x) return x #else -# define MAYBE_RETURN_FOR_SOLARIS(x) CRYPTOPP_UNUSED(x) +# define MAYBE_RETURN(x) CRYPTOPP_UNUSED(x) #endif NAMESPACE_BEGIN(CryptoPP) @@ -365,7 +365,7 @@ public: CRYPTOPP_UNUSED(hash);CRYPTOPP_UNUSED(recoverableMessage); CRYPTOPP_UNUSED(recoverableMessageLength); CRYPTOPP_UNUSED(presignature); CRYPTOPP_UNUSED(presignatureLength); CRYPTOPP_UNUSED(semisignature); if (RecoverablePartFirst()) - assert(!"ProcessRecoverableMessage() not implemented"); + CRYPTOPP_ASSERT(!"ProcessRecoverableMessage() not implemented"); } virtual void ComputeMessageRepresentative(RandomNumberGenerator &rng, @@ -1314,7 +1314,7 @@ public: { CRYPTOPP_UNUSED(params); CRYPTOPP_UNUSED(publicKey); CRYPTOPP_UNUSED(r); CRYPTOPP_UNUSED(s); throw NotImplemented("DL_ElgamalLikeSignatureAlgorithm: this signature scheme does not support message recovery"); - MAYBE_RETURN_FOR_SOLARIS(Integer::Zero()); + MAYBE_RETURN(Integer::Zero()); } virtual size_t RLen(const DL_GroupParameters ¶ms) const {return params.GetSubgroupOrder().ByteCount();} @@ -1420,7 +1420,7 @@ public: //! \returns maximum recoverable length based on signature length, in bytes //! \details this function is not implemented and always returns 0. size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const - {CRYPTOPP_UNUSED(signatureLength); assert(false); return 0;} // TODO + {CRYPTOPP_UNUSED(signatureLength); CRYPTOPP_ASSERT(false); return 0;} // TODO //! \brief Determines if the scheme is probabilistic //! \returns true if the scheme is probabilistic, false otherwise @@ -2006,7 +2006,7 @@ public: return params.ExponentiateElement(publicElement, privateExponent*params.GetCofactor()); else { - assert(COFACTOR_OPTION::ToEnum() == NO_COFACTOR_MULTIPLICTION); + CRYPTOPP_ASSERT(COFACTOR_OPTION::ToEnum() == NO_COFACTOR_MULTIPLICTION); if (!validateOtherPublicKey) return params.ExponentiateElement(publicElement, privateExponent); diff --git a/pwdbased.h b/pwdbased.h index 539c9a7e..cc0bcedb 100644 --- a/pwdbased.h +++ b/pwdbased.h @@ -83,8 +83,8 @@ template unsigned int PKCS5_PBKDF1::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const { CRYPTOPP_UNUSED(purpose); - assert(derivedLen <= MaxDerivedKeyLength()); - assert(iterations > 0 || timeInSeconds > 0); + CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength()); + CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0); if (!iterations) iterations = 1; @@ -113,8 +113,8 @@ template unsigned int PKCS5_PBKDF2_HMAC::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const { CRYPTOPP_UNUSED(purpose); - assert(derivedLen <= MaxDerivedKeyLength()); - assert(iterations > 0 || timeInSeconds > 0); + CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength()); + CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0); if (!iterations) iterations = 1; @@ -183,8 +183,8 @@ public: template unsigned int PKCS12_PBKDF::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const { - assert(derivedLen <= MaxDerivedKeyLength()); - assert(iterations > 0 || timeInSeconds > 0); + CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength()); + CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0); if (!iterations) iterations = 1; diff --git a/queue.cpp b/queue.cpp index 0569d18e..fd236381 100644 --- a/queue.cpp +++ b/queue.cpp @@ -464,7 +464,7 @@ byte ByteQueue::operator[](lword i) const i -= current->CurrentSize(); } - assert(i < m_lazyLength); + CRYPTOPP_ASSERT(i < m_lazyLength); return m_lazyString[i]; } diff --git a/queue.h b/queue.h index 88a3b8d4..e1ed4da6 100644 --- a/queue.h +++ b/queue.h @@ -132,7 +132,7 @@ public: LazyPutter(ByteQueue &bq, const byte *inString, size_t size) : m_bq(bq) {bq.LazyPut(inString, size);} ~LazyPutter() - {try {m_bq.FinalizeLazyPut();} catch(const Exception&) {assert(0);}} + {try {m_bq.FinalizeLazyPut();} catch(const Exception&) {CRYPTOPP_ASSERT(0);}} protected: LazyPutter(ByteQueue &bq) : m_bq(bq) {} private: diff --git a/rdrand.cpp b/rdrand.cpp index cc18cc43..36f0538c 100644 --- a/rdrand.cpp +++ b/rdrand.cpp @@ -163,7 +163,7 @@ NAMESPACE_BEGIN(CryptoPP) #if ALL_RDRAND_INTRIN_AVAILABLE static int ALL_RRI_GenerateBlock(byte *output, size_t size, unsigned int safety) { - assert((output && size) || !(output || size)); + CRYPTOPP_ASSERT((output && size) || !(output || size)); #if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 word32 val; #else @@ -186,7 +186,7 @@ static int ALL_RRI_GenerateBlock(byte *output, size_t size, unsigned int safety) { if (!safety--) { - assert(0); + CRYPTOPP_ASSERT(0); return 0; } } @@ -208,7 +208,7 @@ static int ALL_RRI_GenerateBlock(byte *output, size_t size, unsigned int safety) { if (!safety--) { - assert(0); + CRYPTOPP_ASSERT(0); return 0; } } @@ -223,7 +223,7 @@ static int ALL_RRI_GenerateBlock(byte *output, size_t size, unsigned int safety) #if GCC_RDRAND_ASM_AVAILABLE static int GCC_RRA_GenerateBlock(byte *output, size_t size, unsigned int safety) { - assert((output && size) || !(output || size)); + CRYPTOPP_ASSERT((output && size) || !(output || size)); #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 word64 val; #else @@ -268,7 +268,7 @@ static int GCC_RRA_GenerateBlock(byte *output, size_t size, unsigned int safety) { if (!safety--) { - assert(0); + CRYPTOPP_ASSERT(0); return 0; } } @@ -285,7 +285,7 @@ static int GCC_RRA_GenerateBlock(byte *output, size_t size, unsigned int safety) void RDRAND::GenerateBlock(byte *output, size_t size) { CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size); - assert((output && size) || !(output || size)); + CRYPTOPP_ASSERT((output && size) || !(output || size)); if(!HasRDRAND()) throw NotImplemented("RDRAND: rdrand is not available on this platform"); @@ -313,7 +313,7 @@ void RDRAND::DiscardBytes(size_t n) { // RoundUpToMultipleOf is used because a full word is read, and its cheaper // to discard full words. There's no sense in dealing with tail bytes. - assert(HasRDRAND()); + CRYPTOPP_ASSERT(HasRDRAND()); #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 FixedSizeSecBlock discard; n = RoundUpToMultipleOf(n, sizeof(word64)); @@ -338,7 +338,7 @@ void RDRAND::DiscardBytes(size_t n) #if ALL_RDSEED_INTRIN_AVAILABLE static int ALL_RSI_GenerateBlock(byte *output, size_t size, unsigned int safety) { - assert((output && size) || !(output || size)); + CRYPTOPP_ASSERT((output && size) || !(output || size)); #if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 word32 val; #else @@ -361,7 +361,7 @@ static int ALL_RSI_GenerateBlock(byte *output, size_t size, unsigned int safety) { if (!safety--) { - assert(0); + CRYPTOPP_ASSERT(0); return 0; } } @@ -383,7 +383,7 @@ static int ALL_RSI_GenerateBlock(byte *output, size_t size, unsigned int safety) { if (!safety--) { - assert(0); + CRYPTOPP_ASSERT(0); return 0; } } @@ -398,7 +398,7 @@ static int ALL_RSI_GenerateBlock(byte *output, size_t size, unsigned int safety) #if GCC_RDSEED_ASM_AVAILABLE static int GCC_RSA_GenerateBlock(byte *output, size_t size, unsigned int safety) { - assert((output && size) || !(output || size)); + CRYPTOPP_ASSERT((output && size) || !(output || size)); #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 word64 val; #else @@ -443,7 +443,7 @@ static int GCC_RSA_GenerateBlock(byte *output, size_t size, unsigned int safety) { if (!safety--) { - assert(0); + CRYPTOPP_ASSERT(0); return 0; } } @@ -459,7 +459,7 @@ static int GCC_RSA_GenerateBlock(byte *output, size_t size, unsigned int safety) void RDSEED::GenerateBlock(byte *output, size_t size) { CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size); - assert((output && size) || !(output || size)); + CRYPTOPP_ASSERT((output && size) || !(output || size)); if(!HasRDSEED()) throw NotImplemented("RDSEED: rdseed is not available on this platform"); @@ -487,7 +487,7 @@ void RDSEED::DiscardBytes(size_t n) { // RoundUpToMultipleOf is used because a full word is read, and its cheaper // to discard full words. There's no sense in dealing with tail bytes. - assert(HasRDSEED()); + CRYPTOPP_ASSERT(HasRDSEED()); #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 FixedSizeSecBlock discard; n = RoundUpToMultipleOf(n, sizeof(word64)); diff --git a/rdrand.h b/rdrand.h index 58a71319..45c20f71 100644 --- a/rdrand.h +++ b/rdrand.h @@ -103,7 +103,7 @@ public: { // Override to avoid the base class' throw. CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length); - // assert(0); // warn in debug builds + // CRYPTOPP_ASSERT(0); // warn in debug builds } private: @@ -187,7 +187,7 @@ public: { // Override to avoid the base class' throw. CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length); - // assert(0); // warn in debug builds + // CRYPTOPP_ASSERT(0); // warn in debug builds } private: diff --git a/rijndael.cpp b/rijndael.cpp index 0ba1a199..b4ca2d84 100644 --- a/rijndael.cpp +++ b/rijndael.cpp @@ -1128,7 +1128,7 @@ inline size_t AESNI_AdvancedProcessBlocks(F1 func1, F4 func4, MAYBE_CONST __m128 if (flags & BlockTransformation::BT_ReverseDirection) { - assert(length % blockSize == 0); + CRYPTOPP_ASSERT(length % blockSize == 0); inBlocks += length - blockSize; xorBlocks += length - blockSize; outBlocks += length - blockSize; @@ -1267,7 +1267,7 @@ size_t Rijndael::Enc::AdvancedProcessBlocks(const byte *inBlocks, const byte *xo size_t increment = BLOCKSIZE; if (flags & BT_ReverseDirection) { - assert(length % BLOCKSIZE == 0); + CRYPTOPP_ASSERT(length % BLOCKSIZE == 0); inBlocks += length - BLOCKSIZE; xorBlocks += length - BLOCKSIZE; outBlocks += length - BLOCKSIZE; diff --git a/rsa.cpp b/rsa.cpp index 3587fe80..fd0a17d8 100644 --- a/rsa.cpp +++ b/rsa.cpp @@ -108,13 +108,13 @@ void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const Nam int modulusSize = 2048; alg.GetIntValue(Name::ModulusSize(), modulusSize) || alg.GetIntValue(Name::KeySize(), modulusSize); - assert(modulusSize >= 16); + CRYPTOPP_ASSERT(modulusSize >= 16); if (modulusSize < 16) throw InvalidArgument("InvertibleRSAFunction: specified modulus size is too small"); m_e = alg.GetValueWithDefault(Name::PublicExponent(), Integer(17)); - assert(m_e >= 3); assert(!m_e.IsEven()); + CRYPTOPP_ASSERT(m_e >= 3); CRYPTOPP_ASSERT(!m_e.IsEven()); if (m_e < 3 || m_e.IsEven()) throw InvalidArgument("InvertibleRSAFunction: invalid public exponent"); @@ -125,7 +125,7 @@ void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const Nam m_q.GenerateRandom(rng, primeParam); m_d = m_e.InverseMod(LCM(m_p-1, m_q-1)); - assert(m_d.IsPositive()); + CRYPTOPP_ASSERT(m_d.IsPositive()); m_dp = m_d % (m_p-1); m_dq = m_d % (m_q-1); diff --git a/rw.cpp b/rw.cpp index 784a0368..56584d59 100644 --- a/rw.cpp +++ b/rw.cpp @@ -239,7 +239,7 @@ Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const // Signature Integer s = modn.Multiply(modn.Square(Y), rInv); - assert((e * f * s.Squared()) % m_n == x); + CRYPTOPP_ASSERT((e * f * s.Squared()) % m_n == x); // IEEE P1363, Section 8.2.8 IFSP-RW, p.44 s = STDMIN(s, m_n - s); diff --git a/salsa.cpp b/salsa.cpp index ddf779ae..85c33545 100644 --- a/salsa.cpp +++ b/salsa.cpp @@ -63,7 +63,7 @@ void Salsa20_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, void Salsa20_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length); - assert(length==8); + CRYPTOPP_ASSERT(length==8); GetBlock get(IV); get(m_state[14])(m_state[11]); @@ -592,7 +592,7 @@ void XSalsa20_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key void XSalsa20_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length); - assert(length==24); + CRYPTOPP_ASSERT(length==24); word32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; diff --git a/seal.cpp b/seal.cpp index 9babbfa1..d827c1d6 100644 --- a/seal.cpp +++ b/seal.cpp @@ -73,7 +73,7 @@ template void SEAL_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(IV), CRYPTOPP_UNUSED(length); - assert(length==4); + CRYPTOPP_ASSERT(length==4); m_outsideCounter = IV ? GetWord(false, BIG_ENDIAN_ORDER, IV) : 0; m_startCount = m_outsideCounter; @@ -93,7 +93,7 @@ void SEAL_Policy::OperateKeystream(KeystreamOperation operation, byte *output word32 a, b, c, d, n1, n2, n3, n4; unsigned int p, q; - assert(IsAlignedOn(m_T.begin(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_T.begin(),GetAlignmentOf())); for (size_t iteration = 0; iteration < iterationCount; ++iteration) { #define Ttab(x) *(word32 *)(void*)((byte *)m_T.begin()+x) diff --git a/secblock.h b/secblock.h index 375f8209..4cf97068 100644 --- a/secblock.h +++ b/secblock.h @@ -118,7 +118,7 @@ typedef typename AllocatorBase::const_reference const_reference; template typename A::pointer StandardReallocate(A& alloc, T *oldPtr, typename A::size_type oldSize, typename A::size_type newSize, bool preserve) { - assert((oldPtr && oldSize) || !(oldPtr || oldSize)); + CRYPTOPP_ASSERT((oldPtr && oldSize) || !(oldPtr || oldSize)); if (oldSize == newSize) return oldPtr; @@ -164,13 +164,13 @@ public: //! \details AlignedAllocate() is used if T_Align16 is true. //! UnalignedAllocate() used if T_Align16 is false. //! \details This is the C++ *Placement New* operator. ptr is not used, and the function - //! asserts in Debug builds if ptr is non-NULL. + //! CRYPTOPP_ASSERTs in Debug builds if ptr is non-NULL. //! \sa CallNewHandler() for the methods used to recover from a failed //! allocation attempt. //! \note size is the count of elements, and not the number of bytes pointer allocate(size_type size, const void *ptr = NULL) { - CRYPTOPP_UNUSED(ptr); assert(ptr == NULL); + CRYPTOPP_UNUSED(ptr); CRYPTOPP_ASSERT(ptr == NULL); this->CheckSize(size); if (size == 0) return NULL; @@ -194,7 +194,7 @@ public: //! UnalignedDeallocate() used if T_Align16 is false. void deallocate(void *ptr, size_type size) { - assert((ptr && size) || !(ptr || size)); + CRYPTOPP_ASSERT((ptr && size) || !(ptr || size)); SecureWipeArray((pointer)ptr, size); #if CRYPTOPP_BOOL_ALIGN16 @@ -220,7 +220,7 @@ public: //! number of bytes. pointer reallocate(T *oldPtr, size_type oldSize, size_type newSize, bool preserve) { - assert((oldPtr && oldSize) || !(oldPtr || oldSize)); + CRYPTOPP_ASSERT((oldPtr && oldSize) || !(oldPtr || oldSize)); return StandardReallocate(*this, oldPtr, oldSize, newSize, preserve); } @@ -272,13 +272,13 @@ public: pointer allocate(size_type n, const void* unused = NULL) { CRYPTOPP_UNUSED(n); CRYPTOPP_UNUSED(unused); - assert(false); return NULL; + CRYPTOPP_ASSERT(false); return NULL; } void deallocate(void *p, size_type n) { CRYPTOPP_UNUSED(p); CRYPTOPP_UNUSED(n); - assert(false); + CRYPTOPP_ASSERT(false); } CRYPTOPP_CONSTEXPR size_type max_size() const {return 0;} @@ -320,7 +320,7 @@ public: //! \sa reallocate(), SecBlockWithHint pointer allocate(size_type size) { - assert(IsAlignedOn(m_array, 8)); + CRYPTOPP_ASSERT(IsAlignedOn(m_array, 8)); if (size <= S && !m_allocated) { @@ -367,8 +367,8 @@ public: { if (ptr == GetAlignedArray()) { - assert(size <= S); - assert(m_allocated); + CRYPTOPP_ASSERT(size <= S); + CRYPTOPP_ASSERT(m_allocated); m_allocated = false; SecureWipeArray((pointer)ptr, size); } @@ -397,7 +397,7 @@ public: { if (oldPtr == GetAlignedArray() && newSize <= S) { - assert(oldSize <= S); + CRYPTOPP_ASSERT(oldSize <= S); if (oldSize > newSize) SecureWipeArray(oldPtr+newSize, oldSize-newSize); return oldPtr; @@ -455,7 +455,7 @@ public: //! \throws std::bad_alloc SecBlock(const SecBlock &t) : m_size(t.m_size), m_ptr(m_alloc.allocate(t.m_size, NULL)) { - assert((!t.m_ptr && !m_size) || (t.m_ptr && m_size)); + CRYPTOPP_ASSERT((!t.m_ptr && !m_size) || (t.m_ptr && m_size)); if (t.m_ptr) {memcpy_s(m_ptr, m_size*sizeof(T), t.m_ptr, t.m_size*sizeof(T));} } @@ -469,7 +469,7 @@ public: //! \note size is the count of elements, and not the number of bytes SecBlock(const T *ptr, size_type len) : m_size(len), m_ptr(m_alloc.allocate(len, NULL)) { - assert((!m_ptr && !m_size) || (m_ptr && m_size)); + CRYPTOPP_ASSERT((!m_ptr && !m_size) || (m_ptr && m_size)); if (ptr && m_ptr) memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T)); else if (m_size) @@ -578,7 +578,7 @@ public: //! \details Internally, this SecBlock calls Grow and then appends t. SecBlock& operator+=(const SecBlock &t) { - assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size)); + CRYPTOPP_ASSERT((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size)); if(t.m_size) { @@ -603,8 +603,8 @@ public: //! \details Internally, a new SecBlock is created from this and a concatenation of t. SecBlock operator+(const SecBlock &t) { - assert((!m_ptr && !m_size) || (m_ptr && m_size)); - assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size)); + CRYPTOPP_ASSERT((!m_ptr && !m_size) || (m_ptr && m_size)); + CRYPTOPP_ASSERT((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size)); if(!t.m_size) return SecBlock(*this); SecBlock result(m_size+t.m_size); diff --git a/sha.cpp b/sha.cpp index 2b74b312..f02c0e19 100644 --- a/sha.cpp +++ b/sha.cpp @@ -886,8 +886,8 @@ CRYPTOPP_NAKED static void CRYPTOPP_FASTCALL SHA512_SSE2_Transform(word64 *state void SHA512::Transform(word64 *state, const word64 *data) { - assert(IsAlignedOn(state, GetAlignmentOf())); - assert(IsAlignedOn(data, GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(state, GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(data, GetAlignmentOf())); #if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE && (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32) if (HasSSE2()) diff --git a/sha3.cpp b/sha3.cpp index 4e383479..435cbd56 100644 --- a/sha3.cpp +++ b/sha3.cpp @@ -251,7 +251,7 @@ static void KeccakF1600(word64 *state) void SHA3::Update(const byte *input, size_t length) { - assert((input && length) || !(input || length)); + CRYPTOPP_ASSERT((input && length) || !(input || length)); if (!length) return; diff --git a/shark.cpp b/shark.cpp index 99d63d21..b9bd1307 100644 --- a/shark.cpp +++ b/shark.cpp @@ -96,7 +96,7 @@ template struct SharkProcessAndXorBlock{ // VC60 workaround: problem with template functions inline SharkProcessAndXorBlock(const word64 *roundKeys, unsigned int rounds, const byte *inBlock, const byte *xorBlock, byte *outBlock) { - assert(IsAlignedOn(inBlock,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(inBlock,GetAlignmentOf())); word64 tmp = *(word64 *)(void *)inBlock ^ roundKeys[0]; ByteOrder order = GetNativeByteOrder(); @@ -125,7 +125,7 @@ inline SharkProcessAndXorBlock(const word64 *roundKeys, unsigned int rounds, con (sbox[GETBYTE(tmp, 1)]) (sbox[GETBYTE(tmp, 0)]); - assert(IsAlignedOn(outBlock,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(outBlock,GetAlignmentOf())); *(word64 *)(void *)outBlock ^= roundKeys[rounds]; }}; diff --git a/simple.h b/simple.h index 0c181124..afe06c75 100644 --- a/simple.h +++ b/simple.h @@ -97,7 +97,7 @@ public: bool Flush(bool completeFlush, int propagation=-1, bool blocking=true) {return ChannelFlush(DEFAULT_CHANNEL, completeFlush, propagation, blocking);} bool IsolatedFlush(bool hardFlush, bool blocking) - {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); assert(false); return false;} + {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); CRYPTOPP_ASSERT(false); return false;} bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true) { if (hardFlush && !InputBufferIsEmpty()) @@ -167,7 +167,7 @@ public: private: bool IsolatedFlush(bool hardFlush, bool blocking) - {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); assert(false); return false;} + {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); CRYPTOPP_ASSERT(false); return false;} }; //! \class CustomSignalPropagation @@ -182,7 +182,7 @@ public: private: void IsolatedInitialize(const NameValuePairs ¶meters) - {CRYPTOPP_UNUSED(parameters); assert(false);} + {CRYPTOPP_UNUSED(parameters); CRYPTOPP_ASSERT(false);} }; //! \class Multichannel diff --git a/smartptr.h b/smartptr.h index 1d08bf2d..38e1aeef 100644 --- a/smartptr.h +++ b/smartptr.h @@ -238,9 +238,9 @@ public: {delete [] m_ptr;} T& operator[](size_t index) - {assert(m_size && indexm_size); return this->m_ptr[index];} + {CRYPTOPP_ASSERT(m_size && indexm_size); return this->m_ptr[index];} const T& operator[](size_t index) const - {assert(m_size && indexm_size); return this->m_ptr[index];} + {CRYPTOPP_ASSERT(m_size && indexm_size); return this->m_ptr[index];} size_t size() const {return this->m_size;} void resize(size_t newSize) @@ -293,9 +293,9 @@ public: {delete [] this->m_ptr;} member_ptr& operator[](size_t index) - {assert(indexm_size); return this->m_ptr[index];} + {CRYPTOPP_ASSERT(indexm_size); return this->m_ptr[index];} const member_ptr& operator[](size_t index) const - {assert(indexm_size); return this->m_ptr[index];} + {CRYPTOPP_ASSERT(indexm_size); return this->m_ptr[index];} size_t size() const {return this->m_size;} void resize(size_t newSize) diff --git a/socketft.cpp b/socketft.cpp index ff6e0d40..f9b5bd66 100644 --- a/socketft.cpp +++ b/socketft.cpp @@ -68,7 +68,7 @@ Socket::~Socket() } catch (const Exception&) { - assert(0); + CRYPTOPP_ASSERT(0); } } } @@ -93,7 +93,7 @@ socket_t Socket::DetachSocket() void Socket::Create(int nType) { - assert(m_s == INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s == INVALID_SOCKET); m_s = socket(AF_INET, nType, 0); CheckAndHandleError("socket", m_s); m_own = true; @@ -107,12 +107,12 @@ void Socket::CloseSocket() #ifdef USE_WINDOWS_STYLE_SOCKETS # if defined(USE_WINDOWS8_API) BOOL result = CancelIoEx((HANDLE) m_s, NULL); - assert(result || (!result && GetLastError() == ERROR_NOT_FOUND)); + CRYPTOPP_ASSERT(result || (!result && GetLastError() == ERROR_NOT_FOUND)); CheckAndHandleError_int("closesocket", closesocket(m_s)); - CRYPTOPP_UNUSED(result); // Used by assert in debug builds + CRYPTOPP_UNUSED(result); // Used by CRYPTOPP_ASSERT in debug builds # else BOOL result = CancelIo((HANDLE) m_s); - assert(result || (!result && GetLastError() == ERROR_NOT_FOUND)); + CRYPTOPP_ASSERT(result || (!result && GetLastError() == ERROR_NOT_FOUND)); CheckAndHandleError_int("closesocket", closesocket(m_s)); CRYPTOPP_UNUSED(result); # endif @@ -150,20 +150,20 @@ void Socket::Bind(unsigned int port, const char *addr) void Socket::Bind(const sockaddr *psa, socklen_t saLen) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); // cygwin workaround: needs const_cast CheckAndHandleError_int("bind", bind(m_s, const_cast(psa), saLen)); } void Socket::Listen(int backlog) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); CheckAndHandleError_int("listen", listen(m_s, backlog)); } bool Socket::Connect(const char *addr, unsigned int port) { - assert(addr != NULL); + CRYPTOPP_ASSERT(addr != NULL); sockaddr_in sa; memset(&sa, 0, sizeof(sa)); @@ -180,7 +180,7 @@ bool Socket::Connect(const char *addr, unsigned int port) } else { - assert(IsAlignedOn(lphost->h_addr,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(lphost->h_addr,GetAlignmentOf())); sa.sin_addr.s_addr = ((in_addr *)(void *)lphost->h_addr)->s_addr; } } @@ -192,7 +192,7 @@ bool Socket::Connect(const char *addr, unsigned int port) bool Socket::Connect(const sockaddr* psa, socklen_t saLen) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); int result = connect(m_s, const_cast(psa), saLen); if (result == SOCKET_ERROR && GetLastError() == SOCKET_EWOULDBLOCK) return false; @@ -202,7 +202,7 @@ bool Socket::Connect(const sockaddr* psa, socklen_t saLen) bool Socket::Accept(Socket& target, sockaddr *psa, socklen_t *psaLen) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); socket_t s = accept(m_s, psa, psaLen); if (s == INVALID_SOCKET && GetLastError() == SOCKET_EWOULDBLOCK) return false; @@ -213,19 +213,19 @@ bool Socket::Accept(Socket& target, sockaddr *psa, socklen_t *psaLen) void Socket::GetSockName(sockaddr *psa, socklen_t *psaLen) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); CheckAndHandleError_int("getsockname", getsockname(m_s, psa, psaLen)); } void Socket::GetPeerName(sockaddr *psa, socklen_t *psaLen) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); CheckAndHandleError_int("getpeername", getpeername(m_s, psa, psaLen)); } unsigned int Socket::Send(const byte* buf, size_t bufLen, int flags) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); int result = send(m_s, (const char *)buf, UnsignedMin(INT_MAX, bufLen), flags); CheckAndHandleError_int("send", result); return result; @@ -233,7 +233,7 @@ unsigned int Socket::Send(const byte* buf, size_t bufLen, int flags) unsigned int Socket::Receive(byte* buf, size_t bufLen, int flags) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); int result = recv(m_s, (char *)buf, UnsignedMin(INT_MAX, bufLen), flags); CheckAndHandleError_int("recv", result); return result; @@ -241,14 +241,14 @@ unsigned int Socket::Receive(byte* buf, size_t bufLen, int flags) void Socket::ShutDown(int how) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); int result = shutdown(m_s, how); CheckAndHandleError_int("shutdown", result); } void Socket::IOCtl(long cmd, unsigned long *argp) { - assert(m_s != INVALID_SOCKET); + CRYPTOPP_ASSERT(m_s != INVALID_SOCKET); #ifdef USE_WINDOWS_STYLE_SOCKETS CheckAndHandleError_int("ioctlsocket", ioctlsocket(m_s, cmd, argp)); #else @@ -369,11 +369,11 @@ SocketReceiver::~SocketReceiver() #ifdef USE_WINDOWS_STYLE_SOCKETS # if defined(USE_WINDOWS8_API) BOOL result = CancelIoEx((HANDLE) m_s.GetSocket(), NULL); - assert(result || (!result && GetLastError() == ERROR_NOT_FOUND)); - CRYPTOPP_UNUSED(result); // Used by assert in debug builds + CRYPTOPP_ASSERT(result || (!result && GetLastError() == ERROR_NOT_FOUND)); + CRYPTOPP_UNUSED(result); // Used by CRYPTOPP_ASSERT in debug builds # else BOOL result = CancelIo((HANDLE) m_s.GetSocket()); - assert(result || (!result && GetLastError() == ERROR_NOT_FOUND)); + CRYPTOPP_ASSERT(result || (!result && GetLastError() == ERROR_NOT_FOUND)); CRYPTOPP_UNUSED(result); # endif #endif @@ -381,7 +381,7 @@ SocketReceiver::~SocketReceiver() bool SocketReceiver::Receive(byte* buf, size_t bufLen) { - assert(!m_resultPending && !m_eofReceived); + CRYPTOPP_ASSERT(!m_resultPending && !m_eofReceived); DWORD flags = 0; // don't queue too much at once, or we might use up non-paged memory @@ -459,11 +459,11 @@ SocketSender::~SocketSender() #ifdef USE_WINDOWS_STYLE_SOCKETS # if defined(USE_WINDOWS8_API) BOOL result = CancelIoEx((HANDLE) m_s.GetSocket(), NULL); - assert(result || (!result && GetLastError() == ERROR_NOT_FOUND)); - CRYPTOPP_UNUSED(result); // Used by assert in debug builds + CRYPTOPP_ASSERT(result || (!result && GetLastError() == ERROR_NOT_FOUND)); + CRYPTOPP_UNUSED(result); // Used by CRYPTOPP_ASSERT in debug builds # else BOOL result = CancelIo((HANDLE) m_s.GetSocket()); - assert(result || (!result && GetLastError() == ERROR_NOT_FOUND)); + CRYPTOPP_ASSERT(result || (!result && GetLastError() == ERROR_NOT_FOUND)); CRYPTOPP_UNUSED(result); # endif #endif @@ -471,7 +471,7 @@ SocketSender::~SocketSender() void SocketSender::Send(const byte* buf, size_t bufLen) { - assert(!m_resultPending); + CRYPTOPP_ASSERT(!m_resultPending); DWORD written = 0; // don't queue too much at once, or we might use up non-paged memory WSABUF wsabuf = {UnsignedMin((u_long)128*1024, bufLen), (char *)buf}; @@ -491,7 +491,7 @@ void SocketSender::Send(const byte* buf, size_t bufLen) void SocketSender::SendEof() { - assert(!m_resultPending); + CRYPTOPP_ASSERT(!m_resultPending); m_s.ShutDown(SD_SEND); m_s.CheckAndHandleError("ResetEvent", ResetEvent(m_event)); m_s.CheckAndHandleError_int("WSAEventSelect", WSAEventSelect(m_s, m_event, FD_CLOSE)); diff --git a/socketft.h b/socketft.h index 61592834..2ebee4db 100644 --- a/socketft.h +++ b/socketft.h @@ -94,7 +94,7 @@ public: {if (result == static_cast(SOCKET_ERROR)) HandleError(operation);} #ifdef USE_WINDOWS_STYLE_SOCKETS void CheckAndHandleError(const char *operation, BOOL result) const - {assert(result==TRUE || result==FALSE); if (!result) HandleError(operation);} + {CRYPTOPP_ASSERT(result==TRUE || result==FALSE); if (!result) HandleError(operation);} void CheckAndHandleError(const char *operation, bool result) const {if (!result) HandleError(operation);} #endif @@ -121,7 +121,7 @@ class SocketsInitializer { public: SocketsInitializer() {Socket::StartSockets();} - ~SocketsInitializer() {try {Socket::ShutdownSockets();} catch (const Exception&) {assert(0);}} + ~SocketsInitializer() {try {Socket::ShutdownSockets();} catch (const Exception&) {CRYPTOPP_ASSERT(0);}} }; class SocketReceiver : public NetworkReceiver diff --git a/sosemanuk.cpp b/sosemanuk.cpp index 2fba4371..366fe358 100644 --- a/sosemanuk.cpp +++ b/sosemanuk.cpp @@ -28,7 +28,7 @@ void SosemanukPolicy::CipherSetKey(const NameValuePairs ¶ms, const byte *use void SosemanukPolicy::CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length) { CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(iv), CRYPTOPP_UNUSED(length); - assert(length==16); + CRYPTOPP_ASSERT(length==16); word32 a, b, c, d, e; diff --git a/stdcpp.h b/stdcpp.h index f8f6c783..a176a597 100644 --- a/stdcpp.h +++ b/stdcpp.h @@ -44,7 +44,7 @@ namespace std { #include #include #include -#include +#include "trap.h" #ifdef CRYPTOPP_INCLUDE_VECTOR_CC // workaround needed on Sun Studio 12u1 Sun C++ 5.10 SunOS_i386 128229-02 2009/09/21 diff --git a/strciphr.cpp b/strciphr.cpp index b8cd2530..a0197c94 100644 --- a/strciphr.cpp +++ b/strciphr.cpp @@ -39,7 +39,7 @@ void AdditiveCipherTemplate::GenerateBlock(byte *outString, size_t length) if (!length) return; } - assert(m_leftOver == 0); + CRYPTOPP_ASSERT(m_leftOver == 0); PolicyInterface &policy = this->AccessPolicy(); unsigned int bytesPerIteration = policy.GetBytesPerIteration(); @@ -78,7 +78,7 @@ void AdditiveCipherTemplate::ProcessData(byte *outString, const byte *inStrin if (!length) return; } - assert(m_leftOver == 0); + CRYPTOPP_ASSERT(m_leftOver == 0); PolicyInterface &policy = this->AccessPolicy(); unsigned int bytesPerIteration = policy.GetBytesPerIteration(); @@ -176,7 +176,7 @@ void CFB_CipherTemplate::Resynchronize(const byte *iv, int length) template void CFB_CipherTemplate::ProcessData(byte *outString, const byte *inString, size_t length) { - assert(length % this->MandatoryBlockSize() == 0); + CRYPTOPP_ASSERT(length % this->MandatoryBlockSize() == 0); PolicyInterface &policy = this->AccessPolicy(); unsigned int bytesPerIteration = policy.GetBytesPerIteration(); @@ -196,7 +196,7 @@ void CFB_CipherTemplate::ProcessData(byte *outString, const byte *inString if (!length) return; - assert(m_leftOver == 0); + CRYPTOPP_ASSERT(m_leftOver == 0); if (policy.CanIterate() && length >= bytesPerIteration && IsAlignedOn(outString, alignment)) { diff --git a/strciphr.h b/strciphr.h index d0d1e8a7..9d1e093a 100644 --- a/strciphr.h +++ b/strciphr.h @@ -151,7 +151,7 @@ struct CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy //! which will be derived from GetBytesPerIteration(). //! \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream(), KeystreamOperation() virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount) - {CRYPTOPP_UNUSED(operation); CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(iterationCount); assert(false);} + {CRYPTOPP_UNUSED(operation); CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(false);} //! \brief Key the cipher //! \param params set of NameValuePairs use to initialize this object @@ -175,7 +175,7 @@ struct CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy //! \returns iterationCount //! \sa CipherIsRandomAccess() virtual void SeekToIteration(lword iterationCount) - {CRYPTOPP_UNUSED(iterationCount); assert(!CipherIsRandomAccess()); throw NotImplemented("StreamTransformation: this object doesn't support random access");} + {CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(!CipherIsRandomAccess()); throw NotImplemented("StreamTransformation: this object doesn't support random access");} }; //! \class AdditiveCipherConcretePolicy @@ -382,7 +382,7 @@ public: //! \sa IsSelfInverting() and IsForwardTransformation() virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount) {CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(dir); CRYPTOPP_UNUSED(iterationCount); - assert(false); /*throw 0;*/ throw Exception(Exception::OTHER_ERROR, "SimpleKeyingInterface: unexpected error");} + CRYPTOPP_ASSERT(false); /*throw 0;*/ throw Exception(Exception::OTHER_ERROR, "SimpleKeyingInterface: unexpected error");} //! \brief Key the cipher //! \param params set of NameValuePairs use to initialize this object @@ -441,8 +441,8 @@ struct CRYPTOPP_NO_VTABLE CFB_CipherConcretePolicy : public BASE //! \returns reference to the next feedback register word inline RegisterOutput& operator()(WordType ®isterWord) { - assert(IsAligned(m_output)); - assert(IsAligned(m_input)); + CRYPTOPP_ASSERT(IsAligned(m_output)); + CRYPTOPP_ASSERT(IsAligned(m_input)); if (!NativeByteOrderIs(B::ToEnum())) registerWord = ByteReverse(registerWord); @@ -450,7 +450,9 @@ struct CRYPTOPP_NO_VTABLE CFB_CipherConcretePolicy : public BASE if (m_dir == ENCRYPTION) { if (m_input == NULL) - assert(m_output == NULL); + { + CRYPTOPP_ASSERT(m_output == NULL); + } else { WordType ct = *(const WordType *)m_input ^ registerWord; diff --git a/tea.cpp b/tea.cpp index dba159f6..3c0daa4c 100644 --- a/tea.cpp +++ b/tea.cpp @@ -106,8 +106,8 @@ void XTEA::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, by void BTEA::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { CRYPTOPP_UNUSED(xorBlock); - assert(IsAlignedOn(inBlock,GetAlignmentOf())); - assert(IsAlignedOn(outBlock,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(inBlock,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(outBlock,GetAlignmentOf())); unsigned int n = m_blockSize / 4; word32 *v = (word32*)(void *)outBlock; @@ -136,8 +136,8 @@ void BTEA::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, by void BTEA::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { CRYPTOPP_UNUSED(xorBlock); - assert(IsAlignedOn(inBlock,GetAlignmentOf())); - assert(IsAlignedOn(outBlock,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(inBlock,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(outBlock,GetAlignmentOf())); unsigned int n = m_blockSize / 4; word32 *v = (word32*)(void *)outBlock; diff --git a/test.cpp b/test.cpp index bf0ddc02..52dd740a 100644 --- a/test.cpp +++ b/test.cpp @@ -21,6 +21,7 @@ #include "whrlpool.h" #include "tiger.h" #include "smartptr.h" +#include "trap.h" #include "validate.h" #include "bench.h" @@ -128,6 +129,11 @@ RandomNumberGenerator & GlobalRNG() return dynamic_cast(s_globalRNG); } +// See misc.h and trap.h for comments and usage +#if CRYPTOPP_DEBUG && (defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE)) +static const SignalHandler s_dummyHandler; +#endif + int CRYPTOPP_API main(int argc, char *argv[]) { #ifdef _CRTDBG_LEAK_CHECK_DF @@ -271,7 +277,7 @@ int CRYPTOPP_API main(int argc, char *argv[]) // compute MAC member_ptr pMac(NewIntegrityCheckingMAC()); - assert(pMac->DigestSize() == sizeof(mac)); + CRYPTOPP_ASSERT(pMac->DigestSize() == sizeof(mac)); MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac)))); f.AddRangeToSkip(0, checksumPos, 4); f.AddRangeToSkip(0, certificateTableDirectoryPos, 8); @@ -628,7 +634,7 @@ void DecryptFile(const char *in, const char *out, const char *passPhrase) void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed) { - assert(nShares >= 1 && nShares<=1000); + CRYPTOPP_ASSERT(nShares >= 1 && nShares<=1000); if (nShares < 1 || nShares > 1000) throw InvalidArgument("SecretShareFile: " + IntToString(nShares) + " is not in range [1, 1000]"); @@ -658,7 +664,7 @@ void SecretShareFile(int threshold, int nShares, const char *filename, const cha void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames) { - assert(threshold >= 1 && threshold <=1000); + CRYPTOPP_ASSERT(threshold >= 1 && threshold <=1000); if (threshold < 1 || threshold > 1000) throw InvalidArgument("SecretRecoverFile: " + IntToString(threshold) + " is not in range [1, 1000]"); @@ -685,7 +691,7 @@ void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFi void InformationDisperseFile(int threshold, int nShares, const char *filename) { - assert(threshold >= 1 && threshold <=1000); + CRYPTOPP_ASSERT(threshold >= 1 && threshold <=1000); if (threshold < 1 || threshold > 1000) throw InvalidArgument("InformationDisperseFile: " + IntToString(nShares) + " is not in range [1, 1000]"); @@ -712,7 +718,7 @@ void InformationDisperseFile(int threshold, int nShares, const char *filename) void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames) { - assert(threshold<=1000); + CRYPTOPP_ASSERT(threshold<=1000); if (threshold < 1 || threshold > 1000) throw InvalidArgument("InformationRecoverFile: " + IntToString(threshold) + " is not in range [1, 1000]"); @@ -811,7 +817,7 @@ void ForwardTcpPort(const char *sourcePortName, const char *destinationHost, con sockListen.Bind(sourcePort); int err = setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, "\x01", 1); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); if(err != 0) throw Socket::Err(sockListen, "setsockopt", sockListen.GetLastError()); @@ -963,9 +969,9 @@ bool Validate(int alg, bool thorough, const char *seedInput) const time_t endTime = time(NULL); err = localtime_s(&localTime, &endTime); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); err = asctime_s(timeBuf, sizeof(timeBuf), &localTime); - assert(err == 0); + CRYPTOPP_ASSERT(err == 0); cout << "\nTest ended at " << timeBuf; #else diff --git a/trap.h b/trap.h index 63985840..7a5d4a39 100644 --- a/trap.h +++ b/trap.h @@ -1,28 +1,28 @@ // trap.h - written and placed in public domain by Jeffrey Walton. // Copyright assigned to Crypto++ project +//! \file trap.h +//! \brief Debugging and diagnostic assertions +//! \details CRYPTOPP_ASSERT is the library's debugging and diagnostic assertion. CRYPTOPP_ASSERT +//! is enabled by CRYPTOPP_DEBUG, DEBUG or _DEBUG. +//! \details CRYPTOPP_ASSERT raises a SIGTRAP (Unix) or calls DebugBreak() (Windows). +//! CRYPTOPP_ASSERT is only in effect when the user requests a debug configuration. Unlike Posix assert, +//! NDEBUG (or failure to define it) does not affect the library. +//! The traditional Posix define NDEBUG has no effect on CRYPTOPP_DEBUG or DebugTrapHandler. +//! \since Crypto++ 5.6.5 +//! \sa DebugTrapHandler, Issue 277, +//! CVE-2016-7420 + #ifndef CRYPTOPP_TRAP_H #define CRYPTOPP_TRAP_H #include "config.h" -// CRYPTOPP_POSIX_ASSERT unconditionally disables the library assert and yields -// to Posix assert. CRYPTOPP_POSIX_ASSERT can be set in config.h. if you want -// to disable asserts, then define NDEBUG or _NDEBUG when building the library. - -// Needed for NDEBUG and CRYPTOPP_POSIX_ASSERT -#include - -#if defined(CRYPTOPP_DEBUG) +#if CRYPTOPP_DEBUG # include # include # if defined(CRYPTOPP_WIN32_AVAILABLE) -# pragma push_macro("WIN32_LEAN_AND_MEAN") -# pragma push_macro("_WIN32_WINNT") -# pragma push_macro("NOMINMAX") # define WIN32_LEAN_AND_MEAN -# define _WIN32_WINNT 0x0400 -# define NOMINMAX # include # elif defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE) # include @@ -31,11 +31,37 @@ // ************** run-time assertion *************** -// See test.cpp and DebugTrapHandler for code to install a null signal handler -// for SIGTRAP on BSD, Linux and Unix. The handler installs itself during -// initialization of the test program. +#if defined(CRYPTOPP_DOXYGEN_PROCESSING) +//! \brief Debugging and diagnostic assertion +//! \details CRYPTOPP_ASSERT is the library's debugging and diagnostic assertion. CRYPTOPP_ASSERT +//! is enabled by the preprocessor macros CRYPTOPP_DEBUG, DEBUG or _DEBUG. +//! \details CRYPTOPP_ASSERT raises a SIGTRAP (Unix) or calls DebugBreak() (Windows). +//! CRYPTOPP_ASSERT is only in effect when the user explictly requests a debug configuration. +//! \details If you want to ensure CRYPTOPP_ASSERT is inert, then do not define +//! CRYPTOPP_DEBUG, DEBUG or _DEBUG. Avoiding the defines means CRYPTOPP_ASSERT +//! is processed into ((void)(exp)). +//! \details The traditional Posix define NDEBUG has no effect on CRYPTOPP_DEBUG, CRYPTOPP_ASSERT +//! or DebugTrapHandler. +//! \details An example of using \ref CRYPTOPP_ASSERT "CRYPTOPP_ASSERT" and DebugTrapHandler is shown below. The library's +//! test program, cryptest.exe (from test.cpp), exercises the structure: +//!
+//!    #if CRYPTOPP_DEBUG && (defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE))
+//!    static const DebugTrapHandler g_dummyHandler;
+//!    #endif
+//!
+//!    int main(int argc, char* argv[])
+//!    {
+//!       CRYPTOPP_ASSERT(argv != nullptr);
+//!       ...
+//!    }
+//!  
+//! \since Crypto++ 5.6.5 +//! \sa DebugTrapHandler, SignalHandler, Issue 277, +//! CVE-2016-7420 +# define CRYPTOPP_ASSERT(exp) { ... } +#endif -#if defined(CRYPTOPP_DEBUG) && (defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE)) +#if CRYPTOPP_DEBUG && (defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE)) # define CRYPTOPP_ASSERT(exp) { \ if (!(exp)) { \ std::ostringstream oss; \ @@ -46,26 +72,106 @@ raise(SIGTRAP); \ } \ } -#elif defined(CRYPTOPP_DEBUG) && defined(CRYPTOPP_WIN32_AVAILABLE) +#elif CRYPTOPP_DEBUG && defined(CRYPTOPP_WIN32_AVAILABLE) # define CRYPTOPP_ASSERT(exp) { \ if (!(exp)) { \ std::ostringstream oss; \ oss << "Assertion failed: " << (char*)(__FILE__) << "(" \ << (int)(__LINE__) << "): " << (char*)(__FUNCTION__) \ << std::endl; \ - DebugBreak(); \ std::cerr << oss.str(); \ + DebugBreak(); \ } \ } -// Fallback to original behavior for NDEBUG (and non-Windows/non-Unix builds) -#else -# define CRYPTOPP_ASSERT(exp) assert(exp) #endif // DEBUG and Unix or Windows -#if defined(CRYPTOPP_DEBUG) && defined(CRYPTOPP_WIN32_AVAILABLE) -# pragma pop_macro("WIN32_LEAN_AND_MEAN") -# pragma pop_macro("_WIN32_WINNT") -# pragma pop_macro("NOMINMAX") +// Remove CRYPTOPP_ASSERT in non-debug builds. +// Can't use CRYPTOPP_UNUSED due to circular dependency +#ifndef CRYPTOPP_ASSERT +# define CRYPTOPP_ASSERT(exp) ((void)(exp)) #endif +NAMESPACE_BEGIN(CryptoPP) + +// ************** SIGTRAP handler *************** + +#if (CRYPTOPP_DEBUG && (defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE))) || defined(CRYPTOPP_DOXYGEN_PROCESSING) +//! \brief Default SIGTRAP handler +//! \details DebugTrapHandler() can be used by a program to install an empty SIGTRAP handler. If present, +//! the handler ensures there is a signal handler in place for SIGTRAP raised by +//! CRYPTOPP_ASSERT. If CRYPTOPP_ASSERT raises SIGTRAP without +//! a handler, then one of two things can occur. First, the OS might allow the program +//! to continue. Second, the OS might terminate the program. OS X allows the program to continue, while +//! some Linuxes terminate the program. +//! \details If DebugTrapHandler detects another handler in place, then it will not install a handler. This +//! ensures a debugger can gain control of the SIGTRAP signal without contention. It also allows multiple +//! DebugTrapHandler to be created without contentious or unusual behavior. Though muliple DebugTrapHandler can be +//! created, a program should only create one, if needed. +//! \details A DebugTrapHandler is subject to C++ static initialization [dis]order. If you need to install a handler +//! and it must be installed early, then reference the code associated with CRYPTOPP_INIT_PRIORITY in +//! cryptlib.cpp and cpu.cpp. +//! \details If you want to ensure CRYPTOPP_ASSERT is inert, then do not define +//! CRYPTOPP_DEBUG, DEBUG or _DEBUG. Avoiding the defines means CRYPTOPP_ASSERT +//! is processed into ((void)(exp)). +//! \details The traditional Posix define NDEBUG has no effect on CRYPTOPP_DEBUG, CRYPTOPP_ASSERT +//! or DebugTrapHandler. +//! \details An example of using \ref CRYPTOPP_ASSERT "CRYPTOPP_ASSERT" and DebugTrapHandler is shown below. The library's +//! test program, cryptest.exe (from test.cpp), exercises the structure: +//!
+//!    #if CRYPTOPP_DEBUG && (defined(CRYPTOPP_BSD_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE))
+//!    static const DebugTrapHandler g_dummyHandler;
+//!    #endif
+//!
+//!    int main(int argc, char* argv[])
+//!    {
+//!       CRYPTOPP_ASSERT(argv != nullptr);
+//!       ...
+//!    }
+//!  
+//! \since Crypto++ 5.6.5 +//! \sa \ref CRYPTOPP_ASSERT "CRYPTOPP_ASSERT", SignalHandler, Issue 277, +//! CVE-2016-7420 +struct DebugTrapHandler +{ + DebugTrapHandler() + { + // http://pubs.opengroup.org/onlinepubs/007908799/xsh/sigaction.html + struct sigaction old_handler, new_handler; + memset(&old_handler, 0x00, sizeof(old_handler)); + memset(&new_handler, 0x00, sizeof(new_handler)); + + do + { + int ret = 0; + + ret = sigaction (SIGTRAP, 0, &old_handler); + if (ret != 0) break; // Failed + + // Don't step on another's handler + if (old_handler.sa_handler != 0) break; + + // Set up the structure to specify the NULL action. + new_handler.sa_handler = &DebugTrapHandler::NullHandler; + new_handler.sa_flags = 0; + + ret = sigemptyset (&new_handler.sa_mask); + if (ret != 0) break; // Failed + + // Install it + ret = sigaction (SIGTRAP, &new_handler, 0); + if (ret != 0) break; // Failed + + } while(0); + } + + static void NullHandler(int /*unused*/) { } + +private: + DebugTrapHandler(const DebugTrapHandler &); + void operator=(const DebugTrapHandler &); +}; +#endif // DebugTrapHandler + +NAMESPACE_END + #endif // CRYPTOPP_TRAP_H diff --git a/trdlocal.cpp b/trdlocal.cpp index 12386abe..0d9d42f1 100644 --- a/trdlocal.cpp +++ b/trdlocal.cpp @@ -30,13 +30,13 @@ ThreadLocalStorage::ThreadLocalStorage() { #ifdef HAS_WINTHREADS m_index = TlsAlloc(); - assert(m_index != TLS_OUT_OF_INDEXES); + CRYPTOPP_ASSERT(m_index != TLS_OUT_OF_INDEXES); if (m_index == TLS_OUT_OF_INDEXES) throw Err("TlsAlloc", GetLastError()); #else m_index = 0; int error = pthread_key_create(&m_index, NULL); - assert(!error); + CRYPTOPP_ASSERT(!error); if (error) throw Err("pthread_key_create", error); #endif @@ -52,14 +52,14 @@ ThreadLocalStorage::~ThreadLocalStorage() CRYPTOPP_THROW #ifdef HAS_WINTHREADS { int rc = TlsFree(m_index); - assert(rc); + CRYPTOPP_ASSERT(rc); if (!rc) throw Err("TlsFree", GetLastError()); } #else { int error = pthread_key_delete(m_index); - assert(!error); + CRYPTOPP_ASSERT(!error); if (error) throw Err("pthread_key_delete", error); } @@ -89,7 +89,7 @@ void *ThreadLocalStorage::GetValue() const void *result = TlsGetValue(m_index); const DWORD dwRet = GetLastError(); - assert(result || (!result && (dwRet == NO_ERROR))); + CRYPTOPP_ASSERT(result || (!result && (dwRet == NO_ERROR))); if (!result && dwRet != NO_ERROR) throw Err("TlsGetValue", dwRet); #else diff --git a/validat1.cpp b/validat1.cpp index 36c888dd..9f382e33 100644 --- a/validat1.cpp +++ b/validat1.cpp @@ -216,7 +216,7 @@ bool TestSettings() } #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS - // Don't assert the alignment of testvals. That's what this test is for. + // Don't CRYPTOPP_ASSERT the alignment of testvals. That's what this test is for. byte testvals[10] = {1,2,2,3,3,3,3,2,2,1}; if (*(word32 *)(void *)(testvals+3) == 0x03030303 && *(word64 *)(void *)(testvals+1) == W64LIT(0x0202030303030202)) cout << "passed: Your machine allows unaligned data access.\n"; @@ -1580,7 +1580,7 @@ bool TestRDRAND() RandomNumberSource rns(rdrand, SIZE, true, new Redirector(chsw)); deflator.Flush(true); - assert(0 == maurer.BytesNeeded()); + CRYPTOPP_ASSERT(0 == maurer.BytesNeeded()); const double mv = maurer.GetTestValue(); if (mv < 0.98f) { @@ -1659,7 +1659,7 @@ bool TestRDSEED() RandomNumberSource rns(rdseed, SIZE, true, new Redirector(chsw)); deflator.Flush(true); - assert(0 == maurer.BytesNeeded()); + CRYPTOPP_ASSERT(0 == maurer.BytesNeeded()); const double mv = maurer.GetTestValue(); if (mv < 0.98f) { @@ -1803,7 +1803,7 @@ public: { std::cerr << "incorrect output " << counter << ", " << (word16)validOutput[counter] << ", " << (word16)inByte << "\n"; fail = true; - assert(false); + CRYPTOPP_ASSERT(false); } counter++; } @@ -1818,7 +1818,7 @@ public: if (counter != outputLen) { fail = true; - assert(false); + CRYPTOPP_ASSERT(false); } return 0; diff --git a/validat2.cpp b/validat2.cpp index ccea46f1..307a19ad 100644 --- a/validat2.cpp +++ b/validat2.cpp @@ -711,7 +711,7 @@ bool ValidateDSA(bool thorough) DSA::Verifier pub(priv); FileSource fs2(CRYPTOPP_DATA_DIR "TestData/dsa1024b.dat", true, new HexDecoder()); DSA::Verifier pub1(fs2); - assert(pub.GetKey() == pub1.GetKey()); + CRYPTOPP_ASSERT(pub.GetKey() == pub1.GetKey()); pass = SignatureValidate(priv, pub, thorough) && pass; pass = RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/dsa.txt", g_nullNameValuePairs, thorough) && pass; diff --git a/vmac.cpp b/vmac.cpp index 1fa58f1c..a6662f21 100644 --- a/vmac.cpp +++ b/vmac.cpp @@ -87,7 +87,7 @@ void VMAC_Base::UncheckedSetKey(const byte *userKey, unsigned int keylength, con in[0] = 0xE0; in[15] = 0; word64 *l3Key = m_l3Key(); - assert(IsAlignedOn(l3Key,GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(l3Key,GetAlignmentOf())); for (i = 0; i <= (size_t)m_is128; i++) do @@ -147,7 +147,7 @@ void VMAC_Base::Resynchronize(const byte *nonce, int len) void VMAC_Base::HashEndianCorrectedBlock(const word64 *data) { CRYPTOPP_UNUSED(data); - assert(false); + CRYPTOPP_ASSERT(false); throw NotImplemented("VMAC: HashEndianCorrectedBlock is not implemented"); } @@ -170,8 +170,8 @@ __attribute__ ((noinline)) // Intel Compiler 9.1 workaround #endif VMAC_Base::VHASH_Update_SSE2(const word64 *data, size_t blocksRemainingInWord64, int tagPart) { - assert(IsAlignedOn(m_polyState(),GetAlignmentOf())); - assert(IsAlignedOn(m_nhKey(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_polyState(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_nhKey(),GetAlignmentOf())); const word64 *nhK = m_nhKey(); word64 *polyS = (word64*)(void*)m_polyState(); @@ -538,8 +538,8 @@ template #endif void VMAC_Base::VHASH_Update_Template(const word64 *data, size_t blocksRemainingInWord64) { - assert(IsAlignedOn(m_polyState(),GetAlignmentOf())); - assert(IsAlignedOn(m_nhKey(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_polyState(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_nhKey(),GetAlignmentOf())); #define INNER_LOOP_ITERATION(j) {\ word64 d0 = ConditionalByteReverse(LITTLE_ENDIAN_ORDER, data[i+2*j+0]);\ @@ -870,8 +870,8 @@ static word64 L3Hash(const word64 *input, const word64 *l3Key, size_t len) void VMAC_Base::TruncatedFinal(byte *mac, size_t size) { - assert(IsAlignedOn(DataBuf(),GetAlignmentOf())); - assert(IsAlignedOn(m_polyState(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(DataBuf(),GetAlignmentOf())); + CRYPTOPP_ASSERT(IsAlignedOn(m_polyState(),GetAlignmentOf())); size_t len = ModPowerOf2(GetBitCountLo()/8, m_L1KeyLength); if (len) diff --git a/wait.cpp b/wait.cpp index f559b9d4..3c3195c9 100644 --- a/wait.cpp +++ b/wait.cpp @@ -152,15 +152,15 @@ WaitObjectContainer::~WaitObjectContainer() } BOOL bResult = PulseEvent(m_startWaiting); - assert(bResult != 0); CRYPTOPP_UNUSED(bResult); + CRYPTOPP_ASSERT(bResult != 0); CRYPTOPP_UNUSED(bResult); // Enterprise Analysis warning #if defined(USE_WINDOWS8_API) DWORD dwResult = ::WaitForMultipleObjectsEx((DWORD)m_threads.size(), threadHandles, TRUE, INFINITE, FALSE); - assert((dwResult >= WAIT_OBJECT_0) && (dwResult < (DWORD)m_threads.size())); + CRYPTOPP_ASSERT((dwResult >= WAIT_OBJECT_0) && (dwResult < (DWORD)m_threads.size())); #else DWORD dwResult = ::WaitForMultipleObjects((DWORD)m_threads.size(), threadHandles, TRUE, INFINITE); - assert((dwResult >= WAIT_OBJECT_0) && (dwResult < (DWORD)m_threads.size())); + CRYPTOPP_ASSERT((dwResult >= WAIT_OBJECT_0) && (dwResult < (DWORD)m_threads.size())); #endif for (i=0; i WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + handles.size())) { - assert(!"error in WaitingThread"); // break here so we can see which thread has an error + CRYPTOPP_ASSERT(!"error in WaitingThread"); // break here so we can see which thread has an error *thread.error = ::GetLastError(); } } @@ -328,10 +328,10 @@ bool WaitObjectContainer::Wait(unsigned long milliseconds) #if defined(USE_WINDOWS8_API) DWORD result = ::WaitForSingleObjectEx(m_stopWaiting, milliseconds, FALSE); - assert(result != WAIT_FAILED); + CRYPTOPP_ASSERT(result != WAIT_FAILED); #else DWORD result = ::WaitForSingleObject(m_stopWaiting, milliseconds); - assert(result != WAIT_FAILED); + CRYPTOPP_ASSERT(result != WAIT_FAILED); #endif if (result == WAIT_OBJECT_0) @@ -359,10 +359,10 @@ bool WaitObjectContainer::Wait(unsigned long milliseconds) #endif #if defined(USE_WINDOWS8_API) DWORD result = ::WaitForMultipleObjectsEx((DWORD)m_handles.size(), &m_handles[0], FALSE, milliseconds, FALSE); - assert(result != WAIT_FAILED); + CRYPTOPP_ASSERT(result != WAIT_FAILED); #else DWORD result = ::WaitForMultipleObjects((DWORD)m_handles.size(), &m_handles[0], FALSE, milliseconds); - assert(result != WAIT_FAILED); + CRYPTOPP_ASSERT(result != WAIT_FAILED); #endif #if TRACE_WAIT if (milliseconds > 0) diff --git a/winpipes.cpp b/winpipes.cpp index 0b4846d0..ca0ed568 100644 --- a/winpipes.cpp +++ b/winpipes.cpp @@ -34,7 +34,7 @@ WindowsHandle::~WindowsHandle() } catch (const Exception&) { - assert(0); + CRYPTOPP_ASSERT(0); } } } @@ -99,7 +99,7 @@ WindowsPipeReceiver::WindowsPipeReceiver() bool WindowsPipeReceiver::Receive(byte* buf, size_t bufLen) { - assert(!m_resultPending && !m_eofReceived); + CRYPTOPP_ASSERT(!m_resultPending && !m_eofReceived); const HANDLE h = GetHandle(); // don't queue too much at once, or we might use up non-paged memory diff --git a/winpipes.h b/winpipes.h index 246fb91b..f7335ffe 100644 --- a/winpipes.h +++ b/winpipes.h @@ -55,7 +55,7 @@ protected: virtual HANDLE GetHandle() const =0; virtual void HandleError(const char *operation) const; void CheckAndHandleError(const char *operation, BOOL result) const - {assert(result==TRUE || result==FALSE); if (!result) HandleError(operation);} + {CRYPTOPP_ASSERT(result==TRUE || result==FALSE); if (!result) HandleError(operation);} }; //! \brief Pipe-based implementation of NetworkReceiver diff --git a/words.h b/words.h index 5a5af2a2..c2be9793 100644 --- a/words.h +++ b/words.h @@ -55,7 +55,7 @@ inline void AndWords(word *r, const word *a, size_t n) inline word ShiftWordsLeftByBits(word *r, size_t n, unsigned int shiftBits) { - assert (shiftBits0; i--) diff --git a/xtr.cpp b/xtr.cpp index 9819b81d..0de51f80 100644 --- a/xtr.cpp +++ b/xtr.cpp @@ -18,8 +18,8 @@ const GFP2Element & GFP2Element::Zero() void XTR_FindPrimesAndGenerator(RandomNumberGenerator &rng, Integer &p, Integer &q, GFP2Element &g, unsigned int pbits, unsigned int qbits) { - assert(qbits > 9); // no primes exist for pbits = 10, qbits = 9 - assert(pbits > qbits); + CRYPTOPP_ASSERT(qbits > 9); // no primes exist for pbits = 10, qbits = 9 + CRYPTOPP_ASSERT(pbits > qbits); const Integer minQ = Integer::Power2(qbits - 1); const Integer maxQ = Integer::Power2(qbits) - 1; @@ -30,11 +30,11 @@ void XTR_FindPrimesAndGenerator(RandomNumberGenerator &rng, Integer &p, Integer do { bool qFound = q.Randomize(rng, minQ, maxQ, Integer::PRIME, 7, 12); - CRYPTOPP_UNUSED(qFound); assert(qFound); + CRYPTOPP_UNUSED(qFound); CRYPTOPP_ASSERT(qFound); bool solutionsExist = SolveModularQuadraticEquation(r1, r2, 1, -1, 1, q); - CRYPTOPP_UNUSED(solutionsExist); assert(solutionsExist); + CRYPTOPP_UNUSED(solutionsExist); CRYPTOPP_ASSERT(solutionsExist); } while (!p.Randomize(rng, minP, maxP, Integer::PRIME, CRT(rng.GenerateBit()?r1:r2, q, 2, 3, EuclideanMultiplicativeInverse(p, 3)), 3*q)); - assert(((p.Squared() - p + 1) % q).IsZero()); + CRYPTOPP_ASSERT(((p.Squared() - p + 1) % q).IsZero()); GFP2_ONB gfp2(p); GFP2Element three = gfp2.ConvertIn(3), t; @@ -50,7 +50,7 @@ void XTR_FindPrimesAndGenerator(RandomNumberGenerator &rng, Integer &p, Integer if (g != three) break; } - assert(XTR_Exponentiate(g, q, p) == three); + CRYPTOPP_ASSERT(XTR_Exponentiate(g, q, p) == three); } GFP2Element XTR_Exponentiate(const GFP2Element &b, const Integer &e, const Integer &p) diff --git a/xtr.h b/xtr.h index d38bae95..301d51cc 100644 --- a/xtr.h +++ b/xtr.h @@ -183,7 +183,7 @@ public: // a^2 - 2a^p const Element & SpecialOperation1(const Element &a) const { - assert(&a != &result); + CRYPTOPP_ASSERT(&a != &result); result = Square(a); modp.Reduce(result.c1, a.c2); modp.Reduce(result.c1, a.c2); @@ -195,7 +195,7 @@ public: // x * z - y * z^p const Element & SpecialOperation2(const Element &x, const Element &y, const Element &z) const { - assert(&x != &result && &y != &result && &z != &result); + CRYPTOPP_ASSERT(&x != &result && &y != &result && &z != &result); t = modp.Add(x.c2, y.c2); result.c1 = modp.Multiply(z.c1, modp.Subtract(y.c1, t)); modp.Accumulate(result.c1, modp.Multiply(z.c2, modp.Subtract(t, x.c1))); diff --git a/zdeflate.cpp b/zdeflate.cpp index a016b300..15ae2de7 100644 --- a/zdeflate.cpp +++ b/zdeflate.cpp @@ -20,14 +20,14 @@ LowFirstBitWriter::LowFirstBitWriter(BufferedTransformation *attachment) void LowFirstBitWriter::StartCounting() { - assert(!m_counting); + CRYPTOPP_ASSERT(!m_counting); m_counting = true; m_bitCount = 0; } unsigned long LowFirstBitWriter::FinishCounting() { - assert(m_counting); + CRYPTOPP_ASSERT(m_counting); m_counting = false; return m_bitCount; } @@ -40,7 +40,7 @@ void LowFirstBitWriter::PutBits(unsigned long value, unsigned int length) { m_buffer |= value << m_bitsBuffered; m_bitsBuffered += length; - assert(m_bitsBuffered <= sizeof(unsigned long)*8); + CRYPTOPP_ASSERT(m_bitsBuffered <= sizeof(unsigned long)*8); while (m_bitsBuffered >= 8) { m_outputBuffer[m_bytesBuffered++] = (byte)m_buffer; @@ -109,8 +109,8 @@ struct FreqLessThan void HuffmanEncoder::GenerateCodeLengths(unsigned int *codeBits, unsigned int maxCodeBits, const unsigned int *codeCounts, size_t nCodes) { - assert(nCodes > 0); - assert(nCodes <= ((size_t)1 << maxCodeBits)); + CRYPTOPP_ASSERT(nCodes > 0); + CRYPTOPP_ASSERT(nCodes <= ((size_t)1 << maxCodeBits)); size_t i; SecBlockWithHint tree(nCodes); @@ -164,7 +164,7 @@ void HuffmanEncoder::GenerateCodeLengths(unsigned int *codeBits, unsigned int ma bits--; blCount[bits]--; blCount[bits+1] += 2; - assert(blCount[maxCodeBits] > 0); + CRYPTOPP_ASSERT(blCount[maxCodeBits] > 0); blCount[maxCodeBits]--; } @@ -178,12 +178,12 @@ void HuffmanEncoder::GenerateCodeLengths(unsigned int *codeBits, unsigned int ma codeBits[tree[i].symbol] = bits; blCount[bits]--; } - assert(blCount[bits] == 0); + CRYPTOPP_ASSERT(blCount[bits] == 0); } void HuffmanEncoder::Initialize(const unsigned int *codeBits, unsigned int nCodes) { - assert(nCodes > 0); + CRYPTOPP_ASSERT(nCodes > 0); unsigned int maxCodeBits = *std::max_element(codeBits, codeBits+nCodes); if (maxCodeBits == 0) return; // assume this object won't be used @@ -202,7 +202,7 @@ void HuffmanEncoder::Initialize(const unsigned int *codeBits, unsigned int nCode code = (code + blCount[i-1]) << 1; nextCode[i] = code; } - assert(maxCodeBits == 1 || code == (1 << maxCodeBits) - blCount[maxCodeBits]); + CRYPTOPP_ASSERT(maxCodeBits == 1 || code == (1 << maxCodeBits) - blCount[maxCodeBits]); m_valueToCode.resize(nCodes); for (i=0; i 0); + CRYPTOPP_ASSERT(m_valueToCode[value].len > 0); writer.PutBits(m_valueToCode[value].code, m_valueToCode[value].len); } @@ -265,7 +265,7 @@ void Deflator::IsolatedInitialize(const NameValuePairs ¶meters) Reset(true); const int deflateLevel = parameters.GetIntValueWithDefault("DeflateLevel", DEFAULT_DEFLATE_LEVEL); - assert(deflateLevel >= MIN_DEFLATE_LEVEL /*0*/ && deflateLevel <= MAX_DEFLATE_LEVEL /*9*/); + CRYPTOPP_ASSERT(deflateLevel >= MIN_DEFLATE_LEVEL /*0*/ && deflateLevel <= MAX_DEFLATE_LEVEL /*9*/); SetDeflateLevel(deflateLevel); bool detectUncompressible = parameters.GetValueWithDefault("DetectUncompressible", true); m_compressibleDeflateLevel = detectUncompressible ? m_deflateLevel : 0; @@ -276,7 +276,7 @@ void Deflator::Reset(bool forceReset) if (forceReset) ClearBitBuffer(); else - assert(m_bitsBuffered == 0); + CRYPTOPP_ASSERT(m_bitsBuffered == 0); m_headerWritten = false; m_matchAvailable = false; @@ -340,16 +340,16 @@ unsigned int Deflator::FillWindow(const byte *str, size_t length) memcpy(m_byteBuffer, m_byteBuffer + DSIZE, DSIZE); m_dictionaryEnd = m_dictionaryEnd < DSIZE ? 0 : m_dictionaryEnd-DSIZE; - assert(m_stringStart >= DSIZE); + CRYPTOPP_ASSERT(m_stringStart >= DSIZE); m_stringStart -= DSIZE; - assert(!m_matchAvailable || m_previousMatch >= DSIZE); + CRYPTOPP_ASSERT(!m_matchAvailable || m_previousMatch >= DSIZE); m_previousMatch -= DSIZE; - assert(m_blockStart >= DSIZE); + CRYPTOPP_ASSERT(m_blockStart >= DSIZE); m_blockStart -= DSIZE; // These are set to the same value in IsolatedInitialize(). If they // are the same, then we can clear a Coverity false alarm. - assert(DSIZE == HSIZE); + CRYPTOPP_ASSERT(DSIZE == HSIZE); unsigned int i; for (i=0; i m_stringStart+m_lookahead); + CRYPTOPP_ASSERT(maxBlockSize > m_stringStart+m_lookahead); unsigned int accepted = UnsignedMin(maxBlockSize-(m_stringStart+m_lookahead), length); - assert(accepted > 0); + CRYPTOPP_ASSERT(accepted > 0); memcpy(m_byteBuffer + m_stringStart + m_lookahead, str, accepted); m_lookahead += accepted; return accepted; @@ -369,13 +369,13 @@ unsigned int Deflator::FillWindow(const byte *str, size_t length) inline unsigned int Deflator::ComputeHash(const byte *str) const { - assert(str+3 <= m_byteBuffer + m_stringStart + m_lookahead); + CRYPTOPP_ASSERT(str+3 <= m_byteBuffer + m_stringStart + m_lookahead); return ((str[0] << 10) ^ (str[1] << 5) ^ str[2]) & HMASK; } unsigned int Deflator::LongestMatch(unsigned int &bestMatch) const { - assert(m_previousLength < MAX_MATCH); + CRYPTOPP_ASSERT(m_previousLength < MAX_MATCH); bestMatch = 0; unsigned int bestLength = STDMAX(m_previousLength, (unsigned int)MIN_MATCH-1); @@ -393,10 +393,10 @@ unsigned int Deflator::LongestMatch(unsigned int &bestMatch) const while (current > limit && --chainLength > 0) { const byte *match = m_byteBuffer + current; - assert(scan + bestLength < m_byteBuffer + m_stringStart + m_lookahead); + CRYPTOPP_ASSERT(scan + bestLength < m_byteBuffer + m_stringStart + m_lookahead); if (scan[bestLength-1] == match[bestLength-1] && scan[bestLength] == match[bestLength] && scan[0] == match[0] && scan[1] == match[1]) { - assert(scan[2] == match[2]); + CRYPTOPP_ASSERT(scan[2] == match[2]); unsigned int len = (unsigned int)( #if defined(_STDEXT_BEGIN) && !(defined(_MSC_VER) && (_MSC_VER < 1400 || _MSC_VER >= 1600)) && !defined(_STLPORT_VERSION) stdext::unchecked_mismatch @@ -408,13 +408,13 @@ unsigned int Deflator::LongestMatch(unsigned int &bestMatch) const #else (scan+3, scanEnd, match+3).first - scan); #endif - assert(len != bestLength); + CRYPTOPP_ASSERT(len != bestLength); if (len > bestLength) { bestLength = len; bestMatch = current; - assert(scanEnd >= scan); + CRYPTOPP_ASSERT(scanEnd >= scan); if (len == (unsigned int)(scanEnd - scan)) break; } @@ -426,7 +426,7 @@ unsigned int Deflator::LongestMatch(unsigned int &bestMatch) const inline void Deflator::InsertString(unsigned int start) { - assert(start <= 0xffff); + CRYPTOPP_ASSERT(start <= 0xffff); unsigned int hash = ComputeHash(m_byteBuffer + start); m_prev[start & DMASK] = m_head[hash]; m_head[hash] = word16(start); @@ -493,7 +493,7 @@ void Deflator::ProcessBuffer() m_lookahead--; } - assert(m_stringStart - (m_blockStart+m_blockLength) == (unsigned int)m_matchAvailable); + CRYPTOPP_ASSERT(m_stringStart - (m_blockStart+m_blockLength) == (unsigned int)m_matchAvailable); } if (m_minLookahead == 0 && m_matchAvailable) @@ -517,7 +517,7 @@ size_t Deflator::Put2(const byte *str, size_t length, int messageEnd, bool block ProcessUncompressedData(str+accepted, newAccepted); accepted += newAccepted; } - assert(accepted == length); + CRYPTOPP_ASSERT(accepted == length); if (messageEnd) { @@ -586,9 +586,9 @@ void Deflator::MatchFound(unsigned int distance, unsigned int length) {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073, 4097,6145,8193,12289,16385,24577}; - assert(m_matchBufferEnd < m_matchBuffer.size()); + CRYPTOPP_ASSERT(m_matchBufferEnd < m_matchBuffer.size()); EncodedMatch &m = m_matchBuffer[m_matchBufferEnd++]; - assert((length >= 3) && (length-3 < COUNTOF(lengthCodes))); + CRYPTOPP_ASSERT((length >= 3) && (length-3 < COUNTOF(lengthCodes))); unsigned int lengthCode = lengthCodes[length-3]; m.literalCode = lengthCode; m.literalExtra = length - lengthBases[lengthCode-257]; @@ -650,8 +650,8 @@ void Deflator::EncodeBlock(bool eof, unsigned int blockType) if (blockType == STORED) { - assert(m_blockStart + m_blockLength <= m_byteBuffer.size()); - assert(m_blockLength <= 0xffff); + CRYPTOPP_ASSERT(m_blockStart + m_blockLength <= m_byteBuffer.size()); + CRYPTOPP_ASSERT(m_blockLength <= 0xffff); FlushBitBuffer(); AttachedTransformation()->PutWord16(word16(m_blockLength), LITTLE_ENDIAN_ORDER); AttachedTransformation()->PutWord16(word16(~m_blockLength), LITTLE_ENDIAN_ORDER); @@ -738,7 +738,7 @@ void Deflator::EncodeBlock(bool eof, unsigned int blockType) literalEncoder.Encode(*this, literalCode); if (literalCode >= 257) { - assert(literalCode <= 285); + CRYPTOPP_ASSERT(literalCode <= 285); PutBits(m_matchBuffer[i].literalExtra, lengthExtraBits[literalCode-257]); unsigned int distanceCode = m_matchBuffer[i].distanceCode; distanceEncoder.Encode(*this, distanceCode); diff --git a/zinflate.cpp b/zinflate.cpp index adffca01..da473f35 100644 --- a/zinflate.cpp +++ b/zinflate.cpp @@ -32,20 +32,20 @@ inline bool LowFirstBitReader::FillBuffer(unsigned int length) m_buffer |= (unsigned long)b << m_bitsBuffered; m_bitsBuffered += 8; } - assert(m_bitsBuffered <= sizeof(unsigned long)*8); + CRYPTOPP_ASSERT(m_bitsBuffered <= sizeof(unsigned long)*8); return true; } inline unsigned long LowFirstBitReader::PeekBits(unsigned int length) { bool result = FillBuffer(length); - CRYPTOPP_UNUSED(result); assert(result); + CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result); return m_buffer & (((unsigned long)1 << length) - 1); } inline void LowFirstBitReader::SkipBits(unsigned int length) { - assert(m_bitsBuffered >= length); + CRYPTOPP_ASSERT(m_bitsBuffered >= length); m_buffer >>= length; m_bitsBuffered -= length; } @@ -141,10 +141,10 @@ void HuffmanDecoder::Initialize(const unsigned int *codeBits, unsigned int nCode m_cacheBits = STDMIN(9U, m_maxCodeBits); m_cacheMask = (1 << m_cacheBits) - 1; m_normalizedCacheMask = NormalizeCode(m_cacheMask, m_cacheBits); - assert(m_normalizedCacheMask == BitReverse(m_cacheMask)); + CRYPTOPP_ASSERT(m_normalizedCacheMask == BitReverse(m_cacheMask)); const word64 shiftedCache = ((word64)1 << m_cacheBits); - assert(shiftedCache <= SIZE_MAX); + CRYPTOPP_ASSERT(shiftedCache <= SIZE_MAX); if (m_cache.size() != shiftedCache) m_cache.resize((size_t)shiftedCache); @@ -181,7 +181,7 @@ void HuffmanDecoder::FillCacheEntry(LookupEntry &entry, code_t normalizedCode) c inline unsigned int HuffmanDecoder::Decode(code_t code, /* out */ value_t &value) const { - assert(m_codeToValue.size() > 0); + CRYPTOPP_ASSERT(m_codeToValue.size() > 0); LookupEntry &entry = m_cache[code & m_cacheMask]; code_t normalizedCode = 0; @@ -209,7 +209,7 @@ inline unsigned int HuffmanDecoder::Decode(code_t code, /* out */ value_t &value bool HuffmanDecoder::Decode(LowFirstBitReader &reader, value_t &value) const { bool result = reader.FillBuffer(m_maxCodeBits); - CRYPTOPP_UNUSED(result); // assert(result); + CRYPTOPP_UNUSED(result); // CRYPTOPP_ASSERT(result); unsigned int codeBits = Decode(reader.PeekBuffer(), value); if (codeBits > reader.BitsBuffered()) @@ -478,13 +478,13 @@ bool Inflator::DecodeBody() switch (m_blockType) { case 0: // stored - assert(m_reader.BitsBuffered() == 0); + CRYPTOPP_ASSERT(m_reader.BitsBuffered() == 0); while (!m_inQueue.IsEmpty() && !blockEnd) { size_t size; const byte *block = m_inQueue.Spy(size); size = UnsignedMin(m_storedLen, size); - assert(size <= 0xffff); + CRYPTOPP_ASSERT(size <= 0xffff); OutputString(block, size); m_inQueue.Skip(size); @@ -562,7 +562,7 @@ bool Inflator::DecodeBody() } break; default: - assert(0); + CRYPTOPP_ASSERT(0); } } if (blockEnd) @@ -591,7 +591,7 @@ void Inflator::FlushOutput() { if (m_state != PRE_STREAM) { - assert(m_current >= m_lastFlush); + CRYPTOPP_ASSERT(m_current >= m_lastFlush); ProcessDecompressedData(m_window + m_lastFlush, m_current - m_lastFlush); m_lastFlush = m_current; } diff --git a/zlib.cpp b/zlib.cpp index bba4dc8e..12b1f633 100644 --- a/zlib.cpp +++ b/zlib.cpp @@ -21,9 +21,9 @@ static const byte FDICT_FLAG = (1 << 5); void ZlibCompressor::WritePrestreamHeader() { m_adler32.Restart(); - assert(((GetLog2WindowSize()-8) << 4) <= 255); + CRYPTOPP_ASSERT(((GetLog2WindowSize()-8) << 4) <= 255); byte cmf = byte(DEFLATE_METHOD | ((GetLog2WindowSize()-8) << 4)); - assert((GetCompressionLevel() << 6) <= 255); + CRYPTOPP_ASSERT((GetCompressionLevel() << 6) <= 255); byte flags = byte(GetCompressionLevel() << 6); AttachedTransformation()->PutWord16(RoundUpToMultipleOf(word16(cmf*256+flags), word16(31))); }