[lld] [lld][macho] Fix gcc category merging warning (PR #86091)

via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 20 23:20:08 PDT 2024


https://github.com/alx32 created https://github.com/llvm/llvm-project/pull/86091

Fixing gcc warning regarding creating non-null-terminated string:
```
../../lld/MachO/ObjC.cpp:1226:10: warning: 'char* strncpy(char*, const char*, size_t)' output truncated before terminating nul copying as many bytes from a string as its length [-Wstringop-truncation]
 1226 |   strncpy(strData, str, len);
      |   ~~~~~~~^~~~~~~~~~~~~~~~~~~
../../lld/MachO/ObjC.cpp: In member function 'void {anonymous}::ObjcCategoryMerger::emitAndLinkPointerList(lld::macho::Defined*, uint32_t, const {anonymous}::ObjcCategoryMerger::ClassExtensionInfo&, const {anonymous}::ObjcCategoryMerger::PointerListInfo&)':
../../lld/MachO/ObjC.cpp:1223:24: note: length computed here
 1223 |   uint32_t len = strlen(str);
      |                  ~~~~~~^~~~~
```
This is not actually a bug, as `newSectionData` returns a zero-initialized memory region, so the null terminator will be there. 

>From 36f1e1a6a71ac7d2d27427a1ef6f6e628548ef7e Mon Sep 17 00:00:00 2001
From: alx32 <103613512+alx32 at users.noreply.github.com>
Date: Wed, 20 Mar 2024 23:17:01 -0700
Subject: [PATCH] [lld][macho] Fix gcc category merging warning

---
 lld/MachO/ObjC.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/lld/MachO/ObjC.cpp b/lld/MachO/ObjC.cpp
index 40df2243b26f06..831a5bcea3acfe 100644
--- a/lld/MachO/ObjC.cpp
+++ b/lld/MachO/ObjC.cpp
@@ -1221,9 +1221,10 @@ void ObjcCategoryMerger::doCleanup() { generatedSectionData.clear(); }
 
 StringRef ObjcCategoryMerger::newStringData(const char *str) {
   uint32_t len = strlen(str);
-  auto &data = newSectionData(len + 1);
+  uint32_t bufSize = len + 1;
+  auto &data = newSectionData(bufSize);
   char *strData = reinterpret_cast<char *>(data.data());
-  strncpy(strData, str, len);
+  strncpy(strData, str, bufSize);
   return StringRef(strData, len);
 }
 



More information about the llvm-commits mailing list