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

Keep Windows objects and programs free of the time

The cache policy tests failed on Windows: after --recompile the archive
ran again, and after --no-cache the next build ran four actions and the
test lost its cached pass. Clang targeting Windows stamps every COFF
object for incremental linking, and link.exe and lld-link stamp every
program, so the same sources gave other bytes each time.

- Compiling for Windows with clang adds -mno-incremental-linker-compatible.
- Linking for Windows adds -Wl,/Brepro with clang's MSVC driver and
  -Wl,--no-insert-timestamp with MinGW (a clang aimed at *-gnu or mingw,
  or gcc).
- Every action runs with SOURCE_DATE_EPOCH, 0 unless the user set one,
  which GCC and binutils read instead of the clock.

PlannerTests checks the flags for an MSVC and a MinGW clang and the
variable; the Linux snapshot is unchanged. 492 tests pass, 1 skipped.
Commit
1f9c4e3a50a2c32e0b5880bdf9c356a23952b03a
Author
Leitwolf11 ·
Parents
afd9622a21f6

Files · Download .tar.gz

Changes

 CHANGELOG.md                                 |  5 +++
 src/Progmasoft.Tazel/Driver/CCPlanner.cs     | 41 ++++++++++++++++++++++++-
 src/Progmasoft.Tazel/Driver/Processes.cs     |  4 +++
 tests/Progmasoft.Tazel.Tests/PlannerTests.cs | 46 ++++++++++++++++++++++++++++
 4 files changed, 95 insertions(+), 1 deletion(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7b3691e..96f7684 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,11 @@
 
 ## Unreleased
 
+- The same sources give the same objects and programs on Windows: clang compiles with
+  `-mno-incremental-linker-compatible` and links with `/Brepro` (MinGW: `--no-insert-timestamp`), and every action runs
+  with `SOURCE_DATE_EPOCH` (0 unless set). Before, each compilation stamped the time into the object, so the archive,
+  the program and its cached test ran again after any recompilation.
+
 - `--recompile` and `--no-cache` for `build`, `run`, `test` and `coverage`: every compilation runs, or every action and
   test runs with no cache read or written. zig compiles again with an empty cache of its own.
 
diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs
index 0a59d20..a49f846 100644
--- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs
+++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs
@@ -151,8 +151,10 @@ internal sealed partial class Planner
         var objectFile = $"{context.ObjectsDirectory}/{relative}.o";
         var cxx = language is SourceLanguage.Cpp or SourceLanguage.ObjectiveCpp;
         var settings = context.Settings;
-        var command = new List<string>((cxx ? context.Toolchain.Cpp : context.Toolchain.C).Command);
+        var compiler = cxx ? context.Toolchain.Cpp : context.Toolchain.C;
+        var command = new List<string>(compiler.Command);
         command.AddRange(ModeFlags());
+        command.AddRange(ReproducibleCompileFlags(compiler));
         command.AddRange(Flags(context.Features, ActionOf(language)));
         if (context.Pic)
         {
@@ -328,6 +330,7 @@ internal sealed partial class Planner
         var settings = (CCSettings)target.Settings;
         var command = new List<string>(toolchain.Linker.Command);
         command.AddRange(ModeFlags());
+        command.AddRange(ReproducibleLinkFlags(toolchain.Linker));
         command.AddRange(Flags(features, shared ? CCAction.CppLinkSharedLibrary : CCAction.CppLinkExecutable));
         var (output, after) = shared
             ? SharedLibraryOutput(target, (CCSharedLibrarySettings)settings, products, directory, command)
@@ -423,6 +426,42 @@ internal sealed partial class Planner
     private IEnumerable<string> ModeFlags() =>
         Options.Mode == BuildMode.Debug ? ["-g"] : ["-O2", "-DNDEBUG"];
 
+    /// <summary>
+    /// Keeps a compiler from writing the time into an object. Clang targeting Windows stamps every COFF object for
+    /// incremental linking unless told not to, so the same source would give another object, and the archive, the
+    /// program and its tests after it would run again. GCC takes SOURCE_DATE_EPOCH from the action environment.
+    /// </summary>
+    private IEnumerable<string> ReproducibleCompileFlags(Tool compiler) =>
+        Options.Platform.GetOS() == OS.Windows && IsClang(compiler) ? ["-mno-incremental-linker-compatible"] : [];
+
+    /// <summary>Keeps a linker from writing the time into a Windows program or library.</summary>
+    private IEnumerable<string> ReproducibleLinkFlags(Tool linker)
+    {
+        if (Options.Platform.GetOS() != OS.Windows)
+        {
+            return [];
+        }
+
+        if (IsClang(linker))
+        {
+            // link.exe and lld-link take /Brepro; the MinGW driver links with ld, which has its own switch.
+            return TargetsMinGW(linker) ? ["-Wl,--no-insert-timestamp"] : ["-Wl,/Brepro"];
+        }
+
+        var name = Path.GetFileNameWithoutExtension(linker.Program);
+        return name.EndsWith("gcc", StringComparison.Ordinal) || name.EndsWith("g++", StringComparison.Ordinal)
+            ? ["-Wl,--no-insert-timestamp"]
+            : [];
+    }
+
+    private static bool IsClang(Tool tool) =>
+        Path.GetFileNameWithoutExtension(tool.Program).Contains("clang", StringComparison.Ordinal);
+
+    private static bool TargetsMinGW(Tool tool) =>
+        Path.GetFileNameWithoutExtension(tool.Program).Contains("mingw", StringComparison.Ordinal) ||
+        tool.Prefix.Any(argument => argument.Contains("-gnu", StringComparison.Ordinal) ||
+            argument.Contains("mingw", StringComparison.Ordinal));
+
     /// <summary>Every target <paramref name="target"/> depends on, near or far, each once.</summary>
     private static List<ProjectTarget> Closure(ProjectTarget target)
     {
diff --git a/src/Progmasoft.Tazel/Driver/Processes.cs b/src/Progmasoft.Tazel/Driver/Processes.cs
index cd081f1..7ce00ff 100644
--- a/src/Progmasoft.Tazel/Driver/Processes.cs
+++ b/src/Progmasoft.Tazel/Driver/Processes.cs
@@ -210,6 +210,10 @@ internal static class Processes
             environment["ZERO_AR_DATE"] = "1";
         }
 
+        // Compilers, assemblers and linkers that would stamp the time into an output (GCC's __DATE__, binutils' PE and
+        // COFF headers) take it from here instead, so that the same inputs give the same bytes. A value the user set is
+        // kept: it is how a reproducible release names its own date.
+        environment["SOURCE_DATE_EPOCH"] = System.Environment.GetEnvironmentVariable("SOURCE_DATE_EPOCH") ?? "0";
         return environment;
     }
 
diff --git a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs
index 52da6dc..295f9af 100644
--- a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs
+++ b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs
@@ -161,6 +161,52 @@ public sealed class PlannerTests
         Assert.Contains($"builds for {other.Name()}", error.Message, StringComparison.Ordinal);
     }
 
+    [Theory]
+    [InlineData("clang", "-Wl,/Brepro")]
+    [InlineData("x86_64-w64-mingw32-clang", "-Wl,--no-insert-timestamp")]
+    public async Task WindowsObjectsAndProgramsCarryNoTime(string compiler, string linkFlag)
+    {
+        using var module = new TemporaryModule();
+        module.Write("MODULE.csx", TemporaryModule.ModuleFile + """
+
+                toolchains = Toolchains.Define("//toolchains:windows");
+                """)
+            .Write("toolchains/BUILD.csx", $$"""
+                using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude;
+                CC.Toolchain("windows", new()
+                {
+                    ExecutionPlatform = Platform.{{Host.Platform}},
+                    TargetPlatform = Platform.WindowsX64,
+                    Tools = new()
+                    {
+                        CCompiler = @"{{Path.Combine(module.Root, "tools", compiler)}}",
+                        CppCompiler = @"{{Path.Combine(module.Root, "tools", compiler + "++")}}",
+                        Archiver = @"{{Path.Combine(module.Root, "tools", "llvm-ar")}}",
+                    },
+                });
+                """)
+            .Write("BUILD.csx", """
+                using Progmasoft.Tazel.Dsl.Build.Prelude;
+                CC.Executable("app", new() { Sources = ["main.c"] });
+                """)
+            .Write("main.c", "")
+            .Write($"tools/{compiler}", "").Write($"tools/{compiler}++", "").Write("tools/llvm-ar", "");
+        var workspace = await Workspace.LoadAsync(module.Root, new BuildContext(BuildMode.Debug, Platform.WindowsX64),
+            new Version(0, 1, 0));
+        var planner = new Planner(workspace, new BuildOptions { Platform = Platform.WindowsX64 },
+            new ToolchainChooser(workspace, Platform.WindowsX64));
+        var actions = new List<BuildAction>();
+        Collect(planner.Plan(workspace.Targets[new TargetLabel(PackageId.Root, "app")]).Main!, actions);
+
+        var compile = actions.Single(action => action.Description.StartsWith("Compiling", StringComparison.Ordinal));
+        var link = actions.Single(action => action.Description.StartsWith("Linking", StringComparison.Ordinal));
+        Assert.Contains("-mno-incremental-linker-compatible", compile.Command);
+        Assert.Contains(linkFlag, link.Command);
+        // A date the user set is kept; otherwise the epoch.
+        Assert.Equal(Environment.GetEnvironmentVariable("SOURCE_DATE_EPOCH") ?? "0",
+            compile.Environment["SOURCE_DATE_EPOCH"]);
+    }
+
     private static void Collect(BuildAction action, List<BuildAction> into)
     {
         if (into.Contains(action))