[clang-tools-extra] [clangd] Fix include-cleaner crash on header replaced behind symlink (PR #241215)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 11 02:59:12 PST 2026
https://github.com/AllStars101-sudo created https://github.com/llvm/llvm-project/pull/241215
clangd crashes in `computeIncludeCleanerFindings()` when an include directory is reached through a symlink and an included header is replaced by a new file (for example, saved via write-temp-then-rename) while the old preamble is still in use. Either condition alone is fine.
`IncludeStructure` identifies headers by the `UniqueID` recorded when the preamble was built, but `convertIncludes()` looks includes up again by canonical path. That path misses the preamble's stat cache, which is keyed by the path as included, so clangd sees the new file and `getID()` returns `std::nullopt`, which is then dereferenced.
When `getID()` fails, I now fall back to the `HeaderID` recorded for the `#include` on the same line, as `isPreferredProvider()` does. Nothing changes when `getID()` succeeds. Skipping the include instead would report it as unused.
The new test hits the existing assertion without the fix and passes with it. `check-clangd` passes, and the reproducer from the issue no longer crashes. I have not tested on Windows.
Open question: matching by line could credit the wrong include if two end up on the same line (bare-CR line endings plus preamble patching), giving a wrong unused-include warning where clangd used to crash. Passing the `HeaderID` through `convertIncludes()` avoids this but changes its interface. I can do that if reviewers prefer.
Fixes #161700
I wrote this patch with help from Claude Code, and reviewed and tested it myself.
>From e0573056d1bb82a5c08cd0d16917790777e896b3 Mon Sep 17 00:00:00 2001
From: Chris Pagolu <chrispagolu at gmail.com>
Date: Wed, 11 Nov 2026 21:40:17 +1100
Subject: [PATCH] [clangd] Fix include-cleaner crash on header replaced behind
symlink
clangd crashes in `computeIncludeCleanerFindings()` when an include
directory is reached through a symlink and an included header is
replaced by a new file (for example, saved via write-temp-then-rename)
while the old preamble is still in use. Either condition alone is fine.
`IncludeStructure` identifies headers by the `UniqueID` recorded when
the preamble was built, but `convertIncludes()` looks includes up again
by canonical path. That path misses the preamble's stat cache, which is
keyed by the path as included, so clangd sees the new file and
`getID()` returns `std::nullopt`, which is then dereferenced.
When `getID()` fails, I now fall back to the `HeaderID` recorded for
the `#include` on the same line, as `isPreferredProvider()` does.
Nothing changes when `getID()` succeeds. Skipping the include instead
would report it as unused.
The new test hits the existing assertion without the fix and passes
with it. `check-clangd` passes, and the reproducer from the issue no
longer crashes. I have not tested on Windows.
Open question: matching by line could credit the wrong include if two
end up on the same line (bare-CR line endings plus preamble patching),
giving a wrong unused-include warning where clangd used to crash.
Passing the `HeaderID` through `convertIncludes()` avoids this but
changes its interface. I can do that if reviewers prefer.
Fixes #161700
Assisted-by: Claude Code
---
clang-tools-extra/clangd/IncludeCleaner.cpp | 31 +++++---
.../clangd/unittests/IncludeCleanerTests.cpp | 76 +++++++++++++++++++
2 files changed, 97 insertions(+), 10 deletions(-)
diff --git a/clang-tools-extra/clangd/IncludeCleaner.cpp b/clang-tools-extra/clangd/IncludeCleaner.cpp
index 92637178d41580..1e389d32dbcc9d 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -388,6 +388,25 @@ computeIncludeCleanerFindings(ParsedAST &AST, bool AnalyzeAngledIncludes) {
collectMacroReferences(AST);
std::vector<MissingIncludeDiagInfo> MissingIncludes;
llvm::DenseSet<IncludeStructure::HeaderID> Used;
+ auto MarkUsed = [&](const include_cleaner::Include &Inc) {
+ const IncludeStructure &Includes = AST.getIncludeStructure();
+ if (auto HeaderID = Includes.getID(&Inc.Resolved->getFileEntry())) {
+ Used.insert(*HeaderID);
+ return;
+ }
+ // convertIncludes() looks up each include by its canonical path. The
+ // preamble's stat cache is keyed by the path the header was included by,
+ // which differs if e.g. the include directory is a symlink. If the header
+ // was replaced on disk since a stale preamble was built, we then see a
+ // file whose UniqueID is unknown to the IncludeStructure. Use the HeaderID
+ // recorded for the #include on the same line instead.
+ for (const Inclusion &MFI : Includes.MainFileIncludes) {
+ if (MFI.HeaderID && unsigned(MFI.HashLine + 1) == Inc.Line) {
+ Used.insert(static_cast<IncludeStructure::HeaderID>(*MFI.HeaderID));
+ return;
+ }
+ }
+ };
trace::Span Tracer("include_cleaner::walkUsed");
OptionalDirectoryEntryRef ResourceDir = AST.getPreprocessor()
.getHeaderSearchInfo()
@@ -408,11 +427,7 @@ computeIncludeCleanerFindings(ParsedAST &AST, bool AnalyzeAngledIncludes) {
}
for (auto *Inc : ConvertedIncludes.match(H)) {
Satisfied = true;
- auto HeaderID =
- AST.getIncludeStructure().getID(&Inc->Resolved->getFileEntry());
- assert(HeaderID.has_value() &&
- "ConvertedIncludes only contains resolved includes.");
- Used.insert(*HeaderID);
+ MarkUsed(*Inc);
}
}
@@ -431,11 +446,7 @@ computeIncludeCleanerFindings(ParsedAST &AST, bool AnalyzeAngledIncludes) {
for (auto *Inc :
ConvertedIncludes.match(include_cleaner::Header{Spelling})) {
Satisfied = true;
- auto HeaderID =
- AST.getIncludeStructure().getID(&Inc->Resolved->getFileEntry());
- assert(HeaderID.has_value() &&
- "ConvertedIncludes only contains resolved includes.");
- Used.insert(*HeaderID);
+ MarkUsed(*Inc);
}
if (Satisfied)
return;
diff --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
index 5b9db8af33f127..af6381db25b73e 100644
--- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -11,6 +11,7 @@
#include "Diagnostics.h"
#include "IncludeCleaner.h"
#include "ParsedAST.h"
+#include "Preamble.h"
#include "SourceCode.h"
#include "TestFS.h"
#include "TestTU.h"
@@ -25,7 +26,10 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Error.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/VirtualFileSystem.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <cstddef>
@@ -745,6 +749,78 @@ TEST(IncludeCleaner, DifferentHeaderSameSpelling) {
EXPECT_THAT(Findings.UnusedIncludes, IsEmpty());
EXPECT_THAT(Findings.MissingIncludes, IsEmpty());
}
+
+TEST(IncludeCleaner, NoCrashOnHeaderReplacedBehindSymlink) {
+ // InMemoryFileSystem::getRealPath() doesn't resolve symlinks.
+ class RealPathFS : public llvm::vfs::ProxyFileSystem {
+ public:
+ using ProxyFileSystem::ProxyFileSystem;
+ std::error_code getRealPath(const llvm::Twine &Path,
+ llvm::SmallVectorImpl<char> &Output) override {
+ if (auto EC = ProxyFileSystem::getRealPath(Path, Output))
+ return EC;
+ llvm::sys::path::replace_path_prefix(Output, testPath("link"),
+ testPath("real"));
+ return {};
+ }
+ };
+ // A MockFS in which the directory "link" is a symlink to the directory
+ // "real".
+ class SymlinkFS : public MockFS {
+ IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override {
+ auto MemFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
+ MemFS->setCurrentWorkingDirectory(testRoot());
+ for (const auto &[File, Contents] : Files)
+ MemFS->addFile(File, /*ModificationTime=*/0,
+ llvm::MemoryBuffer::getMemBufferCopy(Contents, File));
+ MemFS->addSymbolicLink(testPath("link"), testPath("real"),
+ /*ModificationTime=*/0);
+ return llvm::makeIntrusiveRefCnt<RealPathFS>(std::move(MemFS));
+ }
+ };
+
+ TestTU TU;
+ TU.Code = R"cpp(
+ #include "foo.h"
+ #include "bar.h"
+ void baz() { foo(); }
+ )cpp";
+ TU.AdditionalFiles["real/foo.h"] = guard("void foo();");
+ TU.AdditionalFiles["real/bar.h"] = guard("void bar();");
+ TU.ExtraArgs.push_back("-Ilink");
+
+ SymlinkFS FS;
+ IgnoreDiagnostics Diags;
+ auto Inputs = TU.inputs(FS);
+ auto CI = buildCompilerInvocation(Inputs, Diags);
+ ASSERT_TRUE(CI);
+ auto Preamble = buildPreamble(testPath(TU.Filename), *CI, Inputs,
+ /*StoreInMemory=*/true,
+ /*PreambleCallback=*/nullptr);
+ ASSERT_TRUE(Preamble);
+
+ // Replace foo.h, like an editor that saves by renaming a temporary file over
+ // the original. InMemoryFileSystem derives UniqueIDs from file contents, so
+ // the new file has a different UniqueID. The preamble's stat cache hides
+ // this for the path the header was included by, but not for its canonical
+ // path.
+ TU.AdditionalFiles["real/foo.h"] = guard("void foo(); void qux();");
+ Inputs = TU.inputs(FS);
+ CI = buildCompilerInvocation(Inputs, Diags);
+ ASSERT_TRUE(CI);
+ auto AST = ParsedAST::build(testPath(TU.Filename), Inputs, std::move(CI), {},
+ Preamble);
+ ASSERT_TRUE(AST);
+ auto FooH = AST->getSourceManager().getFileManager().getOptionalFileRef(
+ testPath("real/foo.h"));
+ ASSERT_TRUE(FooH);
+ ASSERT_FALSE(AST->getIncludeStructure().getID(&FooH->getFileEntry()));
+
+ auto Findings = computeIncludeCleanerFindings(*AST);
+ EXPECT_THAT(Findings.UnusedIncludes,
+ ElementsAre(Pointee(writtenInclusion("\"bar.h\""))));
+ EXPECT_THAT(Findings.MissingIncludes, IsEmpty());
+}
} // namespace
} // namespace clangd
} // namespace clang
More information about the cfe-commits
mailing list