[PATCH] D147686: [clangd] Fix a nullptr-dereference crash in computeIncludeCleanerFindings.

Haojian Wu via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Thu Apr 6 01:15:57 PDT 2023


hokein updated this revision to Diff 511319.
hokein added a comment.

add a comment.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D147686/new/

https://reviews.llvm.org/D147686

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===================================================================
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -442,6 +442,23 @@
   EXPECT_EQ(RefRange, Findings[1].SymRefRange);
 }
 
+TEST(IncludeCleaner, NoCrash) {
+  TestTU TU;
+  TU.Code = R"cpp(
+    #include "all.h"
+    void test() {
+      1s;
+    }
+    )cpp";
+  TU.AdditionalFiles["foo.h"] =
+      guard("int operator\"\"s(unsigned long long) { return 0; }");
+  TU.AdditionalFiles["all.h"] = guard("#include \"foo.h\"");
+  ParsedAST AST = TU.build();
+  auto Findings = computeIncludeCleanerFindings(AST);
+  // FIXME: this is not ideal, but at least we don't crash.
+  EXPECT_THAT(Findings.MissingIncludes, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===================================================================
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -405,10 +405,12 @@
         // through an #include.
         while (SM.getFileID(Loc) != SM.getMainFileID())
           Loc = SM.getIncludeLoc(SM.getFileID(Loc));
-        const auto *Token = AST.getTokens().spelledTokenAt(Loc);
-        MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
-                                        Providers};
-        MissingIncludes.push_back(std::move(DiagInfo));
+
+        if (const auto *Token = AST.getTokens().spelledTokenAt(Loc)) {
+          MissingIncludeDiagInfo DiagInfo{Ref.Target, Token->range(SM),
+                                          Providers};
+          MissingIncludes.push_back(std::move(DiagInfo));
+        }
       });
   std::vector<const Inclusion *> UnusedIncludes =
       getUnused(AST, Used, /*ReferencedPublicHeaders*/ {});


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D147686.511319.patch
Type: text/x-patch
Size: 1926 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20230406/20a317f0/attachment-0001.bin>


More information about the cfe-commits mailing list