[clang-tidy] Fix bugprone-bad-signal-to-kill-thread not working in clangd (#180711)

After preamble deserialization, `Token::getLiteralData()` returns
`nullptr` for macro tokens defined in headers. Fall back to
`SourceManager` to retrieve the token text from the source buffer.

Fixes https://github.com/clangd/clangd/issues/2473
This commit is contained in:
Alex Wang 2026-02-12 23:48:32 -08:00 committed by GitHub
parent b9f4c78873
commit 25a56fbd15
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 31 additions and 2 deletions

View File

@ -38,9 +38,15 @@ void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) {
return std::nullopt;
const MacroInfo *MI = PP->getMacroInfo(It->first);
const Token &T = MI->tokens().back();
if (!T.isLiteral() || !T.getLiteralData())
if (!T.isLiteral())
return std::nullopt;
SmallVector<char> Buffer;
bool Invalid = false;
const StringRef ValueStr = PP->getSpelling(T, Buffer, &Invalid);
if (Invalid)
return std::nullopt;
const StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
llvm::APInt IntValue;
constexpr unsigned AutoSenseRadix = 0;

View File

@ -823,6 +823,25 @@ TEST(DiagnosticTest, ClangTidyNoLiteralDataInMacroToken) {
EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre()); // no-crash
}
TEST(DiagnosticTest, BadSignalToKillThreadInPreamble) {
Annotations Main(R"cpp(
#include "signal.h"
using pthread_t = int;
int pthread_kill(pthread_t thread, int sig);
int func() {
pthread_t thread;
return pthread_kill(thread, 15);
}
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.HeaderFilename = "signal.h";
TU.HeaderCode = "#define SIGTERM 15";
TU.ClangTidyProvider = addTidyChecks("bugprone-bad-signal-to-kill-thread");
EXPECT_THAT(TU.build().getDiagnostics(),
ifTidyChecks(UnorderedElementsAre(
diagName("bugprone-bad-signal-to-kill-thread"))));
}
TEST(DiagnosticTest, ClangTidyMacroToEnumCheck) {
Annotations Main(R"cpp(
#if 1

View File

@ -144,6 +144,10 @@ Changes in existing checks
<clang-tidy/checks/bugprone/argument-comment>` to also check for C++11
inherited constructors.
- Improved :doc:`bugprone-bad-signal-to-kill-thread
<clang-tidy/checks/bugprone/bad-signal-to-kill-thread>` check by fixing false
negatives when the ``SIGTERM`` macro is obtained from a precompiled header.
- Improved :doc:`bugprone-exception-escape
<clang-tidy/checks/bugprone/exception-escape>` check by adding
`TreatFunctionsWithoutSpecificationAsThrowing` option to support reporting