Skip to content

[clang][dep-scan] Resolve lexer crash from a permutation of invalid tokens #142452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions clang/lib/Lex/DependencyDirectivesScanner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,15 @@ bool Scanner::lexModuleDirectiveBody(DirectiveKind Kind, const char *&First,
const char *const End) {
const char *DirectiveLoc = Input.data() + CurDirToks.front().Offset;
for (;;) {
// Keep a copy of the First char incase it needs to be reset.
const char *Previous = First;
const dependency_directives_scan::Token &Tok = lexToken(First, End);
if ((Tok.is(tok::hash) || Tok.is(tok::at)) &&
(Tok.Flags & clang::Token::StartOfLine)) {
CurDirToks.pop_back();
First = Previous;
return false;
}
if (Tok.is(tok::eof))
return reportError(
DirectiveLoc,
Expand Down Expand Up @@ -846,6 +854,7 @@ bool Scanner::lexPPLine(const char *&First, const char *const End) {
if (*First == '@')
return lexAt(First, End);

// Handle module directives for C++20 modules.
if (*First == 'i' || *First == 'e' || *First == 'm')
return lexModule(First, End);

Expand Down
17 changes: 16 additions & 1 deletion clang/unittests/Lex/DependencyDirectivesScannerTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -677,13 +677,28 @@ TEST(MinimizeSourceToDependencyDirectivesTest, EmptyIncludesAndImports) {
Out.data());
}

TEST(MinimizeSourceToDependencyDirectivesTest, AtImportFailures) {
TEST(MinimizeSourceToDependencyDirectivesTest, ImportFailures) {
SmallVector<char, 128> Out;

ASSERT_TRUE(minimizeSourceToDependencyDirectives("@import A\n", Out));
ASSERT_FALSE(
minimizeSourceToDependencyDirectives("@import MACRO(A);\n", Out));
ASSERT_FALSE(minimizeSourceToDependencyDirectives("@import \" \";\n", Out));

ASSERT_FALSE(minimizeSourceToDependencyDirectives("import <Foo.h>\n"
"@import Foo;",
Out));
EXPECT_STREQ("@import Foo;\n", Out.data());

ASSERT_FALSE(
minimizeSourceToDependencyDirectives("import <Foo.h>\n"
"#import <Foo.h>\n"
"@;\n"
"#pragma clang module import Foo",
Out));
EXPECT_STREQ("#import <Foo.h>\n"
"#pragma clang module import Foo\n",
Out.data());
}

TEST(MinimizeSourceToDependencyDirectivesTest, RawStringLiteral) {
Expand Down
Loading