Crafter.Build/tests/CudaCompile/main.cpp
Jorijn van der Graaf 6b2da3b1d6
test(cuda): a changed header compiles the .cu again
CudaCompile's .cu includes a header of its own now. After the unchanged
build, the test makes the header newer than the object and builds once
more, which has to run nvcc again. Before nvcc wrote a depfile, it did
not, and the object built from the old header stayed.
2026-11-11 19:34:52 +01:00

137 lines
6.6 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// cfg.cuda is compiled with the nvcc ResolveToolchain finds, for the GPU
// architecture cfg.cudaArch names. It used to be whatever "nvcc" meant to the
// shell, for sm_89 alone: crafter-build's Flatpak sets PATH to
// /app/bin:/usr/bin, and with that PATH every CUDA build there stopped at
// "nvcc: command not found" with the host's toolkit in reach at /opt/cuda.
//
// The test puts an nvcc on PATH that fails, names a toolkit through CUDA_PATH
// whose nvcc writes down its arguments and runs the real one, and builds an
// executable from a C++ unit and a .cu: with the default architecture, which
// is native, then with another one, which compiles the unchanged .cu again in
// a directory of its own, then once more with nothing changed, which compiles
// nothing, and once its header is newer than its object, which compiles it
// again: nvcc's depfile is the record of what the .cu includes, and before
// nvcc wrote one, a changed header left the old object in place. Where nvcc
// is looked for is ToolchainResolve's to check; this is the build that uses
// it. Skips without a CUDA toolkit, which CI does not have.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The nvcc crafter-build finds in this environment, looked for with the
// inputs GetToolchain() gives ResolveToolchain, the host's /usr under
// /run/host in a sandbox included, before the test changes CUDA_PATH and
// PATH. ResolveToolchain is pure: GetToolchain()'s cache stays empty.
Toolchain RealToolkit() {
ToolchainInputs in;
for (const std::string_view name : {"CUDA_PATH", "PATH"}) {
if (const char* value = std::getenv(std::string(name).c_str()); value && *value) in.env.emplace(std::string(name), value);
}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" };
return ResolveToolchain(in);
}
void WriteProgram(const fs::path& file, std::string_view text) {
fs::create_directories(file.parent_path());
std::ofstream(file) << text;
fs::permissions(file, fs::perms::owner_exec, fs::perm_options::add);
}
std::vector<std::string> Lines(const fs::path& file) {
std::vector<std::string> lines;
std::ifstream in(file);
for (std::string line; std::getline(in, line);) lines.push_back(line);
return lines;
}
std::string Joined(const std::vector<std::string>& lines) {
return std::views::join_with(lines, std::string(" | ")) | std::ranges::to<std::string>();
}
}
int main() {
const Toolchain real = RealToolkit();
if (real.nvcc.empty()) {
std::println("SKIP: {}", real.nvccError);
return 77;
}
const fs::path nvcc = real.nvcc;
const fs::path scratch = fs::temp_directory_path() / "crafter-build-cuda-compile";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path project = scratch / "project";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", project, fs::copy_options::recursive);
const fs::path log = scratch / "nvcc.log";
const fs::path toolkit = scratch / "toolkit";
WriteProgram(toolkit / "bin" / "nvcc", std::format("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nexec {} \"$@\"\n", ShellQuote(log.string()), ShellQuote(nvcc.string())));
const fs::path decoy = scratch / "decoy";
WriteProgram(decoy / "nvcc", "#!/bin/sh\necho 'the nvcc on PATH ran' >&2\nexit 1\n");
// Before anything resolves the toolchain, which reads the environment
// once per process: the first Configuration does, for its target.
setenv("CUDA_PATH", toolkit.c_str(), 1);
const char* path = std::getenv("PATH");
setenv("PATH", std::format("{}:{}", decoy.string(), path ? path : "").c_str(), 1);
// The CUDA runtime the .cu calls into, from the real toolkit.
const std::string runtimeDir = std::format("-L{}", (nvcc.parent_path().parent_path() / "lib64").string());
const auto build = [&](std::optional<std::string> arch) {
Configuration app;
app.path = project;
app.name = "cuda";
app.outputName = "cuda";
app.type = ConfigurationType::Executable;
if (arch) app.cudaArch = *arch;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
app.cuda = { project / "kernel" };
app.linkFlags = { runtimeDir, "-lcudart" };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult result = Build(app, depResults, depMutex);
return std::pair{ result.result, app.BinDir() / "cuda" };
};
const auto [native, nativeBinary] = build(std::nullopt);
Check(native.empty(), std::format("the build with the default architecture succeeds: {}", native));
Check(fs::exists(nativeBinary), "it links the executable");
std::vector<std::string> runs = Lines(log);
Check(runs.size() == 1 && runs.front().contains("-arch=native"), std::format("CUDA_PATH's nvcc compiles the .cu once, with -arch=native (ran: {})", Joined(runs)));
const auto [other, otherBinary] = build("sm_86");
Check(other.empty(), std::format("the build for sm_86 succeeds: {}", other));
runs = Lines(log);
Check(runs.size() == 2 && runs.back().contains("-arch=sm_86"), std::format("another architecture compiles the unchanged .cu again, for it (ran: {})", Joined(runs)));
Check(fs::exists(otherBinary) && otherBinary.parent_path() != nativeBinary.parent_path(), "in a directory of its own");
const auto [again, againBinary] = build("sm_86");
Check(again.empty() && Lines(log).size() == 2, std::format("an unchanged build compiles nothing (ran: {})", Joined(Lines(log))));
fs::last_write_time(project / "kernel.h", fs::file_time_type::clock::now());
const auto [touched, touchedBinary] = build("sm_86");
Check(touched.empty(), std::format("the build after the header changed succeeds: {}", touched));
runs = Lines(log);
Check(runs.size() == 3 && runs.back().contains("-arch=sm_86"), std::format("a changed header compiles the .cu again (ran: {})", Joined(runs)));
fs::remove_all(scratch, ec);
return Failures == 0 ? 0 : 1;
}