From 512efafc7ec4dbc40094a462c4689a156d06dded Mon Sep 17 00:00:00 2001 From: Alami-Amine Date: Fri, 13 Sep 2024 17:33:45 +0200 Subject: [PATCH] fixing ubsan issues --- src/lib/support/BufferWriter.cpp | 6 ++++-- src/lib/support/CHIPMemString.h | 13 ++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/lib/support/BufferWriter.cpp b/src/lib/support/BufferWriter.cpp index c606cba6e2b37d..2ba03e22d24e03 100644 --- a/src/lib/support/BufferWriter.cpp +++ b/src/lib/support/BufferWriter.cpp @@ -73,8 +73,9 @@ LittleEndian::BufferWriter & LittleEndian::BufferWriter::EndianPutSigned(int64_t BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPut(uint64_t x, size_t size) { - while (size-- > 0) + while (size > 0) { + size--; Put(static_cast((x >> (size * 8)) & 0xff)); } return *this; @@ -82,8 +83,9 @@ BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPut(uint64_t x, size_t BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPutSigned(int64_t x, size_t size) { - while (size-- > 0) + while (size > 0) { + size--; Put(static_cast((x >> (size * 8)) & 0xff)); } return *this; diff --git a/src/lib/support/CHIPMemString.h b/src/lib/support/CHIPMemString.h index 51341192a76250..f15003b8a2d354 100644 --- a/src/lib/support/CHIPMemString.h +++ b/src/lib/support/CHIPMemString.h @@ -84,9 +84,16 @@ inline void CopyString(char * dest, size_t destLength, ByteSpan source) { if (dest && destLength) { - size_t maxChars = std::min(destLength - 1, source.size()); - memcpy(dest, source.data(), maxChars); - dest[maxChars] = '\0'; + if (!source.empty()) + { + size_t maxChars = std::min(destLength - 1, source.size()); + memcpy(dest, source.data(), maxChars); + dest[maxChars] = '\0'; + } + else + { + dest[0] = '\0'; + } } }