Skip to content

[clang][modules] Guard against bad -fmodule-file mappings (#132059) #133462

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
Apr 8, 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
12 changes: 12 additions & 0 deletions clang/lib/Serialization/ASTReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3318,6 +3318,18 @@ ASTReader::ReadControlBlock(ModuleFile &F,
Loaded, StoredSize, StoredModTime,
StoredSignature, Capabilities);

// Check the AST we just read from ImportedFile contains a different
// module than we expected (ImportedName). This can occur for C++20
// Modules when given a mismatch via -fmodule-file=<name>=<file>
if (IsImportingStdCXXModule) {
if (const auto *Imported =
getModuleManager().lookupByFileName(ImportedFile);
Imported != nullptr && Imported->ModuleName != ImportedName) {
Diag(diag::err_failed_to_find_module_file) << ImportedName;
Result = Missing;
}
}

// If we diagnosed a problem, produce a backtrace.
bool recompilingFinalized = Result == OutOfDate &&
(Capabilities & ARR_OutOfDate) &&
Expand Down
48 changes: 48 additions & 0 deletions clang/test/Modules/fmodule-file-mismatch.cppm
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// RUN: rm -rf %t
// RUN: split-file %s %t
// RUN: cd %t

// Related to issue #132059

// Precompile the module dependencies correctly
// RUN: %clang_cc1 -std=c++20 -emit-module-interface a.cppm -o a.pcm
// RUN: %clang_cc1 -std=c++20 -emit-module-interface b.cppm -o b.pcm \
// RUN: -fmodule-file=A=a.pcm

// Verify that providing incorrect mappings via
// `-fmodule-file=<name>=<path/to/bmi>` does not crash the compiler when loading
// a module that imports the incorrectly mapped module.
// RUN: not %clang_cc1 -std=c++20 main1.cpp -fmodule-file=A=b.pcm

//--- a.cppm
export module A;

export int a() {
return 41;
}

//--- b.cppm
export module B;
import A;

export int b() {
return a() + 1;
}

//--- main1.cpp
import A;

int main() {
return a();
}

// Test again for the case where the BMI is first loaded correctly
// RUN: not %clang_cc1 -std=c++20 main2.cpp-fmodule-file=B=b.pcm \
// RUN: -fmodule-file=A=b.pcm

//--- main2.cpp
import B;

int main() {
return b();
}