[clang] [clang-format] Handle possible crash `getCells` (PR #77723)

via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 10 20:08:54 PST 2024


https://github.com/XDeme created https://github.com/llvm/llvm-project/pull/77723

Done as requested in llvm/llvm-project#77045

>From d8293dd1d933ed36e9ab6a73eeadb3cf2eaec8be Mon Sep 17 00:00:00 2001
From: XDeme <fernando.tagawa.gamail.com at gmail.com>
Date: Thu, 11 Jan 2024 01:06:55 -0300
Subject: [PATCH] [clang-format] Handle possible crash `getCells` Done as
 requested in llvm/llvm-project#77045

---
 clang/lib/Format/WhitespaceManager.cpp |  4 +++-
 clang/unittests/Format/FormatTest.cpp  | 10 ++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp
index f1d176f182ffa4..8415c8d360d640 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1451,8 +1451,10 @@ WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
       } else if (C.Tok->is(tok::comma)) {
         if (!Cells.empty())
           Cells.back().EndIndex = i;
-        if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma
+        if (const auto *Next = C.Tok->getNextNonComment();
+            Next && Next->isNot(tok::r_brace)) { // dangling comma
           ++Cell;
+        }
       }
     } else if (Depth == 1) {
       if (C.Tok == MatchingParen) {
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 8f115fb8cbf0fb..e710765d454d01 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -20931,6 +20931,11 @@ TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
       "};",
       Style);
 
+  verifyNoCrash("Foo f[] = {\n"
+                "    [0] = { 1, },\n"
+                "    [1] { 1, },\n"
+                "};",
+                Style);
   verifyNoCrash("Foo foo[] = {\n"
                 "    [0] = {1, 1},\n"
                 "    [1] { 1, 1, },\n"
@@ -21179,6 +21184,11 @@ TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
       "};",
       Style);
 
+  verifyNoCrash("Foo f[] = {\n"
+                "    [0] = { 1, },\n"
+                "    [1] { 1, },\n"
+                "};",
+                Style);
   verifyNoCrash("Foo foo[] = {\n"
                 "    [0] = {1, 1},\n"
                 "    [1] { 1, 1, },\n"



More information about the cfe-commits mailing list