fix: rebuild and relink on what changed, submodules at their revisions, and mingw found where it is
Some checks failed
Flatpak / flatpak (push) Failing after 1m12s

- Shaders record the files glslang opened (a depfile) and their settings
  (source path, stage, entry point, defines, include directories) in the
  build directory, and rebuild when an included file or a setting changes,
  not only the shader's own source.
- An executable relinks when its link command changed, not only when an
  object is newer: a link flag in project.cpp, or a dependency's library
  that moved (an ExternalDependency built into a new cache directory). The
  command is recorded beside the objects; its flags come from ordered sets,
  so the order the dependency threads finish in can't change it.
- An external's newest artifact counts its libDirs and versioned .so names.
- Submodules are checked out at the revisions the fetched commit records,
  from the URLs its .gitmodules gives, after every clone, switch, checkout
  and pull, so a pinned commit builds against its own submodules, and one
  moved by hand is put back; with no .gitmodules, git isn't asked.
- Each external clone's fetch and build hold a file lock: parallel builds
  pulled into one clone at once ("cannot lock ref").
- mingw:
  - -stdlib=libstdc++ always;
  - the std module's source is found through libstdc++.modules.json in the
    mingw toolchain's own library directories (the generic lib/ holds the
    host's Linux one), asking the compiler once a run;
  - a toolchain that isn't there is a build error saying where it looked,
    not std::terminate;
  - CRAFTER_MINGW_DIR names the prefix, the directory holding
    x86_64-w64-mingw32/ and lib/gcc/;
  - inside the Flatpak the host's /usr mingw is used.
- RunScript's exit-status check reads as the one range it is.
- Tests: ConcurrentExternalFetch, ExternalArtifactTime, GitSubmodules,
  LinkFlagsChange, MingwMissing, ShaderIncludeChange; ShaderCompile and
  ToolchainResolve extended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jorijn van der Graaf 2026-10-20 19:08:13 +02:00
commit 653dd0bb9b
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
26 changed files with 1075 additions and 109 deletions

View file

@ -60,7 +60,7 @@ glslang.includeDirs = { "" };
glslang.libs = { "SPIRV", "glslang", "OSDependent" }; glslang.libs = { "SPIRV", "glslang", "OSDependent" };
``` ```
Clones live at `~/.cache/crafter.build/external/<name>-<hash>/`, keyed by `(url, branch, commit, options)` so different projects sharing the same dep with the same spec reuse the clone and cmake build, while projects with diverging specs each get their own cache entry. The clone is resilient to partial-clone recovery and CMake reconfigure is triggered automatically on `options` changes. Clones live at `~/.cache/crafter.build/external/<name>-<hash>/`, keyed by `(url, branch, commit, options)` so different projects sharing the same dep with the same spec reuse the clone and cmake build, while projects with diverging specs each get their own cache entry. The clone is resilient to partial-clone recovery and CMake reconfigure is triggered automatically on `options` changes. Submodules are checked out at the revisions the fetched commit records, after every clone, switch, checkout and pull, so a pinned commit builds against its own submodules and not the default branch's.
**Header-only git deps** — same as cmake deps but `builder = ExternalBuilder::None`. Just clones and propagates `-I` flags. **Header-only git deps** — same as cmake deps but `builder = ExternalBuilder::None`. Just clones and propagates `-I` flags.
@ -147,7 +147,7 @@ For elaborate setups (rsync, ssh ControlMaster, env vars on the spawn, `QEMU_LD_
For cross-arch builds, set `cfg.sysroot` on the `Configuration` to point at a sysroot for the target. `BuildStdPcm` and the compile/link commands both consume it: `--sysroot=<path>` is passed to clang, and the std module is precompiled against the sysroot's libc++ headers. Ordinary compiles are pointed at the same headers (`-nostdinc++ -isystem <sysroot>/usr/include/c++/v1`), so a unit that `#include`s a standard header gets the sysroot's libc++ and not the host toolchain's. The module source has to come from the same libc++ release as those headers, so it is taken from `<sysroot>/usr/share/libc++/v1/std.cppm` when the sysroot ships it, else from the toolchain when both are the same major release, else from the sources crafter-build carries for other releases (`share/crafter-build/libc++-modules/<major>/`, `crafter-build --version` lists them). Alpine is the common case for the last two: its `libc++-dev` has the headers and no module source. When nothing matches, the build stops with one line naming both releases, installing that release's `share/libc++/v1` directory into the sysroot resolves it. The cheapest aarch64 sysroot is an extracted [Arch Linux ARM rootfs](http://os.archlinuxarm.org/) plus `libc++` + `libc++abi` + `gcc` installed into it via `pacman --root <rootfs> --config <alarm-pacman.conf> --dbpath <rootfs>/var/lib/pacman -Sy …` (point pacman at ALARM's mirrors via explicit config to avoid pulling host-arch packages). For cross-arch builds, set `cfg.sysroot` on the `Configuration` to point at a sysroot for the target. `BuildStdPcm` and the compile/link commands both consume it: `--sysroot=<path>` is passed to clang, and the std module is precompiled against the sysroot's libc++ headers. Ordinary compiles are pointed at the same headers (`-nostdinc++ -isystem <sysroot>/usr/include/c++/v1`), so a unit that `#include`s a standard header gets the sysroot's libc++ and not the host toolchain's. The module source has to come from the same libc++ release as those headers, so it is taken from `<sysroot>/usr/share/libc++/v1/std.cppm` when the sysroot ships it, else from the toolchain when both are the same major release, else from the sources crafter-build carries for other releases (`share/crafter-build/libc++-modules/<major>/`, `crafter-build --version` lists them). Alpine is the common case for the last two: its `libc++-dev` has the headers and no module source. When nothing matches, the build stops with one line naming both releases, installing that release's `share/libc++/v1` directory into the sysroot resolves it. The cheapest aarch64 sysroot is an extracted [Arch Linux ARM rootfs](http://os.archlinuxarm.org/) plus `libc++` + `libc++abi` + `gcc` installed into it via `pacman --root <rootfs> --config <alarm-pacman.conf> --dbpath <rootfs>/var/lib/pacman -Sy …` (point pacman at ALARM's mirrors via explicit config to avoid pulling host-arch packages).
For `--target=x86_64-w64-mingw32` (Windows from Linux), the pipeline cross-compiles as long as `mingw-w64` is installed. Pair it with `--runner=cmd:wine` to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. `-fuse-ld=lld` is auto-injected on every link, and `-lstdc++exp` is auto-linked for the mingw target so user projects don't need to declare those flags. For `--target=x86_64-w64-mingw32` (Windows from Linux), the pipeline cross-compiles as long as `mingw-w64` is installed, with libstdc++ 15 or newer for its std module. clang finds it by the `x86_64-w64-mingw32-gcc` on `PATH`; `CRAFTER_MINGW_DIR` names another prefix (the directory holding `x86_64-w64-mingw32/` and `lib/gcc/`), and inside the Flatpak the host's `/usr` is used when it has mingw-w64. Without one the build stops with a message saying where it looked. Pair it with `--runner=cmd:wine` to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. `-fuse-ld=lld` is auto-injected on every link, and `-lstdc++exp` is auto-linked for the mingw target so user projects don't need to declare those flags.
### Configuring runners ### Configuring runners

View file

@ -535,14 +535,14 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} }
for (const Shader& shader : config.shaders) { for (const Shader& shader : config.shaders) {
if (buildCancelled.load(std::memory_order_relaxed)) break; if (buildCancelled.load(std::memory_order_relaxed)) break;
if (shader.Check(outputDir)) continue; if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue;
threads.emplace_back([&shader, &outputDir, &shaderIncludeDirs, &buildError, &buildCancelled]() { threads.emplace_back([&shader, &outputDir, &buildDir, &shaderIncludeDirs, &buildError, &buildCancelled]() {
// A source registered more than once shows up once per variant; // A source registered more than once shows up once per variant;
// name the variant so the lines can be told apart. // name the variant so the lines can be told apart.
Progress::Task task(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant)); Progress::Task task(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant));
if (buildCancelled.load(std::memory_order_relaxed)) return; if (buildCancelled.load(std::memory_order_relaxed)) return;
std::string result = shader.Compile(outputDir, shaderIncludeDirs); std::string result = shader.Compile(outputDir, buildDir, shaderIncludeDirs);
if (result.empty()) return; if (result.empty()) return;
bool expected = false; bool expected = false;
@ -699,7 +699,13 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
std::string stdPcmResult; std::string stdPcmResult;
{ {
Progress::Task task(std::format("Building std PCM ({}-{})", config.target, config.march)); Progress::Task task(std::format("Building std PCM ({}-{})", config.target, config.march));
stdPcmResult = BuildStdPcm(config, stdPcmDir/"std.pcm"); // The shader and external threads are running: an exception leaving
// here would destroy them joinable, which terminates the process.
try {
stdPcmResult = BuildStdPcm(config, stdPcmDir/"std.pcm");
} catch (const std::exception& e) {
stdPcmResult = std::format("building the std module for {}: {}", config.target, e.what());
}
} }
if(!stdPcmResult.empty()) { if(!stdPcmResult.empty()) {
buildCancelled.store(true); buildCancelled.store(true);
@ -728,8 +734,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
const bool isWasm = config.target.starts_with("wasm32"); const bool isWasm = config.target.starts_with("wasm32");
std::string files; std::string files;
std::unordered_set<std::string> libSet; std::set<std::string> libSet;
std::unordered_set<std::string> publicFlagSet; std::set<std::string> publicFlagSet;
std::mutex fileMutex; std::mutex fileMutex;
std::vector<std::thread> depThreads; std::vector<std::thread> depThreads;
depThreads.reserve(config.dependencies.size()); depThreads.reserve(config.dependencies.size());
@ -804,6 +810,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
: std::format(" -march={} -mtune={}", config.march, config.mtune); : std::format(" -march={} -mtune={}", config.march, config.mtune);
if (!config.sysroot.empty()) { if (!config.sysroot.empty()) {
cArchFlags += std::format(" --sysroot={}", config.sysroot); cArchFlags += std::format(" --sysroot={}", config.sysroot);
} else if (config.target == "x86_64-w64-mingw32" && !GetToolchain().mingwSysroot.empty()) {
// The C++ side gets it through GetBaseCommand.
cArchFlags += std::format(" --sysroot={}", GetToolchain().mingwSysroot.string());
} }
if (cIsWasm) { if (cIsWasm) {
// Matches the C++ path's wasi flag set so any libc shim defines // Matches the C++ path's wasi flag set so any libc shim defines
@ -1149,8 +1158,48 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} }
} }
// The exact command the link (or archive) step runs, kept beside the
// objects once it has succeeded. A different one relinks even with no
// object newer than the output: a link flag changed in project.cpp, or a
// dependency's library moved, as an ExternalDependency's does when its
// options change and it is built into a new cache directory.
std::string linkCommand;
if (config.type == ConfigurationType::Executable) {
if (config.target.starts_with("wasm32")) {
linkCommand = std::format("{}{} -o {}.wasm -fuse-ld=lld{}", command, files, (outputDir/config.outputName).string(), linkExtras);
} else {
linkCommand = std::format("{}{} -o {} -fuse-ld=lld{}", command, files, (outputDir/config.outputName).string(), linkExtras);
}
} else if (config.type == ConfigurationType::LibraryStatic) {
// ThinLTO emits LLVM bitcode objects; plain `ar` writes an archive
// index that omits their symbols, so a consumer's lld link can't
// pull the needed members. llvm-ar writes a bitcode-aware index
// and handles plain ELF and COFF objects just as well, so every
// build uses it.
linkCommand = std::format("{} rcs {}.a {}", GetToolchain().llvmAr.string(), (outputDir/fs::path(std::string("lib")+config.outputName)).string(), files);
} else if (config.target == "x86_64-w64-mingw32") {
// LibraryDynamic. Output names follow each target's convention so
// consumers can link via the standard linker search:
// mingw: <name>.dll + lib<name>.dll.a (lld --out-implib)
// unix: lib<name>.so (rpath $ORIGIN)
fs::path dll = outputDir / std::format("{}.dll", config.outputName);
fs::path implib = outputDir / std::format("lib{}.dll.a", config.outputName);
linkCommand = std::format("{}{} -shared -o {} -Wl,--out-implib,{} -fuse-ld=lld{}", command, files, dll.string(), implib.string(), linkExtras);
} else {
linkCommand = std::format("{}{} -shared -o {}.so -Wl,-rpath,'$ORIGIN' -fuse-ld=lld{}", command, files, (outputDir/(std::string("lib")+config.outputName)).string(), linkExtras);
}
const fs::path linkRecord = buildDir / std::format("{}.link", config.outputName);
if (!buildResult.repack) {
std::ifstream recorded(linkRecord, std::ios::binary);
const std::string previous((std::istreambuf_iterator<char>(recorded)), std::istreambuf_iterator<char>());
if (previous != linkCommand) buildResult.repack = true;
}
if(buildResult.repack) { if(buildResult.repack) {
Progress::Task task(std::format("Linking {}", config.outputName)); Progress::Task task(std::format("Linking {}", config.outputName));
// The record goes first, so a link that fails leaves it stale.
std::error_code removed;
fs::remove(linkRecord, removed);
if(config.type == ConfigurationType::Executable) { if(config.type == ConfigurationType::Executable) {
if(config.target == "x86_64-w64-mingw32") { if(config.target == "x86_64-w64-mingw32") {
try { try {
@ -1181,30 +1230,10 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
return {e.what(), false, {}}; return {e.what(), false, {}};
} }
} }
if (config.target.starts_with("wasm32")) { }
buildResult.result = RunBuildCommand(std::format("{}{} -o {}.wasm -fuse-ld=lld{}", command, files, (outputDir/config.outputName).string(), linkExtras)); buildResult.result = RunBuildCommand(linkCommand);
} else { if (buildResult.result.empty()) {
buildResult.result = RunBuildCommand(std::format("{}{} -o {} -fuse-ld=lld{}", command, files, (outputDir/config.outputName).string(), linkExtras)); std::ofstream(linkRecord, std::ios::binary | std::ios::trunc) << linkCommand;
}
} else if(config.type == ConfigurationType::LibraryStatic) {
// ThinLTO emits LLVM bitcode objects; plain `ar` writes an archive
// index that omits their symbols, so a consumer's lld link can't
// pull the needed members. llvm-ar writes a bitcode-aware index
// and handles plain ELF and COFF objects just as well, so every
// build uses it.
buildResult.result = RunBuildCommand(std::format("{} rcs {}.a {}", GetToolchain().llvmAr.string(), (outputDir/fs::path(std::string("lib")+config.outputName)).string(), files));
} else {
// LibraryDynamic. Output names follow each target's convention so
// consumers can link via the standard linker search:
// mingw: <name>.dll + lib<name>.dll.a (lld --out-implib)
// unix: lib<name>.so (rpath $ORIGIN)
if (config.target == "x86_64-w64-mingw32") {
fs::path dll = outputDir / std::format("{}.dll", config.outputName);
fs::path implib = outputDir / std::format("lib{}.dll.a", config.outputName);
buildResult.result = RunBuildCommand(std::format("{}{} -shared -o {} -Wl,--out-implib,{} -fuse-ld=lld{}", command, files, dll.string(), implib.string(), linkExtras));
} else {
buildResult.result = RunBuildCommand(std::format("{}{} -shared -o {}.so -Wl,-rpath,'$ORIGIN' -fuse-ld=lld{}", command, files, (outputDir/(std::string("lib")+config.outputName)).string(), linkExtras));
}
} }
} }
@ -1689,7 +1718,10 @@ Environment:
instead of the compiler's own. instead of the compiler's own.
CRAFTER_BUILD_LIBCLANG Exact libclang to load for lint. CRAFTER_BUILD_LIBCLANG Exact libclang to load for lint.
CRAFTER_BUILD_WASI_SYSROOT WASI sysroot for wasm32 targets. CRAFTER_BUILD_WASI_SYSROOT WASI sysroot for wasm32 targets.
CRAFTER_MINGW_DIR mingw-w64 sysroot, passed as --sysroot. CRAFTER_MINGW_DIR mingw-w64 prefix (holding x86_64-w64-mingw32/
and lib/gcc/), passed as --sysroot. Default:
the mingw gcc on PATH; in the Flatpak, the
host's /usr when it has mingw-w64.
CRAFTER_BUILD_HOME Directory holding the module sources. CRAFTER_BUILD_HOME Directory holding the module sources.
Exit status: Exit status:

View file

@ -36,6 +36,18 @@ std::string FetchGit(const GitSource& source, const fs::path& cloneDir) {
if (r.exitCode != 0) return std::format("`{}` failed (exit {}): {}", cmd, r.exitCode, r.output); if (r.exitCode != 0) return std::format("`{}` failed (exit {}): {}", cmd, r.exitCode, r.output);
return std::nullopt; return std::nullopt;
}; };
// Submodules follow the checkout only when asked to: after every clone,
// switch, checkout or pull, so they match the revision that was fetched
// instead of whichever one was checked out before, from the URLs that
// revision's .gitmodules gives (sync). A no-op, and offline, when they
// already match, which puts back submodules moved by hand; and no git at
// all without any.
auto updateSubmodules = [&runGit](const fs::path& dir) -> std::optional<std::string> {
if (!fs::exists(dir / ".gitmodules")) return std::nullopt;
const std::string quoted = ShellQuote(dir.string());
if (auto err = runGit(std::format("git -C {} submodule sync --recursive", quoted))) return err;
return runGit(std::format("git -C {} submodule update --init --recursive", quoted));
};
if (fs::exists(cloneDir)) { if (fs::exists(cloneDir)) {
CommandResult remote = RunCommandChecked(std::format("git -C {} remote get-url origin", ShellQuote(cloneDir.string()))); CommandResult remote = RunCommandChecked(std::format("git -C {} remote get-url origin", ShellQuote(cloneDir.string())));
@ -51,6 +63,9 @@ std::string FetchGit(const GitSource& source, const fs::path& cloneDir) {
if (auto err = runGit(std::format("git -C {} fetch origin", ShellQuote(cloneDir.string())))) return *err; if (auto err = runGit(std::format("git -C {} fetch origin", ShellQuote(cloneDir.string())))) return *err;
if (auto err = runGit(std::format("git -C {} checkout {}", ShellQuote(cloneDir.string()), ShellQuote(source.commit)))) return *err; if (auto err = runGit(std::format("git -C {} checkout {}", ShellQuote(cloneDir.string()), ShellQuote(source.commit)))) return *err;
} }
// Also when the commit already matched: a clone made before
// submodules were updated has them at the default branch's.
if (auto err = updateSubmodules(cloneDir)) return *err;
return ""; return "";
} else { } else {
// No commit pinned — pull latest. The user opted into "track latest" // No commit pinned — pull latest. The user opted into "track latest"
@ -61,6 +76,7 @@ std::string FetchGit(const GitSource& source, const fs::path& cloneDir) {
} else { } else {
if (auto err = runGit(std::format("git -C {} pull", ShellQuote(cloneDir.string())))) return *err; if (auto err = runGit(std::format("git -C {} pull", ShellQuote(cloneDir.string())))) return *err;
} }
if (auto err = updateSubmodules(cloneDir)) return *err;
return ""; return "";
} }
} }
@ -73,7 +89,9 @@ std::string FetchGit(const GitSource& source, const fs::path& cloneDir) {
fs::path tmpDir = cloneDir; fs::path tmpDir = cloneDir;
tmpDir += std::format(".tmp.{:08x}{:08x}", rd(), rd()); tmpDir += std::format(".tmp.{:08x}{:08x}", rd(), rd());
if (auto err = runGit(std::format("git clone --recursive {} {}", ShellQuote(source.url), ShellQuote(tmpDir.string())))) { // Not --recursive: that checks out the default branch's submodules, and
// the requested revision's come once it is checked out.
if (auto err = runGit(std::format("git clone {} {}", ShellQuote(source.url), ShellQuote(tmpDir.string())))) {
if (fs::exists(tmpDir)) fs::remove_all(tmpDir); if (fs::exists(tmpDir)) fs::remove_all(tmpDir);
return *err; return *err;
} }
@ -89,6 +107,10 @@ std::string FetchGit(const GitSource& source, const fs::path& cloneDir) {
return *err; return *err;
} }
} }
if (auto err = updateSubmodules(tmpDir)) {
fs::remove_all(tmpDir);
return *err;
}
std::error_code ec; std::error_code ec;
fs::rename(tmpDir, cloneDir, ec); fs::rename(tmpDir, cloneDir, ec);
@ -124,6 +146,10 @@ std::string BuildInjectedCMakeFlags(const fs::path& cmakeBuildDir, std::string_v
out += " -DCMAKE_SYSTEM_NAME=Windows"; out += " -DCMAKE_SYSTEM_NAME=Windows";
out += std::format(" -DCMAKE_C_COMPILER_TARGET={}", target); out += std::format(" -DCMAKE_C_COMPILER_TARGET={}", target);
out += std::format(" -DCMAKE_CXX_COMPILER_TARGET={}", target); out += std::format(" -DCMAKE_CXX_COMPILER_TARGET={}", target);
// The libstdc++ and the mingw-w64 install the project's own compiles
// use (GetBaseCommand).
out += " -DCMAKE_CXX_FLAGS=-stdlib=libstdc++";
if (!tc.mingwSysroot.empty()) out += std::format(" -DCMAKE_SYSROOT={}", ShellQuote(tc.mingwSysroot.string()));
} }
fs::path absBuildDir = fs::absolute(cmakeBuildDir); fs::path absBuildDir = fs::absolute(cmakeBuildDir);
out += std::format(" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={}", ShellQuote(absBuildDir.string())); out += std::format(" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={}", ShellQuote(absBuildDir.string()));
@ -227,6 +253,9 @@ ExternalBuildResult Crafter::BuildExternal(const ExternalDependency& dep, std::s
} }
fs::path cloneDir = ExternalCloneDir(dep, target); fs::path cloneDir = ExternalCloneDir(dep, target);
// Builds running side by side (tests built in parallel, two
// crafter-builds) share the clone: one fetches and builds it at a time.
FileLock lock(fs::path(std::format("{}.lock", cloneDir.string())));
std::string fetchErr = FetchGit(dep.source, cloneDir); std::string fetchErr = FetchGit(dep.source, cloneDir);
if (!fetchErr.empty()) { if (!fetchErr.empty()) {
@ -273,13 +302,20 @@ ExternalBuildResult Crafter::BuildExternal(const ExternalDependency& dep, std::s
result.linkFlags.push_back(std::format("-l{}", lib)); result.linkFlags.push_back(std::format("-l{}", lib));
} }
if (fs::exists(cmakeBuildDir)) { // The newest library in every directory the link searches: the build
for (const auto& entry : fs::directory_iterator(cmakeBuildDir)) { // directory and the libDirs, where projects like msquic put theirs,
if (!entry.is_regular_file()) continue; // versioned names (libmsquic.so.2) included.
const fs::path& p = entry.path(); auto isLibrary = [](const std::string& name) {
if (p.extension() != ".a" && p.extension() != ".so") continue; return name.ends_with(".a") || name.ends_with(".so") || name.contains(".so.") || name.ends_with(".dll");
};
std::vector<fs::path> searched = { cmakeBuildDir };
for (const fs::path& libDir : dep.libDirs) searched.push_back(libDir.is_absolute() ? libDir : cmakeBuildDir / libDir);
for (const fs::path& dir : searched) {
std::error_code listEc;
for (fs::directory_iterator it(dir, listEc), end; !listEc && it != end; it.increment(listEc)) {
std::error_code ec; std::error_code ec;
fs::file_time_type t = entry.last_write_time(ec); if (!it->is_regular_file(ec) || !isLibrary(it->path().filename().string())) continue;
fs::file_time_type t = it->last_write_time(ec);
if (!ec && t > result.latestArtifact) result.latestArtifact = t; if (!ec && t > result.latestArtifact) result.latestArtifact = t;
} }
} }
@ -355,6 +391,8 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
fs::path cloneDir = externalRoot / std::format("{}-{}", name, srcHash); fs::path cloneDir = externalRoot / std::format("{}-{}", name, srcHash);
{ {
// One fetch of a clone at a time, as in BuildExternal.
FileLock lock(fs::path(std::format("{}.lock", cloneDir.string())));
const bool exists = fs::exists(cloneDir); const bool exists = fs::exists(cloneDir);
Progress::Task task(std::format("{} {}", exists ? "Updating" : "Cloning", name)); Progress::Task task(std::format("{} {}", exists ? "Updating" : "Cloning", name));
if (std::string err = FetchGit(spec.source, cloneDir); !err.empty()) { if (std::string err = FetchGit(spec.source, cloneDir); !err.empty()) {
@ -396,6 +434,8 @@ fs::path Crafter::GitFetch(const GitSource& source) {
fs::path cloneDir = externalRoot / std::format("{}-{:016x}", name, key); fs::path cloneDir = externalRoot / std::format("{}-{:016x}", name, key);
{ {
// One fetch of a clone at a time, as in BuildExternal.
FileLock lock(fs::path(std::format("{}.lock", cloneDir.string())));
const bool exists = fs::exists(cloneDir); const bool exists = fs::exists(cloneDir);
Progress::Task task(std::format("{} {}", exists ? "Updating" : "Cloning", name)); Progress::Task task(std::format("{} {}", exists ? "Updating" : "Cloning", name));
if (std::string err = FetchGit(source, cloneDir); !err.empty()) { if (std::string err = FetchGit(source, cloneDir); !err.empty()) {

View file

@ -33,27 +33,10 @@ namespace {
// pass through the lock before it reaches the compile steps that *read* those // pass through the lock before it reaches the compile steps that *read* those
// PCMs, so a reader never observes a half-written file. // PCMs, so a reader never observes a half-written file.
// //
// The lock lives in the OS, keyed on a `.lock` file in the cache dir, and is // A FileLock on a `.lock` file in the cache dir.
// released automatically when the descriptor/handle closes — including on struct CacheLock {
// process death — so an interrupted build can never leave a stale lock. The FileLock lock;
// descriptor is close-on-exec / non-inheritable so spawned clang processes explicit CacheLock(const fs::path& cacheDir) : lock(cacheDir / ".lock") {}
// don't keep the lock alive past our own release.
class CacheLock {
std::int32_t fd_ = -1;
public:
explicit CacheLock(const fs::path& cacheDir) {
fd_ = ::open((cacheDir / ".lock").c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (fd_ >= 0) {
while (::flock(fd_, LOCK_EX) != 0 && errno == EINTR) {}
}
}
~CacheLock() {
if (fd_ >= 0) {
::close(fd_); // closing the descriptor drops the flock
}
}
CacheLock(const CacheLock&) = delete;
CacheLock& operator=(const CacheLock&) = delete;
}; };
// The cached Crafter.Build PCMs are keyed by `<target>-<march>` alone, so // The cached Crafter.Build PCMs are keyed by `<target>-<march>` alone, so
@ -120,6 +103,51 @@ namespace {
buffer << in.rdbuf(); buffer << in.rdbuf();
return buffer.str(); return buffer.str();
} }
// The string value of `"key": "..."` in `object`, if it has one.
std::optional<std::string> JsonString(std::string_view object, std::string_view key) {
const std::string quoted = std::format("\"{}\"", key);
std::size_t at = object.find(quoted);
if (at == std::string_view::npos) return std::nullopt;
at = object.find_first_not_of(" \t\r\n", at + quoted.size());
if (at == std::string_view::npos || object[at] != ':') return std::nullopt;
at = object.find_first_not_of(" \t\r\n", at + 1);
if (at == std::string_view::npos || object[at] != '"') return std::nullopt;
std::string value;
for (std::size_t i = at + 1; i < object.size(); ++i) {
if (object[i] == '"') return value;
if (object[i] == '\\' && i + 1 < object.size()) ++i;
value += object[i];
}
return std::nullopt;
}
// The std module's "source-path" in a libstdc++.modules.json: the object
// in its "modules" array whose "logical-name" is "std". The manifest is
// a flat list of such objects, so each one is the text between its
// braces.
std::optional<std::string> StdModuleSourcePath(std::string_view manifest) {
for (std::size_t open = manifest.find('{', manifest.find("\"modules\"")); open != std::string_view::npos; open = manifest.find('{', open + 1)) {
const std::size_t close = manifest.find('}', open);
if (close == std::string_view::npos) break;
const std::string_view object = manifest.substr(open, close - open);
if (JsonString(object, "logical-name") == "std") return JsonString(object, "source-path");
}
return std::nullopt;
}
}
Crafter::FileLock::FileLock(const fs::path& path) {
fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (fd >= 0) {
while (::flock(fd, LOCK_EX) != 0 && errno == EINTR) {}
}
}
Crafter::FileLock::~FileLock() {
if (fd >= 0) {
::close(fd); // closing the descriptor drops the flock
}
} }
fs::path Crafter::GetCrafterBuildHome() { fs::path Crafter::GetCrafterBuildHome() {
@ -464,7 +492,7 @@ namespace {
std::mutex depMutex; std::mutex depMutex;
std::unordered_set<Configuration*> forced; std::unordered_set<Configuration*> forced;
std::unordered_set<Configuration*> walked; std::unordered_set<Configuration*> walked;
std::unordered_set<std::string> libs; std::set<std::string> libs;
for (const PragmaDependency& pragma : pragmas) { for (const PragmaDependency& pragma : pragmas) {
Configuration* cfg = nullptr; Configuration* cfg = nullptr;
@ -646,23 +674,52 @@ CommandResult Crafter::RunCommandWithTimeout(std::string_view cmd, std::chrono::
std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
CacheLock lock(stdPcm.parent_path()); CacheLock lock(stdPcm.parent_path());
if(config.target == "x86_64-w64-mingw32") { if(config.target == "x86_64-w64-mingw32") {
std::vector<std::string> folders; // libstdc++ 15 and newer install libstdc++.modules.json beside the
// library, naming the std module's source relative to itself. It is
// Iterate through the directory and collect all subdirectories // looked for in the library directories the compiler searches for
for (const auto& entry : fs::directory_iterator(GetToolchain().mingwSysroot / "include" / "c++")) { // this target, as it would look for libstdc++ itself, but only in
if (entry.is_directory()) { // those that belong to the mingw toolchain: the list also has the
folders.push_back(entry.path().filename().string()); // generic <prefix>/lib, where the host's own (Linux) libstdc++ keeps
// its manifest. A toolchain that isn't there is a build error, not
// an exception: Build() runs this with its worker threads started.
const Toolchain& tc = GetToolchain();
const std::string where = tc.mingwSysroot.empty()
? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH")
: std::format("under {}", tc.mingwSysroot.string());
const std::string missing = std::format("no mingw-w64 libstdc++ with the std module (libstdc++ 15 or newer) {}. Install mingw-w64, or point CRAFTER_MINGW_DIR at its prefix, the directory holding x86_64-w64-mingw32/ and lib/gcc/", where);
// Asked once a run for each compiler and target: every mingw
// configuration comes through here, up to date or not, and the answer
// costs a clang.
static std::mutex probeMutex;
static std::unordered_map<std::string, CommandResult> probes;
const std::string probe = std::format("{} --target={} -print-search-dirs", GetBaseCommand(config), config.target);
CommandResult dirs;
{
std::lock_guard guard(probeMutex);
auto found = probes.find(probe);
if (found == probes.end()) found = probes.emplace(probe, RunCommandChecked(probe)).first;
dirs = found->second;
}
if (dirs.exitCode != 0) return std::format("{}: {}", missing, dirs.output);
fs::path manifestPath;
constexpr std::string_view librariesLine = "libraries: =";
if (const std::size_t at = dirs.output.find(librariesLine); at != std::string::npos) {
const std::size_t end = dirs.output.find('\n', at);
const std::string list = dirs.output.substr(at + librariesLine.size(), end == std::string::npos ? std::string::npos : end - at - librariesLine.size());
for (const auto part : std::views::split(list, ':')) {
const fs::path dir(std::string_view(part.begin(), part.end()));
const bool mingwOwn = std::ranges::contains(dir, fs::path("x86_64-w64-mingw32"));
if (mingwOwn && fs::exists(dir / "libstdc++.modules.json")) {
manifestPath = dir / "libstdc++.modules.json";
break;
}
} }
} }
if (manifestPath.empty()) return missing;
// Sort the folders by version in descending order const std::optional<std::string> source = StdModuleSourcePath(FileBytes(manifestPath));
std::sort(folders.begin(), folders.end(), [](const std::string& a, const std::string& b) { if (!source) return std::format("{} names no std module", manifestPath.string());
return std::lexicographical_compare(b.begin(), b.end(), a.begin(), a.end()); const fs::path stdCc = (manifestPath.parent_path() / *source).lexically_normal();
}); if (!fs::exists(stdCc)) return std::format("{}, which {} names as the std module, is missing", stdCc.string(), manifestPath.string());
std::string mingWversion = folders.front();
fs::path stdCc = GetToolchain().mingwSysroot / "include" / "c++" / mingWversion / "bits" / "std.cc";
// -femulated-tls keeps PCM TLS access matching libstdc++'s emutls // -femulated-tls keeps PCM TLS access matching libstdc++'s emutls
// definitions; mismatch surfaces as undefined std::__once_callable. // definitions; mismatch surfaces as undefined std::__once_callable.
@ -751,9 +808,11 @@ std::string Crafter::GetBaseCommand(const Configuration& config) {
const Toolchain& tc = GetToolchain(); const Toolchain& tc = GetToolchain();
std::string command = tc.clangxx.string(); std::string command = tc.clangxx.string();
if (config.target == "x86_64-w64-mingw32") { if (config.target == "x86_64-w64-mingw32") {
// libstdc++ from the mingw toolchain, found by clang's own mingw // libstdc++ from the mingw toolchain, said outright: a clang built to
// discovery unless the sysroot was given explicitly. // default to libc++ (the Flatpak's) would otherwise reach for that.
if (tc.mingwSysrootExplicit) command += std::format(" --sysroot={}", tc.mingwSysroot.string()); // Found by clang's own mingw discovery unless there is a sysroot.
command += " -stdlib=libstdc++";
if (!tc.mingwSysroot.empty()) command += std::format(" --sysroot={}", tc.mingwSysroot.string());
return command; return command;
} }
command += " -stdlib=libc++"; command += " -stdlib=libc++";

View file

@ -87,7 +87,7 @@ returned; ctx.args holds the arguments.)msg");
}; };
try { try {
const std::int32_t code = found->run(ctx); const std::int32_t code = found->run(ctx);
if (code == 0 || (code >= 1 && code <= 255)) return code; if (code >= 0 && code <= 255) return code;
std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", found->name, code); std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", found->name, code);
return 1; return 1;
} catch (const std::exception& e) { } catch (const std::exception& e) {

View file

@ -8,6 +8,7 @@ module;
#include "../lib/DirStackFileIncluder.h" #include "../lib/DirStackFileIncluder.h"
module Crafter.Build:Shader_impl; module Crafter.Build:Shader_impl;
import :Shader; import :Shader;
import :Platform;
import std; import std;
namespace fs = std::filesystem; namespace fs = std::filesystem;
@ -31,6 +32,39 @@ namespace {
} }
return EShLangVertex; return EShLangVertex;
} }
// A path as a Make prerequisite, escaped the way NewestPrerequisite reads it.
std::string MakeEscaped(const std::string& path) {
std::string escaped;
for (const char c : path) {
if (c == ' ' || c == '\t' || c == '#') escaped += '\\';
if (c == '$') escaped += '$';
escaped += c;
}
return escaped;
}
std::string ReadFile(const fs::path& file) {
std::ifstream stream(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>());
}
// What a compile's output depends on besides files' contents, one line
// each: two entries of one source differ here, and an #include searched
// for from another source directory or in other directories can find
// another file.
std::string Settings(const Crafter::Shader& shader, std::span<const fs::path> includeDirs) {
std::string settings = std::format("source {}\nstage {}\nentry {}\n", fs::absolute(shader.path).string(), static_cast<int>(shader.type), shader.entrypoint);
for (const std::string& define : shader.defines) settings += std::format("define {}\n", define);
for (const fs::path& dir : includeDirs) settings += std::format("include {}\n", dir.string());
return settings;
}
// Where Compile records, for Check, what the output in the bin dir was
// built from: beside the configuration's objects, as their depfiles are.
fs::path Record(const Crafter::Shader& shader, const fs::path& buildDir, std::string_view kind) {
return buildDir / std::format("{}.{}", shader.OutputName().string(), kind);
}
} }
namespace Crafter { namespace Crafter {
@ -45,11 +79,25 @@ namespace Crafter {
name.replace_extension(variant.empty() ? std::string("spv") : std::format("{}.spv", variant)); name.replace_extension(variant.empty() ? std::string("spv") : std::format("{}.spv", variant));
return name; return name;
} }
bool Shader::Check(const fs::path& outputDir) const { bool Shader::Check(const fs::path& outputDir, const fs::path& buildDir, std::span<const fs::path> includeDirs) const {
fs::path spv = outputDir / OutputName(); std::error_code ec;
return fs::exists(spv) && fs::last_write_time(path) < fs::last_write_time(spv); const fs::file_time_type built = fs::last_write_time(outputDir / OutputName(), ec);
if (ec) return false;
// The source and every file it #included, as the last compile
// recorded them: without a record, or with an included file since
// deleted, NewestPrerequisite reads max(), which is stale.
if (std::max(fs::last_write_time(path), NewestPrerequisite(Record(*this, buildDir, "d"))) >= built) return false;
return ReadFile(Record(*this, buildDir, "settings")) == Settings(*this, includeDirs);
} }
std::string Shader::Compile(const fs::path& outputDir, std::span<const fs::path> includeDirs) const { std::string Shader::Compile(const fs::path& outputDir, const fs::path& buildDir, std::span<const fs::path> includeDirs) const {
// The records go first, so a compile that fails leaves the output
// stale, whatever it wrote.
const fs::path depFile = Record(*this, buildDir, "d");
const fs::path settingsFile = Record(*this, buildDir, "settings");
std::error_code removed;
fs::remove(depFile, removed);
fs::remove(settingsFile, removed);
EShLanguage glslangType = ToEShLanguage(type); EShLanguage glslangType = ToEShLanguage(type);
glslang::InitializeProcess(); glslang::InitializeProcess();
@ -157,6 +205,25 @@ namespace Crafter {
if (!spvLog.empty()) { if (!spvLog.empty()) {
return fail("SPIR-V codegen reported issues", std::move(spvLog)); return fail("SPIR-V codegen reported issues", std::move(spvLog));
} }
// What Check compares the output against next time: the source and
// the files it included, as absolute paths so that reading them back
// doesn't depend on the directory a build runs from, and the settings.
std::ofstream dep(depFile, std::ios::binary);
dep << MakeEscaped(fs::absolute(outputDir / filename).string()) << ": " << MakeEscaped(fs::absolute(path).string());
for (const std::string& included : includeDir.getIncludedFiles()) {
dep << " \\\n " << MakeEscaped(fs::absolute(included).string());
}
dep << '\n';
dep.close();
std::ofstream settings(settingsFile, std::ios::binary);
settings << Settings(*this, includeDirs);
settings.close();
if (!dep || !settings) {
fs::remove(depFile, removed);
fs::remove(settingsFile, removed);
return fail("failed to record what the shader was built from", buildDir.string());
}
glslang::FinalizeProcess(); glslang::FinalizeProcess();
return {}; return {};
} }

View file

@ -137,9 +137,10 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
} }
if (std::string_view dir = Env(in, "CRAFTER_MINGW_DIR"); !dir.empty()) { if (std::string_view dir = Env(in, "CRAFTER_MINGW_DIR"); !dir.empty()) {
tc.mingwSysroot = fs::path(dir); tc.mingwSysroot = fs::path(dir);
tc.mingwSysrootExplicit = true; } else if (!in.hostRoot.empty() && fs::exists(in.hostRoot / "usr" / "x86_64-w64-mingw32")) {
} else { // The sandbox has no mingw-w64 of its own, and no mingw gcc on PATH
tc.mingwSysroot = "/usr/x86_64-w64-mingw32"; // for clang to find one by.
tc.mingwSysroot = in.hostRoot / "usr";
} }
return tc; return tc;
} }
@ -157,6 +158,7 @@ const Toolchain& Crafter::GetToolchain() {
try { try {
in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path(); in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path();
} catch (const std::exception&) {} } catch (const std::exception&) {}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
Toolchain tc = ResolveToolchain(in); Toolchain tc = ResolveToolchain(in);
if (!tc.error.empty()) return tc; if (!tc.error.empty()) return tc;

View file

@ -14,12 +14,15 @@ export namespace Crafter {
struct BuildResult { struct BuildResult {
std::string result; std::string result;
bool repack; bool repack;
std::unordered_set<std::string> libs; // Sets in order: the commands they go into are compared with the ones
// recorded last time, so they come out the same however the
// dependency threads that fill them happen to finish.
std::set<std::string> libs;
// Compile flags (typically -I include paths) the dep wants its // Compile flags (typically -I include paths) the dep wants its
// consumers to see — sourced from its external dependencies' include // consumers to see — sourced from its external dependencies' include
// dirs so headers a dep exposes in its public modules are reachable // dirs so headers a dep exposes in its public modules are reachable
// when a consumer #includes them directly. Propagates transitively. // when a consumer #includes them directly. Propagates transitively.
std::unordered_set<std::string> publicCompileFlags; std::set<std::string> publicCompileFlags;
}; };
struct Define { struct Define {

View file

@ -14,6 +14,21 @@ namespace Crafter {
bool timedOut = false; bool timedOut = false;
std::int32_t signal = 0; std::int32_t signal = 0;
}; };
// An exclusive lock on the file `path` (created if missing), held from
// construction to destruction. An flock, so it keeps out the other
// threads of this process (each opens the file anew) and other
// crafter-build processes alike. The OS drops it when the descriptor
// closes, process death included, so an interrupted build never leaves a
// stale lock; the descriptor is close-on-exec, so the tools a holder
// spawns don't keep it past its release.
class FileLock {
std::int32_t fd = -1;
public:
explicit FileLock(const fs::path& path);
~FileLock();
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
};
std::string BuildStdPcm(const Configuration& config, fs::path stdPcm); std::string BuildStdPcm(const Configuration& config, fs::path stdPcm);
fs::path GetCacheDir(); fs::path GetCacheDir();
CommandResult RunCommandChecked(std::string_view command); CommandResult RunCommandChecked(std::string_view command);

View file

@ -38,16 +38,23 @@ namespace Crafter {
// gives "<name>.spv", "sets" gives "<name>.sets.spv". One file-name // gives "<name>.spv", "sets" gives "<name>.sets.spv". One file-name
// component: no path separators. Every entry of a configuration must // component: no path separators. Every entry of a configuration must
// end up with its own OutputName(); Build() fails if two collide, so // end up with its own OutputName(); Build() fails if two collide, so
// each extra compile of a source needs its own variant. Check() // each extra compile of a source needs its own variant.
// compares only the source's mtime: changing defines without touching
// the source leaves the old output in place.
std::string variant; std::string variant;
Shader(fs::path&& path, std::string&& entrypoint, ShaderType type); Shader(fs::path&& path, std::string&& entrypoint, ShaderType type);
// File name of the compiled SPIR-V, relative to the output directory. // File name of the compiled SPIR-V, relative to the output directory.
// The single source of truth for it: Check, Compile and the artifact // The single source of truth for it: Check, Compile and the artifact
// forwarding in Build() all go through here. // forwarding in Build() all go through here.
fs::path OutputName() const; fs::path OutputName() const;
bool Check(const fs::path& outputDir) const; // Whether the output in `outputDir` is up to date: newer than the
std::string Compile(const fs::path& outputDir, std::span<const fs::path> includeDirs) const; // source and than every file the source #included, and compiled with
// this entry's stage, entry point and defines, searching
// `includeDirs`. Compile records the last two in `buildDir`; without
// its record an output is stale.
bool Check(const fs::path& outputDir, const fs::path& buildDir, std::span<const fs::path> includeDirs) const;
// Compiles into `outputDir`, searching `includeDirs` for #include, and
// records what Check needs in `buildDir`: a depfile naming the source
// and every file it included, and the settings it was compiled with.
// Returns an error message, empty on success.
std::string Compile(const fs::path& outputDir, const fs::path& buildDir, std::span<const fs::path> includeDirs) const;
}; };
} }

View file

@ -37,12 +37,13 @@ export namespace Crafter {
// Empty when the crafter prefix is unknown; need not exist. // Empty when the crafter prefix is unknown; need not exist.
fs::path stdModulesDir; fs::path stdModulesDir;
fs::path wasiSysroot; fs::path wasiSysroot;
// Holds include/c++/<ver>/bits/std.cc for the mingw target. Passed to // The mingw-w64 install prefix, the directory that holds
// clang as --sysroot only when it was set explicitly: clang's own // x86_64-w64-mingw32/ and lib/gcc/x86_64-w64-mingw32/ (/usr for a
// mingw discovery handles the distro layout, and a --sysroot pointing // distro package), passed to clang as --sysroot for the mingw target.
// at the triple directory would lose crtbegin.o and libgcc. // Empty means clang's own discovery, which follows the mingw gcc on
// PATH. Set by CRAFTER_MINGW_DIR, else the host's /usr when running
// sandboxed and it has mingw-w64 (the sandbox's own /usr never does).
fs::path mingwSysroot; fs::path mingwSysroot;
bool mingwSysrootExplicit = false;
// `clang++ -print-target-triple` and the first line of // `clang++ -print-target-triple` and the first line of
// `clang++ --version`; both empty when clang++ could not be run. // `clang++ --version`; both empty when clang++ could not be run.
std::string hostTriple; std::string hostTriple;
@ -72,6 +73,9 @@ export namespace Crafter {
std::map<std::string, std::string, std::less<>> env; std::map<std::string, std::string, std::less<>> env;
// The <prefix> of <prefix>/share/crafter-build; empty when unknown. // The <prefix> of <prefix>/share/crafter-build; empty when unknown.
fs::path crafterPrefix; fs::path crafterPrefix;
// Where the host's root shows inside a sandbox (/run/host in a
// Flatpak); empty outside one.
fs::path hostRoot;
}; };
// Pure path resolution: an env override wins, then a toolchain installed // Pure path resolution: an env override wins, then a toolchain installed
// beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on // beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on

View file

@ -256,6 +256,12 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("CleanProject").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("CleanProject").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ShaderCompile").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderCompile").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ShaderVariantBuild").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderVariantBuild").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ShaderIncludeChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("MingwMissing").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("GitSubmodules").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("LinkFlagsChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ExternalArtifactTime").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ConcurrentExternalFetch").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StandardArgs").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StandardArgs").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("TestRunnerSpec").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("TestRunnerSpec").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("VariantId").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("VariantId").Dependencies({ CrafterBuildLib.get() });

View file

@ -0,0 +1,95 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// Builds that run at the same time share their dependencies' clones in the
// cache: the tests `crafter-build test --jobs=N` builds side by side each
// declare the same ExternalDependency, and two crafter-builds can run at
// once. Fetching a clone that already exists ran `git pull` (and the CMake
// build) in it with nothing to keep a second fetch out, and the second git
// fails on the first one's index.lock. A clone's fetch and build now hold a
// lock of their own.
//
// Eight threads fetch the same tracked branch of a local repository at
// once, a few rounds over, the branch moving between rounds so every pull
// has work to do; every fetch has to succeed. Everything is local;
// XDG_CACHE_HOME keeps the clone out of the real cache.
extern "C" int setenv(const char* name, const char* value, int overwrite);
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
void Git(const fs::path& dir, std::string_view args) {
const std::string command = std::format("git -C {} {}", ShellQuote(dir.string()), args);
auto result = RunCommandWithTimeout(command, std::chrono::seconds(60));
if (result.exitCode != 0) throw std::runtime_error(std::format("{} failed: {}", command, result.output));
}
void Commit(const fs::path& repo, std::uint32_t round) {
std::ofstream(repo / "round.txt", std::ios::binary | std::ios::trunc) << round;
Git(repo, "add round.txt");
Git(repo, std::format("commit -q -m round-{}", round));
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-concurrent-external-fetch";
fs::remove_all(scratch);
fs::create_directories(scratch);
setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1);
setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
setenv("GIT_CONFIG_GLOBAL", "/dev/null", 1);
for (const char* name : { "GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME" }) setenv(name, "crafter-build test", 1);
for (const char* name : { "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL" }) setenv(name, "test@example.invalid", 1);
const fs::path repo = scratch / "shared";
fs::create_directories(repo);
Git(repo, "init -q -b main");
Commit(repo, 0);
const GitSource source { .url = std::format("file://{}", repo.string()), .branch = "main" };
const fs::path clone = GitFetch(source);
constexpr std::uint32_t threads = 8;
constexpr std::uint32_t rounds = 4;
std::vector<std::string> errors;
std::mutex errorsMutex;
for (std::uint32_t round = 1; round <= rounds; ++round) {
Commit(repo, round);
std::vector<std::jthread> fetchers;
for (std::uint32_t i = 0; i < threads; ++i) {
fetchers.emplace_back([&] {
try {
(void)GitFetch(source);
} catch (const std::exception& e) {
std::lock_guard lock(errorsMutex);
errors.push_back(e.what());
}
});
}
}
Check(errors.empty(), std::format("{} fetches at once, {} rounds: every one succeeds ({} failed{}{})", threads, rounds, errors.size(), errors.empty() ? "" : ", the first: ", errors.empty() ? "" : errors.front()));
std::ifstream round(clone / "round.txt");
std::uint32_t last = 0;
round >> last;
Check(last == rounds, std::format("and the clone ends at the last round ({})", last));
std::error_code ec;
fs::remove_all(scratch, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,89 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// A CMake dependency's newest library decides when its consumers are stale
// (BuildExternal's latestArtifact). Only files directly in the CMake build
// directory named *.a or *.so were looked at, so msquic's
// bin/Release/libmsquic.so.2, in one of the dependency's libDirs and with a
// version after the .so, never counted: a rebuilt msquic left everything
// built against the old one in place.
//
// The dependency here is a local repository whose CMake project puts a
// versioned shared library in bin/Release, declared as a libDir. Everything
// is local; XDG_CACHE_HOME keeps the clone out of the real cache.
extern "C" int setenv(const char* name, const char* value, int overwrite);
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
void Git(const fs::path& dir, std::string_view args) {
const std::string command = std::format("git -C {} {}", ShellQuote(dir.string()), args);
auto result = RunCommandWithTimeout(command, std::chrono::seconds(60));
if (result.exitCode != 0) throw std::runtime_error(std::format("{} failed: {}", command, result.output));
}
void Write(const fs::path& file, std::string_view text) {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-external-artifact-time";
fs::remove_all(scratch);
fs::create_directories(scratch);
setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1);
setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
setenv("GIT_CONFIG_GLOBAL", "/dev/null", 1);
for (const char* name : { "GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME" }) setenv(name, "crafter-build test", 1);
for (const char* name : { "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL" }) setenv(name, "test@example.invalid", 1);
const fs::path repo = scratch / "versioned";
fs::create_directories(repo);
Write(repo / "lib.c", "int Versioned(void) { return 2; }\n");
Write(repo / "CMakeLists.txt",
"cmake_minimum_required(VERSION 3.16)\n"
"project(versioned C)\n"
"add_library(versioned SHARED lib.c)\n"
"set_target_properties(versioned PROPERTIES VERSION 2.0.0 SOVERSION 2\n"
" LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin/Release)\n");
Git(repo, "init -q -b main");
Git(repo, "add .");
Git(repo, "commit -q -m versioned");
ExternalDependency dep;
dep.name = "versioned";
dep.source.url = std::format("file://{}", repo.string());
dep.builder = ExternalBuilder::CMake;
dep.libDirs = { "bin/Release" };
dep.libs = { "versioned" };
std::atomic<bool> cancelled = false;
const ExternalBuildResult result = BuildExternal(dep, HostTarget(), cancelled);
Check(result.error.empty(), std::format("the dependency builds: {}", result.error));
const fs::path library = ExternalCloneDir(dep, HostTarget()) / "build" / "bin" / "Release" / "libversioned.so.2.0.0";
Check(fs::exists(library), std::format("the library is where its CMake project puts it: {}", library.string()));
if (fs::exists(library)) {
Check(result.latestArtifact == fs::last_write_time(library), "its newest artifact is the versioned library in the libDir");
}
std::error_code ec;
fs::remove_all(scratch, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,128 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// A fetched dependency's submodules have to match the revision it was fetched
// at. They used to come from the remote's default branch: a fresh clone was
// `git clone --recursive`, which checks out the default branch's submodules,
// and the `switch` or `checkout` to the requested branch or commit that came
// after it left them where they were. A branch that was pulled forward kept
// the submodules of its old tip as well. So pinning msquic to a release built
// that release against the main branch's quictls.
//
// The test makes a repository whose submodule moves between two of its
// commits, then fetches it four ways through GitFetch:
// - pinned to the older commit;
// - by a branch at the older commit;
// - by a branch that is then moved to the newer commit and fetched again;
// - pinned again after the cached clone's submodule was checked out
// elsewhere, as an older crafter-build left it.
// Everything is local; XDG_CACHE_HOME keeps the clones out of the real cache.
extern "C" int setenv(const char* name, const char* value, int overwrite);
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
// Runs git in `dir`; the output, or an exception naming the command.
std::string Git(const fs::path& dir, std::string_view args) {
const std::string command = std::format("git -C {} {}", ShellQuote(dir.string()), args);
auto result = RunCommandWithTimeout(command, std::chrono::seconds(60));
if (result.exitCode != 0) throw std::runtime_error(std::format("{} failed: {}", command, result.output));
while (!result.output.empty() && (result.output.back() == '\n' || result.output.back() == '\r')) result.output.pop_back();
return result.output;
}
void Write(const fs::path& file, std::string_view text) {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
}
std::string Read(const fs::path& file) {
std::ifstream stream(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>());
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-git-submodules";
fs::remove_all(scratch);
fs::create_directories(scratch);
setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1);
// A known git: no user or system configuration, an identity for the
// commits, and file:// allowed for submodules (git refuses it by default),
// also for the git that GitFetch runs.
setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
setenv("GIT_CONFIG_GLOBAL", "/dev/null", 1);
setenv("GIT_CONFIG_COUNT", "1", 1);
setenv("GIT_CONFIG_KEY_0", "protocol.file.allow", 1);
setenv("GIT_CONFIG_VALUE_0", "always", 1);
for (const char* name : { "GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME" }) setenv(name, "crafter-build test", 1);
for (const char* name : { "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL" }) setenv(name, "test@example.invalid", 1);
// The submodule: "one", then "two".
const fs::path sub = scratch / "sub";
fs::create_directories(sub);
Git(sub, "init -q -b main");
Write(sub / "value.txt", "one");
Git(sub, "add value.txt");
Git(sub, "commit -q -m one");
const std::string one = Git(sub, "rev-parse HEAD");
Write(sub / "value.txt", "two");
Git(sub, "commit -q -am two");
const std::string two = Git(sub, "rev-parse HEAD");
// The superproject: `older` has the submodule at "one", main at "two".
const fs::path super = scratch / "super";
fs::create_directories(super);
Git(super, "init -q -b main");
Git(super, std::format("submodule --quiet add {} lib", ShellQuote(std::format("file://{}", sub.string()))));
Git(super / "lib", std::format("checkout -q {}", one));
Git(super, "add lib");
Git(super, "commit -q -m older");
const std::string older = Git(super, "rev-parse HEAD");
Git(super, "branch older");
Git(super, "branch track");
Git(super / "lib", std::format("checkout -q {}", two));
Git(super, "add lib");
Git(super, "commit -q -m newer");
const std::string url = std::format("file://{}", super.string());
// ── Pinned to the older commit ───────────────────────────────────────────
const fs::path pinned = GitFetch({ .url = url, .commit = older });
Check(Read(pinned / "lib" / "value.txt") == "one", std::format("a commit pin gets that commit's submodule (lib says {})", Read(pinned / "lib" / "value.txt")));
// ── By a branch at the older commit ──────────────────────────────────────
const fs::path branch = GitFetch({ .url = url, .branch = "older" });
Check(Read(branch / "lib" / "value.txt") == "one", std::format("a branch gets its own tip's submodule (lib says {})", Read(branch / "lib" / "value.txt")));
// ── A tracked branch moving forward ──────────────────────────────────────
const fs::path tracked = GitFetch({ .url = url, .branch = "track" });
Check(Read(tracked / "lib" / "value.txt") == "one", "a tracked branch starts with its tip's submodule");
Git(super, "branch -f track main");
const fs::path pulled = GitFetch({ .url = url, .branch = "track" });
Check(pulled == tracked && Read(pulled / "lib" / "value.txt") == "two", std::format("pulling it forward moves the submodule along (lib says {})", Read(pulled / "lib" / "value.txt")));
// ── A cached clone with its submodule out of step ────────────────────────
Git(pinned / "lib", std::format("checkout -q {}", two));
const fs::path repaired = GitFetch({ .url = url, .commit = older });
Check(repaired == pinned && Read(repaired / "lib" / "value.txt") == "one", std::format("a cached clone at the pin gets its submodule put back (lib says {})", Read(repaired / "lib" / "value.txt")));
std::error_code ec;
fs::remove_all(scratch, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
int main() {
return 0;
}

View file

@ -0,0 +1,119 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// A change to what an executable is linked with has to relink it, even when
// no object changed. The relink check compared modification times only, so a
// link flag added in project.cpp, or a dependency's library moving (an
// ExternalDependency whose options changed is fetched and built into a new
// cache directory, and its -L and rpath follow), left the old binary in
// place: Crafter.Network's tests kept loading the msquic they were first
// linked against.
//
// The test adds an rpath to an executable's link flags, takes it away again,
// and then builds once more with nothing changed, which must not relink.
// The flags come out of sets the dependency threads fill as they finish, so
// the recorded command lists them sorted: in the order they happened to land
// in, an unchanged build could look like a changed one.
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
constexpr std::string_view marker = "/crafter-build-link-flags-change-marker";
BuildResult BuildOnce(const fs::path& project, std::vector<std::string> linkFlags) {
Configuration app;
app.path = project;
app.name = "linked";
app.outputName = "linked";
app.target = HostTarget();
app.type = ConfigurationType::Executable;
app.linkFlags = std::move(linkFlags);
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult result = Build(app, depResults, depMutex);
return result;
}
Configuration Plain(const fs::path& project) {
Configuration app;
app.path = project;
app.name = "linked";
app.outputName = "linked";
app.target = HostTarget();
app.type = ConfigurationType::Executable;
return app;
}
fs::path Binary(const fs::path& project) {
return Plain(project).BinDir() / "linked";
}
bool HasMarker(const fs::path& binary) {
std::ifstream stream(binary, std::ios::binary);
const std::string bytes((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
return bytes.find(marker) != std::string::npos;
}
}
int main() {
const fs::path project = fs::temp_directory_path() / "crafter-build-link-flags-change";
fs::remove_all(project);
fs::copy(fs::current_path() / "tests" / "LinkFlagsChange" / "fixture", project, fs::copy_options::recursive);
const std::string rpath = std::format("-Wl,-rpath,{}", marker);
const BuildResult first = BuildOnce(project, {});
Check(first.result.empty(), std::format("the plain build succeeds: {}", first.result));
const fs::path binary = Binary(project);
Check(fs::exists(binary) && !HasMarker(binary), "the plain binary has no rpath to the marker");
const BuildResult added = BuildOnce(project, { rpath });
Check(added.result.empty(), std::format("the build with the rpath succeeds: {}", added.result));
Check(HasMarker(binary), "adding a link flag relinks the binary");
const BuildResult removed = BuildOnce(project, {});
Check(removed.result.empty(), std::format("the build without it succeeds: {}", removed.result));
Check(!HasMarker(binary), "taking it away relinks it again");
const fs::file_time_type linked = fs::last_write_time(binary);
const BuildResult again = BuildOnce(project, {});
Check(again.result.empty() && fs::last_write_time(binary) == linked, "an unchanged build doesn't relink");
const std::vector<std::string> flags = { "-Wl,-z,now", "-Wl,-O1", "-Wl,--as-needed", "-Wl,-z,relro", "-Wl,--build-id", "-Wl,--hash-style=gnu" };
const BuildResult many = BuildOnce(project, flags);
Check(many.result.empty(), std::format("the build with six flags succeeds: {}", many.result));
std::ifstream recorded(Plain(project).BuildDir() / "linked.link", std::ios::binary);
const std::string record((std::istreambuf_iterator<char>(recorded)), std::istreambuf_iterator<char>());
std::vector<std::size_t> at;
for (const std::string& flag : flags) at.push_back(record.find(std::format(" {}", flag)));
std::vector<std::string> sorted = flags;
std::ranges::sort(sorted);
bool inOrder = !std::ranges::contains(at, std::string::npos);
for (std::size_t k = 0; inOrder && k + 1 < sorted.size(); ++k) {
const auto index = [&](const std::string& flag) { return at[static_cast<std::size_t>(std::ranges::find(flags, flag) - flags.begin())]; };
inOrder = index(sorted[k]) < index(sorted[k + 1]);
}
Check(inOrder, std::format("the link record lists the flags sorted: {}", record));
std::error_code ec;
fs::remove_all(project, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("hello from crafter-build");
return 0;
}

View file

@ -0,0 +1,97 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// Building for x86_64-w64-mingw32 without a usable mingw-w64 libstdc++ has to
// fail the build with a message that says what is missing. It used to abort
// the whole process with a bare "libc++abi: terminating": the std module's
// source was found by listing <mingw sysroot>/include/c++ with a throwing
// directory_iterator, the exception unwound through Build() while its worker
// threads were still joinable, and ~thread called std::terminate. That is
// what every mingw build inside the Flatpak did, as the sandbox has no
// /usr/x86_64-w64-mingw32.
//
// The std module's source is now found through libstdc++.modules.json in the
// mingw toolchain's library directories. CRAFTER_MINGW_DIR points the
// toolchain at a scratch prefix, which the test takes through four states:
// - missing;
// - with only a manifest in the prefix's generic lib/, where the host's
// Linux libstdc++ keeps one: not the mingw library, so still missing;
// - with a mingw manifest that names no std module;
// - with one whose std module source isn't there.
extern "C" int setenv(const char* name, const char* value, int overwrite);
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
BuildResult BuildOnce(const fs::path& project) {
Configuration app;
app.path = project;
app.name = "hello";
app.outputName = "hello";
app.target = "x86_64-w64-mingw32";
app.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(app, depResults, depMutex);
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-mingw-missing";
fs::remove_all(scratch);
fs::create_directories(scratch);
const fs::path project = scratch / "project";
fs::copy(fs::current_path() / "tests" / "MingwMissing" / "fixture", project, fs::copy_options::recursive);
const fs::path sysroot = scratch / "mingw";
// Before anything resolves the toolchain, which reads both once. The std
// module cache goes to the scratch directory too.
setenv("CRAFTER_MINGW_DIR", sysroot.c_str(), 1);
setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1);
const BuildResult missing = BuildOnce(project);
Check(!missing.result.empty(), "a missing mingw prefix fails the build");
Check(missing.result.contains("mingw") && missing.result.contains(sysroot.string()) && missing.result.contains("CRAFTER_MINGW_DIR"), std::format("and says where it looked and how to point elsewhere: {}", missing.result));
auto write = [](const fs::path& file, std::string_view text) {
fs::create_directories(file.parent_path());
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
};
write(sysroot / "lib" / "libstdc++.modules.json", R"({"version": 1, "modules": [{"logical-name": "std", "source-path": "../include/c++/16/bits/std.cc", "is-std-library": true}]})");
write(sysroot / "include" / "c++" / "16" / "bits" / "std.cc", "// the host's Linux std module\n");
const BuildResult linux = BuildOnce(project);
Check(linux.result.contains("no mingw-w64 libstdc++"), std::format("a manifest outside the mingw toolchain's own directories isn't taken for it: {}", linux.result));
const fs::path manifest = sysroot / "x86_64-w64-mingw32" / "lib" / "libstdc++.modules.json";
write(manifest, R"({"version": 1, "modules": [{"logical-name": "std.compat", "source-path": "../include/c++/15.1.0/bits/std.compat.cc"}]})");
const BuildResult noStd = BuildOnce(project);
Check(noStd.result.contains(manifest.string()) && noStd.result.contains("no std module"), std::format("a manifest without the std module fails the build, naming the manifest: {}", noStd.result));
write(manifest, R"({"version": 1, "modules": [{"source-path": "../include/c++/15.1.0/bits/std.cc", "logical-name": "std"}]})");
const BuildResult noSource = BuildOnce(project);
Check(noSource.result.contains((sysroot / "x86_64-w64-mingw32" / "include" / "c++" / "15.1.0" / "bits" / "std.cc").string()) && noSource.result.contains("missing"),
std::format("a std module source that isn't there fails the build, naming it: {}", noSource.result));
std::error_code ec;
fs::remove_all(scratch, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -27,7 +27,7 @@ int main() {
Shader shader(fs::path(src), "main", ShaderType::Fragment); Shader shader(fs::path(src), "main", ShaderType::Fragment);
std::array<fs::path, 0> includeDirs = {}; std::array<fs::path, 0> includeDirs = {};
std::string err = shader.Compile(outDir, includeDirs); std::string err = shader.Compile(outDir, outDir, includeDirs);
if (!err.empty()) { if (!err.empty()) {
std::println(std::cerr, "shader compile failed: {}", err); std::println(std::cerr, "shader compile failed: {}", err);
return 1; return 1;
@ -51,10 +51,27 @@ int main() {
} }
// Compiling again should be a no-op since the source isn't newer. // Compiling again should be a no-op since the source isn't newer.
if (!shader.Check(outDir)) { if (!shader.Check(outDir, outDir, includeDirs)) {
std::println(std::cerr, "Shader::Check returned false on an up-to-date spv"); std::println(std::cerr, "Shader::Check returned false on an up-to-date spv");
return 1; return 1;
} }
// Searched elsewhere, an #include could find another file: stale.
const std::array<fs::path, 1> elsewhere = { outDir / "elsewhere" };
if (shader.Check(outDir, outDir, elsewhere)) {
std::println(std::cerr, "Shader::Check called an spv up to date for other include directories");
return 1;
}
// So could a source of the same name moved to another directory, which
// its #includes are searched from first.
const fs::path movedDir = outDir / "moved";
fs::create_directories(movedDir);
fs::copy_file(src, movedDir / src.filename());
fs::last_write_time(movedDir / src.filename(), fs::last_write_time(src));
Shader moved(movedDir / src.filename(), "main", ShaderType::Fragment);
if (moved.Check(outDir, outDir, includeDirs)) {
std::println(std::cerr, "Shader::Check called an spv up to date for a source of the same name elsewhere");
return 1;
}
// One source registered twice: the second entry carries defines and a // One source registered twice: the second entry carries defines and a
// variant name. It must land in its own file instead of overwriting the // variant name. It must land in its own file instead of overwriting the
@ -77,16 +94,16 @@ int main() {
// exists, the variant is still due. A Check() that ignored the // exists, the variant is still due. A Check() that ignored the
// variant would call it up to date here, and Build() would then // variant would call it up to date here, and Build() would then
// never compile a variant added to an already built project. // never compile a variant added to an already built project.
if (each == &red && red.Check(outDir)) { if (each == &red && red.Check(outDir, outDir, includeDirs)) {
std::println(std::cerr, "Shader::Check called the variant up to date before it was ever compiled"); std::println(std::cerr, "Shader::Check called the variant up to date before it was ever compiled");
return 1; return 1;
} }
std::string variantErr = each->Compile(outDir, includeDirs); std::string variantErr = each->Compile(outDir, outDir, includeDirs);
if (!variantErr.empty()) { if (!variantErr.empty()) {
std::println(std::cerr, "variant shader compile failed: {}", variantErr); std::println(std::cerr, "variant shader compile failed: {}", variantErr);
return 1; return 1;
} }
if (!each->Check(outDir)) { if (!each->Check(outDir, outDir, includeDirs)) {
std::println(std::cerr, "Shader::Check returned false for {}", each->OutputName().string()); std::println(std::cerr, "Shader::Check returned false for {}", each->OutputName().string());
return 1; return 1;
} }
@ -99,14 +116,14 @@ int main() {
Shader malformed(fs::path(variantSrc), "main", ShaderType::Fragment); Shader malformed(fs::path(variantSrc), "main", ShaderType::Fragment);
malformed.defines = {bad}; malformed.defines = {bad};
malformed.variant = "malformed"; malformed.variant = "malformed";
if (!malformed.Compile(outDir, includeDirs).contains("invalid shader define")) { if (!malformed.Compile(outDir, outDir, includeDirs).contains("invalid shader define")) {
std::println(std::cerr, "a malformed define was not rejected by name"); std::println(std::cerr, "a malformed define was not rejected by name");
return 1; return 1;
} }
} }
Shader nested(fs::path(variantSrc), "main", ShaderType::Fragment); Shader nested(fs::path(variantSrc), "main", ShaderType::Fragment);
nested.variant = "sub/red"; nested.variant = "sub/red";
if (!nested.Compile(outDir, includeDirs).contains("path separator")) { if (!nested.Compile(outDir, outDir, includeDirs).contains("path separator")) {
std::println(std::cerr, "a variant with a path separator was not rejected by name"); std::println(std::cerr, "a variant with a path separator was not rejected by name");
return 1; return 1;
} }

View file

@ -0,0 +1 @@
const vec4 kTint = vec4(0.0, 1.0, 0.0, 1.0);

View file

@ -0,0 +1,16 @@
#version 450
#extension GL_GOOGLE_include_directive : require
// Built by the ShaderIncludeChange test, which edits palette.glsl and this
// entry's defines between builds.
#include "palette.glsl"
layout(location = 0) out vec4 outColor;
void main() {
#ifdef LIT_DIM
outColor = kTint * 0.5;
#else
outColor = kTint;
#endif
}

View file

@ -0,0 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
int main() {
return 0;
}

View file

@ -0,0 +1,8 @@
#version 450
// Includes nothing: the ShaderIncludeChange test checks it is left alone.
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(0.0, 0.0, 1.0, 1.0);
}

View file

@ -0,0 +1,126 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// A shader's output is stale when anything that went into it changed, not
// only its own source. Check() used to compare the .spv against the source's
// mtime alone, so:
// - editing a file the shader #includes left the .spv built against the old
// contents, the GLSL twin of IncrementalHeaderChange;
// - changing an entry's defines without touching the source did too.
// Each pass changes one thing and checks both directions: the shader it
// reaches is recompiled, to new contents, and the shader that includes
// nothing is left alone. A build with nothing changed compiles nothing.
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
// The fixture is edited between passes, so work on a copy outside the repo.
fs::path StageFixture() {
fs::path source = fs::current_path() / "tests" / "ShaderIncludeChange" / "fixture";
fs::path staged = fs::temp_directory_path() / "crafter-build-shader-include-change";
fs::remove_all(staged);
fs::copy(source, staged, fs::copy_options::recursive);
return staged;
}
Configuration MakeApp(const fs::path& staged) {
Configuration app;
app.path = staged;
app.name = "lit";
app.outputName = "lit";
app.target = HostTarget();
app.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
app.shaders.emplace_back(staged / "lit.frag", std::string("main"), ShaderType::Fragment);
app.shaders.emplace_back(staged / "plain.frag", std::string("main"), ShaderType::Fragment);
// Puts include/ on the shaders' #include path.
app.buildFiles = { staged / "include" / "palette.glsl" };
return app;
}
bool BuildOk(Configuration& app, std::string_view label) {
// A fresh depResults per pass: the map memoizes a Configuration's
// build for the duration of one pass.
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(app, depResults, depMutex);
Check(r.result.empty(), std::format("{} builds: {}", label, r.result));
return r.result.empty();
}
std::string ReadAll(const fs::path& file) {
std::ifstream stream(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>());
}
}
int main() {
const fs::path staged = StageFixture();
Configuration app = MakeApp(staged);
const fs::path lit = app.BinDir() / "lit.spv";
const fs::path plain = app.BinDir() / "plain.spv";
const fs::path palette = staged / "include" / "palette.glsl";
// Pass 1: everything from scratch.
if (!BuildOk(app, "the first pass")) return 1;
Check(fs::exists(lit) && fs::exists(plain), "both shaders are in the bin dir");
const fs::file_time_type plainBuilt = fs::last_write_time(plain);
const std::string green = ReadAll(lit);
// Pass 2: nothing changed.
fs::file_time_type litBuilt = fs::last_write_time(lit);
BuildOk(app, "an unchanged project");
Check(fs::last_write_time(lit) == litBuilt && fs::last_write_time(plain) == plainBuilt, "with nothing changed, no shader is recompiled");
// Pass 3: the included file changes. Dated just after the output it must
// outdate, so the rebuilt output is newer than it again.
{
std::ofstream out(palette, std::ios::trunc);
out << "const vec4 kTint = vec4(1.0, 0.0, 0.0, 1.0);\n";
}
fs::last_write_time(palette, litBuilt + std::chrono::milliseconds(1));
BuildOk(app, "an edited include");
const std::string red = ReadAll(lit);
Check(fs::last_write_time(lit) > litBuilt && red != green, "editing an included file recompiles the shader that includes it, to new contents");
Check(fs::last_write_time(plain) == plainBuilt, "and leaves the shader that includes nothing alone");
// Pass 4: the entry's defines change, no file does.
app.shaders[0].defines = { "LIT_DIM" };
litBuilt = fs::last_write_time(lit);
BuildOk(app, "a new define");
const std::string dim = ReadAll(lit);
Check(fs::last_write_time(lit) > litBuilt && dim != red, "a define added to the entry recompiles it, taking the #ifdef branch");
Check(fs::last_write_time(plain) == plainBuilt, "and leaves the other entry alone");
// Pass 5: and back.
app.shaders[0].defines = {};
BuildOk(app, "the define taken out");
Check(ReadAll(lit) == red, "taking the define out again recompiles it as it was");
// Pass 6: nothing changed again; what the passes above recorded holds.
litBuilt = fs::last_write_time(lit);
BuildOk(app, "an unchanged project, again");
Check(fs::last_write_time(lit) == litBuilt && fs::last_write_time(plain) == plainBuilt, "with nothing changed since, no shader is recompiled");
std::error_code ec;
fs::remove_all(staged, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -61,7 +61,7 @@ int main() {
Check(tc.libcxxVersion == LibcxxVersion("/usr/include/c++/v1"), "the system libc++ headers state the release of the system module source"); Check(tc.libcxxVersion == LibcxxVersion("/usr/include/c++/v1"), "the system libc++ headers state the release of the system module source");
Check(tc.stdModulesDir.empty(), "no crafter-build prefix, no shipped module sources"); Check(tc.stdModulesDir.empty(), "no crafter-build prefix, no shipped module sources");
Check(tc.wasiSysroot == "/usr/share/wasi-sysroot", "the system wasi sysroot is the default"); Check(tc.wasiSysroot == "/usr/share/wasi-sysroot", "the system wasi sysroot is the default");
Check(tc.mingwSysroot == "/usr/x86_64-w64-mingw32" && !tc.mingwSysrootExplicit, "the default mingw dir is not passed as --sysroot"); Check(tc.mingwSysroot.empty(), "outside a sandbox, clang finds mingw-w64 itself: no --sysroot");
Check(tc.LibcxxCompileFlags().empty() && tc.LibcxxLinkFlags().empty(), "the PATH fallback adds no libc++ flags"); Check(tc.LibcxxCompileFlags().empty() && tc.LibcxxLinkFlags().empty(), "the PATH fallback adds no libc++ flags");
} }
{ {
@ -144,7 +144,21 @@ int main() {
in.env["CRAFTER_MINGW_DIR"] = "/opt/mingw"; in.env["CRAFTER_MINGW_DIR"] = "/opt/mingw";
Toolchain tc = ResolveToolchain(in); Toolchain tc = ResolveToolchain(in);
Check(tc.wasiSysroot == "/opt/wasi", "CRAFTER_BUILD_WASI_SYSROOT overrides the wasi sysroot"); Check(tc.wasiSysroot == "/opt/wasi", "CRAFTER_BUILD_WASI_SYSROOT overrides the wasi sysroot");
Check(tc.mingwSysroot == "/opt/mingw" && tc.mingwSysrootExplicit, "CRAFTER_MINGW_DIR overrides the mingw dir and is passed as --sysroot"); Check(tc.mingwSysroot == "/opt/mingw", "CRAFTER_MINGW_DIR names the mingw prefix passed as --sysroot");
}
{
// Sandboxed, the host's /usr stands in for the missing mingw-w64,
// unless CRAFTER_MINGW_DIR says otherwise.
const fs::path host = fs::temp_directory_path() / "crafter-build-toolchain-host";
fs::remove_all(host);
ToolchainInputs in;
in.hostRoot = host;
Check(ResolveToolchain(in).mingwSysroot.empty(), "a host without mingw-w64 gives no --sysroot");
fs::create_directories(host / "usr" / "x86_64-w64-mingw32");
Check(ResolveToolchain(in).mingwSysroot == host / "usr", "a host with mingw-w64 gives its /usr as the mingw prefix");
in.env["CRAFTER_MINGW_DIR"] = "/opt/mingw";
Check(ResolveToolchain(in).mingwSysroot == "/opt/mingw", "CRAFTER_MINGW_DIR wins over the host's");
fs::remove_all(host);
} }
{ {
// The cache key separates toolchains that would build different // The cache key separates toolchains that would build different