From afa5a70ca825dc1051e150c7c23e465197d1a00b Mon Sep 17 00:00:00 2001 From: Steven Wu Date: Thu, 26 Jun 2025 09:49:55 -0700 Subject: [PATCH] [clang][DependencyFile] Use atomic write for dependency file Previously when switch to output backend, dependency file was relying on non-atomic write + discard to remove the out of date dependency file when there are missing headers. This makes the write non-atomic and can cause races conditions that build system is trying to read the file while the file is being updated by a different compiler instance. rdar://154128578 --- clang/lib/Frontend/DependencyFile.cpp | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/clang/lib/Frontend/DependencyFile.cpp b/clang/lib/Frontend/DependencyFile.cpp index 0c4812e764006..293eb332b1fc1 100644 --- a/clang/lib/Frontend/DependencyFile.cpp +++ b/clang/lib/Frontend/DependencyFile.cpp @@ -383,16 +383,13 @@ static void PrintFilename(raw_ostream &OS, StringRef Filename, } void DependencyFileGenerator::outputDependencyFile(DiagnosticsEngine &Diags) { - // The use of NoAtomicWrite and calling discard on SeenMissingHeader - // preserves the previous behaviour: no temporary files are used, and when - // SeenMissingHeader is true it deletes a previously-existing file. - // FIXME: switch to atomic-write based on FrontendOptions::UseTemporary and - // and not deleting the previous file, if possible. - Expected O = - OutputBackend->createFile(OutputFile, llvm::vfs::OutputConfig() - .setTextWithCRLF() - .setNoAtomicWrite() - .setNoDiscardOnSignal()); + if (SeenMissingHeader) { + llvm::sys::fs::remove(OutputFile); + return; + } + + Expected O = OutputBackend->createFile( + OutputFile, llvm::vfs::OutputConfig().setTextWithCRLF()); if (!O) { Diags.Report(diag::err_fe_error_opening) @@ -400,11 +397,6 @@ void DependencyFileGenerator::outputDependencyFile(DiagnosticsEngine &Diags) { return; } - if (SeenMissingHeader) { - consumeError(O->discard()); - return; - } - outputDependencyFile(O->getOS()); if (auto Err = O->keep())