From 8844e034c5e2f6ee728a6a03d34b28a7be45b18c Mon Sep 17 00:00:00 2001 From: Evgeni Margolis Date: Mon, 25 Apr 2022 16:46:34 -0700 Subject: [PATCH] Updated ASN1Reader::GetInteger() Implementation to Fix Clang tidy Error The Clang tidy clang-analyzer-core.UndefinedBinaryOperatorResult check was enabled in PR #17649. The original ASN1Reader::GetInteger() was correct but to silent the error the implementation was update. I hope it is now also more user readable --- src/lib/asn1/ASN1Reader.cpp | 24 ++++++++++++++---------- src/lib/asn1/ASN1Writer.cpp | 2 +- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/lib/asn1/ASN1Reader.cpp b/src/lib/asn1/ASN1Reader.cpp index 286a22e14b01e4..9309dc53448721 100644 --- a/src/lib/asn1/ASN1Reader.cpp +++ b/src/lib/asn1/ASN1Reader.cpp @@ -30,11 +30,14 @@ #include #include +#include #include namespace chip { namespace ASN1 { +using namespace chip::Encoding; + void ASN1Reader::Init(const uint8_t * buf, size_t len) { ResetElementState(); @@ -142,23 +145,24 @@ bool ASN1Reader::IsContained() const CHIP_ERROR ASN1Reader::GetInteger(int64_t & val) { + uint8_t encodedVal[sizeof(int64_t)] = { 0 }; + size_t valPaddingLen = sizeof(int64_t) - ValueLen; + ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); ReturnErrorCodeIf(ValueLen < 1, ASN1_ERROR_INVALID_ENCODING); ReturnErrorCodeIf(ValueLen > sizeof(int64_t), ASN1_ERROR_VALUE_OVERFLOW); ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); - // NOLINTBEGIN(clang-analyzer-core.UndefinedBinaryOperatorResult) - // - // TODO: clang-tidy says that if val is -1, then (val << 8) is not defined. - // added above supression to keep clang-tidy validating the rest of the files, however - // this complain likely needs fixing. - const uint8_t * p = Value; - val = ((*p & 0x80) == 0) ? 0 : -1; - for (uint32_t i = ValueLen; i > 0; i--, p++) + if ((*Value & 0x80) == 0x80) { - val = (val << 8) | *p; + for (size_t i = 0; i < valPaddingLen; i++) + { + encodedVal[i] = 0xFF; + } } - // NOLINTEND(clang-analyzer-core.UndefinedBinaryOperatorResult) + memcpy(&encodedVal[valPaddingLen], Value, ValueLen); + + val = static_cast(BigEndian::Get64(encodedVal)); return CHIP_NO_ERROR; } diff --git a/src/lib/asn1/ASN1Writer.cpp b/src/lib/asn1/ASN1Writer.cpp index 6b3d313e825456..a67ca0e041e7c2 100644 --- a/src/lib/asn1/ASN1Writer.cpp +++ b/src/lib/asn1/ASN1Writer.cpp @@ -75,7 +75,7 @@ size_t ASN1Writer::GetLengthWritten() const CHIP_ERROR ASN1Writer::PutInteger(int64_t val) { - uint8_t encodedVal[8]; + uint8_t encodedVal[sizeof(int64_t)]; uint8_t valStart, valLen; BigEndian::Put64(encodedVal, static_cast(val));