Progmasoft Git

tazel

A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.

Clonegit clone https://git.progmasoft.com/tazel

fix(project): keep modes on cloned copies, never remove an existing file, clone on Windows

Motivation: rereading FileClone (merged in #59) found two bugs and a gap
against Next.md §15.0:
- FICLONE opened the destination 0644 and left it so: an executable cloned
  by FileClone (test data, or .tazel/ outputs moved into the Trash across
  file systems and restored) lost its execute bits. File.Copy keeps them.
- After a failed clone, any empty file at the destination was deleted, even
  one that existed before the call (O_EXCL had failed); the ordinary copy
  then succeeded over it instead of refusing as File.Copy does.
- Windows block cloning (FSCTL_DUPLICATE_EXTENTS_TO_FILE) was missing.

Changes:
- The clone attempt reports whether it created the destination; only then
  is it removed after a failure.
- After a clone, the source's Unix mode (Linux) or attributes (Windows) are
  applied; macOS clonefile keeps them itself.
- Windows: the destination is created and sized, then cloned in cluster-
  aligned ranges of at most 1 GiB, the last rounded up to a whole cluster;
  sparse sources are copied instead. GetDiskFreeSpaceW gives the cluster.
- ioctl's request is passed as nuint, matching C's unsigned long.
- I/O and access errors during an attempt fall back to the copy as before.
- CHANGELOG.md describes Windows cloning and the kept permissions.

Verification: Release build with warnings as errors (0 errors);
TrashTests 22/22. FileCloneNeverRemovesAFileThatWasAlreadyThere fails on
the previous code and passes now. FileCloneKeepsTheSourcesModeWhicheverWay
ItCopies passes on both here, because this machine (tmpfs, ext4) and CI
cannot clone, so the mode bug and the Windows path are not exercised; the
fallback to the copy is. Full suite 805 passed, 1 skipped.
Commit
9fb049a20666d1bf7b1ed8d8e354ccccb60390ea
Author
Leitwolf11 ·
Parents
d8183c8ffc2b

Files · Download .tar.gz

Changes

 CHANGELOG.md                               |   3 +-
 src/Progmasoft.Tazel/Project/FileClone.cs  | 134 +++++++++++++++++++++++++----
 tests/Progmasoft.Tazel.Tests/TrashTests.cs |  29 +++++++
 3 files changed, 146 insertions(+), 20 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c370a8..5e2b351 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,7 +11,8 @@
   [--dry-run]` and error code `E0511`.
 - Files copied by Tazel (test data now, cache outputs later) are cloned where the file system allows: `ioctl(FICLONE)`
   on Linux (Btrfs, XFS, bcachefs) and `clonefile` on macOS (APFS), for files of 64 KiB and more; elsewhere they are
-  copied as before. Windows block cloning is not wired yet.
+  copied as before. Windows uses `FSCTL_DUPLICATE_EXTENTS_TO_FILE` (ReFS, Dev Drive). A clone keeps the source's Unix
+  mode or Windows attributes, as an ordinary copy does.
 - Automatic Trash GC after a successful `build`, `run`, `test`, `coverage`, `fetch` or `vendor`, at most once a day under
   a lock: entries older than `trash-max-age` days (default 30), then the oldest above `trash-max-size` MiB (default
   10240). Both options are read only from `$TAZEL_HOME/User/tazel_options.txt`.
diff --git a/src/Progmasoft.Tazel/Project/FileClone.cs b/src/Progmasoft.Tazel/Project/FileClone.cs
index 2a28d0f..dfb8149 100644
--- a/src/Progmasoft.Tazel/Project/FileClone.cs
+++ b/src/Progmasoft.Tazel/Project/FileClone.cs
@@ -5,6 +5,7 @@ using System;
 using System.Collections.Concurrent;
 using System.IO;
 using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
 
 namespace Progmasoft.Tazel.Project;
 
@@ -14,20 +15,25 @@ namespace Progmasoft.Tazel.Project;
 /// never changes the original, which is why hard links are never used instead.
 /// </summary>
 /// <remarks>
-/// Linux uses <c>ioctl(FICLONE)</c> (Btrfs, XFS with reflink, bcachefs) and macOS <c>clonefile</c> (APFS). Windows
-/// block cloning (ReFS, Dev Drive) is not wired yet, so Windows copies. A file system that refused a clone once is not
-/// asked again during this process.
+/// Linux uses <c>ioctl(FICLONE)</c> (Btrfs, XFS with reflink, bcachefs), macOS <c>clonefile</c> (APFS) and Windows
+/// <c>FSCTL_DUPLICATE_EXTENTS_TO_FILE</c> (ReFS, Dev Drive). A clone keeps the source's permissions (Unix mode, Windows
+/// attributes) as <see cref="File.Copy(string, string)"/> does. A directory that refused a clone once is not asked again
+/// during this process.
 /// </remarks>
 public static partial class FileClone
 {
     /// <summary>Files smaller than this are copied: for them a copy costs less than the clone attempt.</summary>
     public static long Threshold { get; } = 64 * 1024;
 
-    private const uint FiClone = 0x40049409;
+    private const nuint FiClone = 0x40049409;
     private const int OCreat = 0x40;
     private const int OWronly = 0x01;
     private const int OExcl = 0x80;
     private const int ORdonly = 0x00;
+    private const uint FsctlDuplicateExtentsToFile = 0x00098344;
+
+    // At most this many bytes per FSCTL_DUPLICATE_EXTENTS_TO_FILE call, which takes less than 4 GiB.
+    private const long WindowsChunk = 1L << 30;
 
     private static readonly ConcurrentDictionary<string, bool> Refused = new(StringComparer.Ordinal);
 
@@ -50,8 +56,9 @@ public static partial class FileClone
         ArgumentNullException.ThrowIfNull(source);
         ArgumentNullException.ThrowIfNull(destination);
         var length = new FileInfo(source).Length;
-        if (length >= Threshold && TryClone(source, destination))
+        if (length >= Threshold && TryClone(source, destination, length))
         {
+            KeepPermissions(source, destination);
             return Result.Cloned;
         }
 
@@ -59,26 +66,24 @@ public static partial class FileClone
         return Result.Copied;
     }
 
-    private static bool TryClone(string source, string destination)
+    private static bool TryClone(string source, string destination, long length)
     {
-        var volume = Path.GetPathRoot(Path.GetFullPath(destination)) ?? "";
-        var key = $"{volume}|{Path.GetDirectoryName(Path.GetFullPath(destination))}";
+        var key = Path.GetDirectoryName(Path.GetFullPath(destination)) ?? "";
         if (Refused.ContainsKey(key))
         {
             return false;
         }
 
+        var created = false;
         bool cloned;
         try
         {
-            cloned = OperatingSystem.IsLinux() ? CloneLinux(source, destination)
-                : OperatingSystem.IsMacOS() && CloneMacOS(source, destination);
+            cloned = OperatingSystem.IsLinux() ? CloneLinux(source, destination, out created)
+                : OperatingSystem.IsMacOS() ? CloneMacOS(source, destination)
+                : OperatingSystem.IsWindows() && CloneWindows(source, destination, length, out created);
         }
-        catch (DllNotFoundException)
-        {
-            cloned = false;
-        }
-        catch (EntryPointNotFoundException)
+        catch (Exception problem) when (problem is DllNotFoundException or EntryPointNotFoundException or IOException or
+            UnauthorizedAccessException)
         {
             cloned = false;
         }
@@ -86,9 +91,10 @@ public static partial class FileClone
         if (!cloned)
         {
             Refused[key] = true;
-            if (File.Exists(destination) && new FileInfo(destination).Length == 0)
+            if (created)
             {
-                // A failed FICLONE leaves the empty file it opened; the ordinary copy needs the path free.
+                // Only what the attempt itself created goes, so the ordinary copy finds the path free; a file that was
+                // there before is left for File.Copy to refuse.
                 File.Delete(destination);
             }
         }
@@ -96,8 +102,22 @@ public static partial class FileClone
         return cloned;
     }
 
-    private static bool CloneLinux(string source, string destination)
+    private static void KeepPermissions(string source, string destination)
     {
+        if (OperatingSystem.IsWindows())
+        {
+            File.SetAttributes(destination, File.GetAttributes(source) & ~(FileAttributes.SparseFile | FileAttributes.Compressed));
+        }
+        else if (!OperatingSystem.IsMacOS())
+        {
+            // clonefile keeps the mode itself; FICLONE shares blocks only, and the file was opened 0644.
+            File.SetUnixFileMode(destination, File.GetUnixFileMode(source));
+        }
+    }
+
+    private static bool CloneLinux(string source, string destination, out bool created)
+    {
+        created = false;
         var from = Open(source, ORdonly, 0);
         if (from < 0)
         {
@@ -112,6 +132,7 @@ public static partial class FileClone
                 return false;
             }
 
+            created = true;
             try
             {
                 return Ioctl(to, FiClone, from) == 0;
@@ -129,15 +150,90 @@ public static partial class FileClone
 
     private static bool CloneMacOS(string source, string destination) => CloneFile(source, destination, 0) == 0;
 
+    private static bool CloneWindows(string source, string destination, long length, out bool created)
+    {
+        created = false;
+        if ((File.GetAttributes(source) & FileAttributes.SparseFile) != 0)
+        {
+            // A sparse source needs a sparse destination; an ordinary copy is simpler and as correct.
+            return false;
+        }
+
+        var root = Path.GetPathRoot(Path.GetFullPath(destination));
+        if (root is null || !GetDiskFreeSpace(root, out var sectorsPerCluster, out var bytesPerSector, out _, out _))
+        {
+            return false;
+        }
+
+        var cluster = (long)sectorsPerCluster * bytesPerSector;
+        using var from = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read);
+        using var to = new FileStream(destination, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
+        created = true;
+        to.SetLength(length);
+        var added = false;
+        from.SafeFileHandle.DangerousAddRef(ref added);
+        try
+        {
+            for (long offset = 0; offset < length; offset += WindowsChunk)
+            {
+                // Each range starts on a cluster boundary; the last one is rounded up to a whole cluster, which the
+                // file system allows at the end of the file.
+                var count = Math.Min(WindowsChunk, length - offset);
+                count = (count + cluster - 1) / cluster * cluster;
+                var data = new DuplicateExtentsData
+                {
+                    FileHandle = from.SafeFileHandle.DangerousGetHandle(),
+                    SourceFileOffset = offset,
+                    TargetFileOffset = offset,
+                    ByteCount = count,
+                };
+                if (!DeviceIoControl(to.SafeFileHandle, FsctlDuplicateExtentsToFile, ref data, Marshal.SizeOf<DuplicateExtentsData>(),
+                        IntPtr.Zero, 0, out _, IntPtr.Zero))
+                {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+        finally
+        {
+            if (added)
+            {
+                from.SafeFileHandle.DangerousRelease();
+            }
+        }
+    }
+
+    [StructLayout(LayoutKind.Sequential)]
+    private struct DuplicateExtentsData
+    {
+        public IntPtr FileHandle;
+        public long SourceFileOffset;
+        public long TargetFileOffset;
+        public long ByteCount;
+    }
+
     [LibraryImport("libc", EntryPoint = "open", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
     private static partial int Open(string path, int flags, int mode);
 
     [LibraryImport("libc", EntryPoint = "ioctl", SetLastError = true)]
-    private static partial int Ioctl(int fd, uint request, int argument);
+    private static partial int Ioctl(int fd, nuint request, int argument);
 
     [LibraryImport("libc", EntryPoint = "close", SetLastError = true)]
     private static partial int Close(int fd);
 
     [LibraryImport("libc", EntryPoint = "clonefile", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
     private static partial int CloneFile(string source, string destination, uint flags);
+
+    [LibraryImport("kernel32.dll", EntryPoint = "GetDiskFreeSpaceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
+    [return: MarshalAs(UnmanagedType.Bool)]
+    private static partial bool GetDiskFreeSpace(
+        string root, out uint sectorsPerCluster, out uint bytesPerSector, out uint freeClusters, out uint totalClusters);
+
+    [LibraryImport("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
+    [return: MarshalAs(UnmanagedType.Bool)]
+    private static partial bool DeviceIoControl(
+        SafeFileHandle device, uint code, ref DuplicateExtentsData input, int inputSize, IntPtr output, int outputSize,
+        out int returned, IntPtr overlapped);
 }
diff --git a/tests/Progmasoft.Tazel.Tests/TrashTests.cs b/tests/Progmasoft.Tazel.Tests/TrashTests.cs
index 2865606..947b09c 100644
--- a/tests/Progmasoft.Tazel.Tests/TrashTests.cs
+++ b/tests/Progmasoft.Tazel.Tests/TrashTests.cs
@@ -260,6 +260,35 @@ public sealed class TrashTests : IDisposable
         Assert.Throws<TrashException>(() => Trash.Find("0123456789"));
     }
 
+    [Fact]
+    [System.Runtime.Versioning.UnsupportedOSPlatform("windows")]
+    public void FileCloneKeepsTheSourcesModeWhicheverWayItCopies()
+    {
+        Assert.SkipWhen(OperatingSystem.IsWindows(), "Unix modes");
+        var source = Path.Combine(_home, "tool");
+        File.WriteAllBytes(source, new byte[FileClone.Threshold * 2]);
+        const UnixFileMode Executable = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |
+            UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute;
+        File.SetUnixFileMode(source, Executable);
+
+        var destination = Path.Combine(_home, "tool-copy");
+        FileClone.Copy(source, destination);
+        Assert.Equal(Executable, File.GetUnixFileMode(destination));
+    }
+
+    [Fact]
+    public void FileCloneNeverRemovesAFileThatWasAlreadyThere()
+    {
+        var source = Path.Combine(_home, "big.bin");
+        File.WriteAllBytes(source, new byte[FileClone.Threshold * 2]);
+        var destination = Path.Combine(_home, "already-there");
+        File.WriteAllBytes(destination, []);
+
+        Assert.Throws<IOException>(() => FileClone.Copy(source, destination));
+        Assert.True(File.Exists(destination));
+        Assert.Equal(0, new FileInfo(destination).Length);
+    }
+
     [Theory]
     [InlineData(10)]
     [InlineData(200_000)]