From bc425352cdc355523de5bafafeb1135bb5f28fed Mon Sep 17 00:00:00 2001 From: 0xTehuti Date: Sun, 22 Nov 2026 23:59:52 +0100 Subject: [PATCH] scripts: robust recursive directory cleanup with readonly reset in build_llvm_mc.ps1 (BUILD-139) When cleaning up temporary build and clone directories on Windows, files with the ReadOnly attribute (such as git objects in the sparse clone) cause PowerShell's Remove-Item to fail with an UnauthorizedAccessException or IOException, leaving gigabytes of files behind in $Temp. Implement Remove-DirectoryRobust: 1. Recursively strip ReadOnly attributes across all nested files and directories. 2. Retry Remove-Item with backoff for brief file handle locks. 3. Fall back to Windows cmd rmdir /s /q which handles read-only attribute trees natively. 4. Add unit test in tests/test_build_llvm_mc_cleanup.py verifying teardown of read-only hierarchies. --- scripts/build_llvm_mc.ps1 | 30 +++++++++++++++--- tests/test_build_llvm_mc_cleanup.py | 48 +++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 tests/test_build_llvm_mc_cleanup.py diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1 index 0e016463e..4dba75512 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 @@ -49,8 +49,29 @@ if (-not ((Test-Path $cmake) -and (Test-Path $ninja))) { $src = Join-Path $Temp "src" $out = Join-Path $Temp "build" +function Remove-DirectoryRobust([string]$path) { + if (-not (Test-Path -LiteralPath $path)) { return } + # Strip read-only attributes on nested files and folders so Windows allows deletion + Get-ChildItem -LiteralPath $path -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object { + try { + if ($_.Attributes -band [System.IO.FileAttributes]::ReadOnly) { + $_.Attributes = $_.Attributes -bxor [System.IO.FileAttributes]::ReadOnly + } + } catch {} + } + for ($attempt = 1; $attempt -le 3; $attempt++) { + try { + Remove-Item -LiteralPath $path -Recurse -Force -ErrorAction Stop + return + } catch { + Start-Sleep -Milliseconds (100 * $attempt) + } + } + cmd.exe /c "rmdir /s /q `"$path`"" 2>$null +} + if (-not (Test-Path (Join-Path $src "llvm\CMakeLists.txt"))) { - if (Test-Path $src) { Remove-Item -Recurse -Force $src } + if (Test-Path -LiteralPath $src) { Remove-DirectoryRobust $src } New-Item -ItemType Directory -Force $Temp | Out-Null # core.longpaths: some llvm/docs paths are about 150 characters, so with a -Temp of about 100 characters the # sparse checkout fails with "Filename too long" (Windows' 260-character limit). Set in the clone's config only. @@ -118,10 +139,9 @@ New-Item -ItemType Directory -Force $Dest | Out-Null $final = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $Dest "llvm-mc.exe")) Copy-Item -Force $exe $final if (-not $Keep) { - try { - Remove-Item -LiteralPath $Temp -Recurse -Force - } catch { - Write-Warning "Installed $final, but cleanup of '$Temp' failed: $($_.Exception.Message)" + Remove-DirectoryRobust $Temp + if (Test-Path -LiteralPath $Temp) { + Write-Warning "Installed $final, but cleanup of '$Temp' failed." } } if (-not $NoEnv) { diff --git a/tests/test_build_llvm_mc_cleanup.py b/tests/test_build_llvm_mc_cleanup.py new file mode 100644 index 000000000..4ad7a7b5a --- /dev/null +++ b/tests/test_build_llvm_mc_cleanup.py @@ -0,0 +1,48 @@ +"""Exercise the native LLVM builder's robust directory cleanup handling read-only attributes.""" +import os +from pathlib import Path +import stat +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_llvm_mc.ps1" + + +@unittest.skipUnless(os.name == "nt", "requires Windows PowerShell") +class BuildCleanupTest(unittest.TestCase): + def test_cleanup_removes_readonly_nested_files_and_directories(self): + text = SCRIPT.read_text(encoding="utf-8-sig") + start = text.index("function Remove-DirectoryRobust") + func_def = text[start:text.index("if (-not (Test-Path (Join-Path $src", start)].strip() + + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / "test_temp_cleanup" + target.mkdir() + sub = target / ".git" / "objects" / "pack" + sub.mkdir(parents=True) + ro_file = sub / "sample_pack.idx" + ro_file.write_bytes(b"DATA") + # Mark file and directory read-only on Windows + os.chmod(ro_file, stat.S_IREAD) + os.chmod(sub, stat.S_IREAD) + + driver = Path(directory) / "test-clean.ps1" + driver.write_text( + "param([string]$Path)\n" + "$ErrorActionPreference = 'Stop'\n" + + func_def + "\n" + "Remove-DirectoryRobust $Path\n", + encoding="utf-8", newline="\n", + ) + res = subprocess.run( + ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", + "-File", str(driver), "-Path", str(target)], + capture_output=True, text=True, check=True, timeout=30, + ) + self.assertFalse(target.exists(), f"Target directory should have been removed: {res.stderr}") + + +if __name__ == "__main__": + unittest.main()