From c04f8acfcb3026fcc9e2ce6f41645c2ec42686e0 Mon Sep 17 00:00:00 2001 From: Dmitry Vasilyev Date: Fri, 9 Oct 2026 16:58:59 +0400 Subject: [PATCH] [Windows][Support] Force FlushViewOfFile() for sparse files before unmap() This patch fixes swiftlang/llvm-project / issues / 12605 (avoid ref for now). We have reproduced the issue on x86_64 too running 2000 processes simultaneously. It is hard to create a stable test for this patch. --- llvm/lib/CAS/MappedFileRegionArena.cpp | 8 ++++++++ llvm/lib/Support/Windows/Path.inc | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/llvm/lib/CAS/MappedFileRegionArena.cpp b/llvm/lib/CAS/MappedFileRegionArena.cpp index bb098d4a2258..69a8b96b6f6d 100644 --- a/llvm/lib/CAS/MappedFileRegionArena.cpp +++ b/llvm/lib/CAS/MappedFileRegionArena.cpp @@ -332,6 +332,14 @@ void MappedFileRegionArena::destroyImpl() { } } +#ifdef _WIN32 + // Always Unmap to + // - avoid address space leak; + // - avoid data loss for sparse files. + if (Region) + Region.unmap(); +#endif + auto Close = [](std::optional &FD) { if (FD) { sys::fs::file_t File = sys::fs::convertFDToNativeFile(*FD); diff --git a/llvm/lib/Support/Windows/Path.inc b/llvm/lib/Support/Windows/Path.inc index 7e78626f2852..e92273388c6e 100644 --- a/llvm/lib/Support/Windows/Path.inc +++ b/llvm/lib/Support/Windows/Path.inc @@ -1142,6 +1142,10 @@ static bool isEXE(StringRef Magic) { void mapped_file_region::unmapImpl() { if (Mapping) { + BY_HANDLE_FILE_INFORMATION FI; + if (::GetFileInformationByHandle(FileHandle.get(), &FI) && + (FI.dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) != 0) + ::FlushViewOfFile(Mapping, Size); bool Exe = isEXE(StringRef((char *)Mapping, Size));