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

Ziqing Luo via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 27 17:33:35 PST 2025


https://github.com/ziqingluo-90 created https://github.com/llvm/llvm-project/pull/129169

`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".

>From f37be15d5df3e8fac5c279862972beb2076c63a8 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Thu, 27 Feb 2025 17:23:53 -0800
Subject: [PATCH] [-Wunsafe-buffer-usage] Fix a potential overflow bug reported
 by #126334

`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".
---
 clang/lib/Analysis/UnsafeBufferUsage.cpp | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

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;
 }
 



More information about the cfe-commits mailing list