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

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


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-lld

@llvm/pr-subscribers-lld-macho

Author: None (alx32)

<details>
<summary>Changes</summary>

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. 

---
Full diff: https://github.com/llvm/llvm-project/pull/86091.diff


1 Files Affected:

- (modified) lld/MachO/ObjC.cpp (+3-2) 


``````````diff
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);
 }
 

``````````

</details>


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


More information about the llvm-commits mailing list