Skip to content

Commit

Permalink
Updated ASN1Reader::GetInteger() Implementation to Fix Clang tidy Err…
Browse files Browse the repository at this point in the history
…or (#17718)

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
  • Loading branch information
emargolis authored and pull[bot] committed Feb 6, 2024
1 parent 5c0dc52 commit 194818a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
24 changes: 14 additions & 10 deletions src/lib/asn1/ASN1Reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,14 @@
#include <stdlib.h>

#include <lib/asn1/ASN1.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/support/SafeInt.h>

namespace chip {
namespace ASN1 {

using namespace chip::Encoding;

void ASN1Reader::Init(const uint8_t * buf, size_t len)
{
ResetElementState();
Expand Down Expand Up @@ -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<int64_t>(BigEndian::Get64(encodedVal));

return CHIP_NO_ERROR;
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/asn1/ASN1Writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint64_t>(val));
Expand Down

0 comments on commit 194818a

Please sign in to comment.