// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® #include 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. Those builds // name no CUDA library: the configuration links the runtime of the toolkit // itself, the static archive in its lib64 by its path. Another build puts the // .cu in a static library and the C++ unit in an executable built on it, which // links only if the library hands the runtime on. That lib64 also holds a // libcheckpoint.so and a libm.so that are no libraries, so a link that // searched it would stop on one: an executable with CUDA sources built on a // library of the project's named checkpoint has to take the project's, and // clang++ adds -lm to every C++ link. A last build names the shared runtime // itself, as a project with CUDA sources had to, and has its -lcudart ahead of // the static archive. Where nvcc is looked for, and the runtime beside it, is // ToolchainResolve's to check; this is the build that uses them. Skips without // a CUDA toolkit whose lib64 holds the static runtime; CI has none. 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::string Read(const fs::path& file) { std::ifstream in(file, std::ios::binary); return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); } std::vector Lines(const fs::path& file) { std::vector 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& lines) { return std::views::join_with(lines, std::string(" | ")) | std::ranges::to(); } struct Built { std::string error; fs::path binary; // The link command the build recorded, beside its objects. fs::path linkRecord; }; } int main() { const Toolchain real = RealToolkit(); if (real.nvcc.empty()) { std::println("SKIP: {}", real.nvccError); return 77; } const fs::path nvcc = real.nvcc; // The static runtime crafter-build links, from the lib64 beside nvcc's // bin. A toolkit without one there gets none linked, and the runtime link // has nothing to show. const fs::path realArchive = real.cudaRuntime; if (realArchive.empty()) { std::println("SKIP: no libcudart_static.a in the lib64 beside {}, so crafter-build links no CUDA runtime for this toolkit", nvcc.parent_path().string()); return 77; } 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); // The toolkit CUDA_PATH names: an nvcc that writes down how it was run and // runs the real one, and a lib64 with the real toolkit's static runtime // and a libcheckpoint.so and a libm.so that are no libraries at all. A // toolkit's lib64 can hold a library named like a project's own (Arch's // holds a libcheckpoint.so) or like one the link takes from the system (a // libOpenCL.so), and a link that searched it would take that one: the // libm.so stands for those, as clang++ adds -lm to every C++ link. 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()))); fs::create_directories(toolkit / "lib64"); fs::create_symlink(realArchive, toolkit / "lib64" / "libcudart_static.a"); std::ofstream(toolkit / "lib64" / "libcheckpoint.so") << "not a library\n"; std::ofstream(toolkit / "lib64" / "libm.so") << "not a library\n"; // What a link names the runtime by: the archive in the toolkit's lib64, by // its path. const std::string runtime = (toolkit / "lib64" / "libcudart_static.a").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); const auto build = [&](std::optional arch) { Configuration app; app.path = project; app.name = "cuda"; app.outputName = "cuda"; app.type = ConfigurationType::Executable; if (arch) app.cudaArch = *arch; std::array ifaces = {}; std::array impls = { "main" }; app.GetInterfacesAndImplementations(ifaces, impls); app.cuda = { project / "kernel" }; std::unordered_map> depResults; std::mutex depMutex; const BuildResult result = Build(app, depResults, depMutex); return Built{ result.result, app.BinDir() / "cuda", app.BuildDir() / "cuda.link" }; }; const Built native = build(std::nullopt); Check(native.error.empty(), std::format("the build with the default architecture succeeds: {}", native.error)); Check(fs::exists(native.binary), "it links the executable"); const std::string record = Read(native.linkRecord); Check(record.contains(runtime), std::format("with the static runtime from the toolkit's lib64, though no link flag names it (link: {})", record)); std::vector 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 Built other = build("sm_86"); Check(other.error.empty(), std::format("the build for sm_86 succeeds: {}", other.error)); 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(other.binary) && other.binary.parent_path() != native.binary.parent_path(), "in a directory of its own"); const Built again = build("sm_86"); Check(again.error.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 Built touched = build("sm_86"); Check(touched.error.empty(), std::format("the build after the header changed succeeds: {}", touched.error)); 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))); { // The .cu in a static library, the C++ unit in an executable built on // it: neither names a CUDA library, and the executable's link has the // runtime only from what the library hands on. const fs::path split = scratch / "split"; fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", split, fs::copy_options::recursive); Configuration kernels; kernels.path = split; kernels.name = "kernels"; kernels.outputName = "kernels"; kernels.type = ConfigurationType::LibraryStatic; kernels.cuda = { split / "kernel" }; Configuration program; program.path = split; program.name = "program"; program.outputName = "program"; program.type = ConfigurationType::Executable; std::array ifaces = {}; std::array impls = { "main" }; program.GetInterfacesAndImplementations(ifaces, impls); program.dependencies = { &kernels }; std::unordered_map> depResults; std::mutex depMutex; const BuildResult built = Build(program, depResults, depMutex); Check(built.result.empty(), std::format("an executable built on a library with CUDA sources links: {}", built.result)); Check(Read(program.BuildDir() / "program.link").contains(runtime), "with the runtime the library hands on"); } { // An executable with CUDA sources built on a library of the // project's named like one in the toolkit's lib64: the linker has to // take the project's, and stops on the toolkit's file if it searches // the toolkit's lib64 first. const fs::path named = scratch / "named"; fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", named, fs::copy_options::recursive); Configuration checkpoint; checkpoint.path = named; checkpoint.name = "checkpoint"; checkpoint.outputName = "checkpoint"; checkpoint.type = ConfigurationType::LibraryStatic; { std::array ifaces = {}; std::array impls = { "checkpoint" }; checkpoint.GetInterfacesAndImplementations(ifaces, impls); } Configuration app; app.path = named; app.name = "named"; app.outputName = "named"; app.type = ConfigurationType::Executable; std::array ifaces = {}; std::array impls = { "main" }; app.GetInterfacesAndImplementations(ifaces, impls); app.cuda = { named / "kernel" }; app.dependencies = { &checkpoint }; std::unordered_map> depResults; std::mutex depMutex; const BuildResult built = Build(app, depResults, depMutex); Check(built.result.empty(), std::format("an executable with CUDA sources links a library of its project's named like one in the toolkit's lib64: {}", built.result)); } { // A project that names the shared runtime itself, as every project.cpp // with CUDA sources had to: its -lcudart comes ahead of the static // archive on the link line, so the linker takes the shared runtime. const fs::path own = scratch / "own"; fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", own, fs::copy_options::recursive); Configuration app; app.path = own; app.name = "own"; app.outputName = "own"; app.type = ConfigurationType::Executable; std::array ifaces = {}; std::array impls = { "main" }; app.GetInterfacesAndImplementations(ifaces, impls); app.cuda = { own / "kernel" }; app.linkFlags = { std::format("-L{}", ShellQuote(realArchive.parent_path().string())), "-lcudart" }; std::unordered_map> depResults; std::mutex depMutex; const BuildResult built = Build(app, depResults, depMutex); Check(built.result.empty(), std::format("a build that names -lcudart itself links: {}", built.result)); const std::string link = Read(app.BuildDir() / "own.link"); const std::size_t shared = link.find(" -lcudart "); const std::size_t archive = link.find(runtime); Check(shared != std::string::npos && archive != std::string::npos && shared < archive, std::format("with its -lcudart ahead of the static runtime (link: {})", link)); } fs::remove_all(scratch, ec); return Failures == 0 ? 0 : 1; }