Skip to content

Commit

Permalink
[clang-format] Fix crash in TokenAnnotator (#82349)
Browse files Browse the repository at this point in the history
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 #82328

---------

Co-authored-by: Owen Pan <owenpiano@gmail.com>
  • Loading branch information
rymiel and owenca committed Feb 22, 2024
1 parent 54a6cf1 commit 2e7cacf
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion clang/lib/Format/TokenAnnotator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 2e7cacf

Please sign in to comment.