[clang] 2e7cacf - [clang-format] Fix crash in TokenAnnotator (#82349)

via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 22 10:22:10 PST 2024


Author: Emilia Kond
Date: 2024-02-22T20:22:05+02:00
New Revision: 2e7cacfced573283d5424830f20333e2a6731251

URL: https://github.com/llvm/llvm-project/commit/2e7cacfced573283d5424830f20333e2a6731251
DIFF: https://github.com/llvm/llvm-project/commit/2e7cacfced573283d5424830f20333e2a6731251.diff

LOG: [clang-format] Fix crash in TokenAnnotator (#82349)

The while loop on line 3814 can cause a segmentation fault getting the
Next field on a nullptr. This is because further down, on line 3823,
there is another for loop, which assigns Tok to Tok->Next in its
initializer. This for loop has a condition to check if the result of
that isn't null. If it is, the loop is skipped and we drop back out to
the outer loop, except, now Tok is null, and we try to dereference it
without checking first.

This patch adds a defensive check that returns if Tok->Next is null
before we make it to the second for loop.

Fixes https://github.com/llvm/llvm-project/issues/82328

---------

Co-authored-by: Owen Pan <owenpiano at gmail.com>

Added: 
    

Modified: 
    clang/lib/Format/TokenAnnotator.cpp
    clang/unittests/Format/FormatTest.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index ec7b7f4dbe3470..a60d6ae197a24e 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3817,7 +3817,7 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
         do {
           Tok = Tok->Next;
         } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
-        if (!Tok)
+        if (!Tok || !Tok->MatchingParen)
           break;
         const auto *LeftParen = Tok;
         for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;

diff  --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 8282e75bd847f4..b8dc01f55b4faa 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -13503,6 +13503,12 @@ TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
   verifyFormat("{");
   verifyFormat("#})");
   verifyNoCrash("(/**/[:!] ?[).");
+  verifyNoCrash("struct X {\n"
+                "  operator iunt(\n"
+                "};");
+  verifyNoCrash("struct Foo {\n"
+                "  operator foo(bar\n"
+                "};");
 }
 
 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {


        


More information about the cfe-commits mailing list