[clang] [-Wunsafe-buffer-usage] Fix a potential overflow bug reported by #126334 (PR #129169)

via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 27 17:34:09 PST 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-analysis

Author: Ziqing Luo (ziqingluo-90)

<details>
<summary>Changes</summary>

`MeasureTokenLength` may return an unsigned 0 representing failure in obtaining length of a token.  The analysis now gives up on such cases. Otherwise, there might be issues caused by unsigned integer "overflow".

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


1 Files Affected:

- (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+6-5) 


``````````diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index ff4f940a596e3..12e99143cb148 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2364,12 +2364,13 @@ template <typename NodeTy>
 static std::optional<SourceLocation>
 getEndCharLoc(const NodeTy *Node, const SourceManager &SM,
               const LangOptions &LangOpts) {
-  unsigned TkLen = Lexer::MeasureTokenLength(Node->getEndLoc(), SM, LangOpts);
-  SourceLocation Loc = Node->getEndLoc().getLocWithOffset(TkLen - 1);
-
-  if (Loc.isValid())
-    return Loc;
+  if (unsigned TkLen =
+          Lexer::MeasureTokenLength(Node->getEndLoc(), SM, LangOpts)) {
+    SourceLocation Loc = Node->getEndLoc().getLocWithOffset(TkLen - 1);
 
+    if (Loc.isValid())
+      return Loc;
+  }
   return std::nullopt;
 }
 

``````````

</details>


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


More information about the cfe-commits mailing list