fix(cuda): look for nvcc instead of leaving it to PATH

cfg.cuda compiled with a bare "nvcc", which the shell looked up on PATH.
In crafter-build's Flatpak PATH is /app/bin:/usr/bin, as its manifest
sets it, which never holds the host's toolkit, so with it every build
with CUDA sources stopped at "sh: line 1: nvcc: command not found",
although the sandbox sees /opt/cuda through --filesystem=host.

ResolveToolchain now finds nvcc as it finds clang++: CUDA_PATH, which is
exclusive as CRAFTER_BUILD_LLVM_DIR is, else /opt/cuda (Arch's package)
or /usr/local/cuda (NVIDIA's installer and packages), else the absolute
entries of PATH, which it searches itself so that a build without a
toolkit can say where it looked. A relative CUDA_PATH is made absolute
there, once, as CRAFTER_MINGW_DIR is, since nvcc runs later from
whatever working directory a build is in. The sandbox shows the host's
/usr and /etc under /run/host, with its own runtime at /usr, and
NVIDIA's /usr/local/cuda is a link, to /usr/local/cuda-<version> or
through /etc/alternatives. A link to an absolute path names a path of
the host, /opt/cuda pointing at /usr/local/cuda-<version> too, and the
sandbox would look it up in its own root, so where the path of a
toolkit, CUDA_PATH, /opt/cuda or /usr/local/cuda, is such a link,
HostPath follows it, and the link its target is in turn, each taken as
the host's; a link partway along that path, or inside the toolkit, is
the kernel's to resolve, in the sandbox's root.

A missing toolkit is reported by the build that has a .cu to compile and
not by GetToolchain(), so no other build fails for want of one.
crafter-build --version prints the nvcc it found, whether or not the
compiler could be resolved.
This commit is contained in:
Jorijn van der Graaf 2026-11-11 19:34:52 +01:00
commit fdba70d176
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
4 changed files with 132 additions and 4 deletions

View file

@ -23,7 +23,7 @@ crafter-build is a C++26 modules build system. A project is described by a `proj
Partitions and what they own:
- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages.
- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages.
- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types.
- `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code.
- `:Interface` and `:Implementation` model module units, their staleness checks and their compiles.

View file

@ -1147,11 +1147,19 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// untested here (no CUDA toolkit in CI), so a .cu that only sees a
// changed header does not rebuild yet.
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath))) {
threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled]() {
const Toolchain& toolchain = GetToolchain();
if (toolchain.nvcc.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError);
}
break;
}
threads.emplace_back([&cFile, &buildError, &buildCancelled, &toolchain, srcPath, objPath]() {
Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string()));
if (buildCancelled.load(std::memory_order_relaxed)) return;
std::string result = RunBuildCommand(std::format("nvcc {}.cu -c -o {}_source.o -O3 -arch=sm_89", cFile.string(), (buildDir / cFile.filename()).string()));
std::string result = RunBuildCommand(std::format("{} {} -c -o {} -O3 -arch=sm_89", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(objPath)));
if (result.empty()) return;
bool expected = false;
@ -2049,8 +2057,15 @@ std::vector<fs::path> Crafter::CleanProject(const fs::path& projectFile) {
static void PrintVersion() {
std::println("crafter-build {}", CrafterBuildVersion());
const Toolchain& tc = GetToolchain();
// nvcc only when there is one: most projects have no CUDA sources, and the
// build that has some says where it looked. Found apart from the compiler,
// so printed whether or not that was resolved.
const auto cuda = [&tc]() {
if (!tc.nvcc.empty()) std::println("nvcc {}", tc.nvcc.string());
};
if (!tc.error.empty()) {
std::println("compiler: {}", tc.error);
cuda();
return;
}
std::println("compiler {} ({})", tc.clangVersion, tc.clangxx.string());
@ -2069,6 +2084,7 @@ static void PrintVersion() {
std::println("libc++ {}{}", LibcxxVersionString(tc.libcxxVersion), also.empty() ? std::string() : std::format(" (std module sources for sysroots also for{})", also.substr(1)));
}
std::println("host {}", tc.hostTriple);
cuda();
}
static void PrintHelp(std::string_view argv0) {
@ -2202,6 +2218,10 @@ Project args:
Environment:
CRAFTER_BUILD_MARCH Override -march (default: native).
CRAFTER_BUILD_MTUNE Override -mtune (default: native).
CUDA_PATH CUDA toolkit whose bin/nvcc compiles
cfg.cuda. Default: /opt/cuda, then
/usr/local/cuda (in the Flatpak, the
host's), then nvcc on PATH.
CRAFTER_BUILD_RUNNER_<TARGET> Default test runner for a target triple.
Replace '-' and '.' with '_' in the
triple. CLI --runner= overrides this.

View file

@ -23,6 +23,8 @@ namespace {
"CRAFTER_BUILD_WASI_SYSROOT",
"CRAFTER_BUILD_FLATPAK_INFO",
"CRAFTER_MINGW_DIR",
"CUDA_PATH",
"PATH",
};
// The arch and branch of the runtime=runtime/<id>/<arch>/<branch> line
@ -100,6 +102,48 @@ namespace {
return normal;
}
// A regular file someone may run, as the shell's PATH lookup wants one.
bool IsProgram(const fs::path& file) {
std::error_code ec;
if (!fs::is_regular_file(file, ec)) return false;
constexpr fs::perms Exec = fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec;
return (fs::status(file, ec).permissions() & Exec) != fs::perms::none;
}
// `path`, as the host names it, where this process finds it. A sandbox
// shows the host's /usr and /etc, and the directories beside them its
// own runtime has (bin, sbin, lib, lib64), under hostRoot, and
// everything else, /opt and /home among it, where the host has it. A
// link to an absolute path names the host's path wherever the link is,
// and the sandbox would look it up in its own root instead: NVIDIA's
// /usr/local/cuda is a link, to /usr/local/cuda-<version> or through
// /etc/alternatives, and an /opt/cuda can be one to such a directory.
// So where the path is a link, it is followed here, and so is its
// target where that is one, each taken as the host's. Outside a
// sandbox, `path` itself.
fs::path HostPath(fs::path path, const fs::path& hostRoot) {
if (hostRoot.empty()) return path;
fs::path shown = path;
// As many links as the kernel follows before it gives up on a loop.
for (std::int32_t hops = 0; hops < 40; ++hops) {
if (!path.is_absolute()) return path;
// Without a trailing separator, which has readlink follow the
// link instead of reading it.
path = path.lexically_normal();
if (!path.has_filename() && path.has_relative_path()) path = path.parent_path();
const fs::path relative = path.relative_path();
const fs::path top = relative.empty() ? fs::path() : *relative.begin();
const bool underHostRoot = top == "usr" || top == "etc" || top == "bin" || top == "sbin" || top == "lib" || top == "lib64";
shown = underHostRoot ? hostRoot / relative : path;
std::error_code ec;
const fs::path target = fs::read_symlink(shown, ec);
if (ec) return shown;
path = target.is_absolute() ? target : (path.parent_path() / target).lexically_normal();
}
// Still a link after all of them: a loop, which opens as nothing.
return shown;
}
// The view MingwSysroot() made and the prefix it shows, for
// MingwViewToPrefix. Written once, before ViewMade is set.
fs::path MadeView;
@ -221,6 +265,50 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.mingwPrefix = PrefixPath(in.hostRoot / "usr");
tc.mingwPrefixIsSystem = true;
}
// 5. nvcc, for cfg.cuda. CUDA_PATH is exclusive, as CRAFTER_BUILD_LLVM_DIR
// is: it names the toolkit, and one without nvcc is an error rather
// than a reason to use another. PATH is searched here, not by the
// shell: in crafter-build's Flatpak it is /app/bin:/usr/bin, which
// never holds the host's toolkit, and every CUDA build there stopped
// at "nvcc: command not found", which named no place to put one.
if (std::string_view cudaPath = Env(in, "CUDA_PATH"); !cudaPath.empty()) {
// Absolute and spelled one way, once, as CRAFTER_MINGW_DIR is: nvcc
// runs later, from whatever working directory a build is in.
const fs::path named = PrefixPath(fs::path(cudaPath));
if (const fs::path nvcc = HostPath(named, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) {
tc.nvcc = nvcc;
} else {
tc.nvccError = std::format("no nvcc at {} (CUDA_PATH)", (named / "bin" / "nvcc").string());
}
} else {
std::vector<std::string> lookedAt;
for (const fs::path& root : in.cudaRoots) {
if (const fs::path nvcc = HostPath(root, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) {
tc.nvcc = nvcc;
break;
}
lookedAt.push_back((root / "bin" / "nvcc").string());
}
const std::string_view path = Env(in, "PATH");
for (std::size_t at = 0; tc.nvcc.empty() && at <= path.size();) {
std::size_t end = path.find(':', at);
if (end == std::string_view::npos) end = path.size();
// An empty or a relative entry names a directory under whatever
// the working directory is, and this lookup is made once per
// process: only an absolute one names a place.
if (const std::string_view dir = path.substr(at, end - at); fs::path(dir).is_absolute() && IsProgram(fs::path(dir) / "nvcc")) {
tc.nvcc = fs::path(dir) / "nvcc";
}
at = end + 1;
}
if (tc.nvcc.empty()) {
lookedAt.push_back(std::format("nvcc on PATH ({})", path.empty() ? std::string_view("unset") : path));
std::string places = lookedAt.front();
for (std::size_t i = 1; i < lookedAt.size(); ++i) places += std::format("{}{}", i + 1 == lookedAt.size() ? " and " : ", ", lookedAt[i]);
tc.nvccError = std::format("no CUDA toolkit found: looked for {}; set CUDA_PATH to the directory a toolkit is installed in", places);
}
}
std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo);
return tc;
}
@ -239,6 +327,7 @@ const Toolchain& Crafter::GetToolchain() {
in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path();
} catch (const std::exception&) {}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" };
{
auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO");
const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info");

View file

@ -55,6 +55,18 @@ export namespace Crafter {
// its mingw-w64 parts; any other prefix is the sysroot itself, and
// Windows libraries installed into its include/ and lib/ are found.
bool mingwPrefixIsSystem = false;
// The nvcc that compiles cfg.cuda: <CUDA_PATH>/bin/nvcc when CUDA_PATH
// is set, else bin/nvcc of the first toolkit that has one among
// ToolchainInputs::cudaRoots, else the first nvcc in an absolute entry
// of PATH. In a sandbox, a toolkit is looked up as the host has it:
// under hostRoot where it is in the host's /usr or /etc, and, where
// its path is a link, through that link and the link its target is in
// turn, each taken as the host's, wherever they point. Empty when
// there is none, and nvccError says where it was looked for; only a
// build with a .cu to compile reports that, so no other build fails
// for want of a CUDA toolkit.
fs::path nvcc;
std::string nvccError;
// The Flatpak runtime crafter-build runs on, from the
// runtime=runtime/<id>/<arch>/<branch> line of /.flatpak-info:
// "x86_64" and "26.08" in the Flatpak, both empty outside one. A
@ -98,7 +110,8 @@ export namespace Crafter {
// What ResolveToolchain reads, so a test can feed it a staged layout.
struct ToolchainInputs {
// The CRAFTER_* variables, present only when set and non-empty.
// The CRAFTER_* variables, CUDA_PATH and PATH, present only when set
// and non-empty.
std::map<std::string, std::string, std::less<>> env;
// The <prefix> of <prefix>/share/crafter-build; empty when unknown.
fs::path crafterPrefix;
@ -108,10 +121,16 @@ export namespace Crafter {
// What /.flatpak-info holds, or the file CRAFTER_BUILD_FLATPAK_INFO
// names; empty outside a Flatpak.
std::string flatpakInfo;
// Where a CUDA toolkit is installed when CUDA_PATH names none, in the
// order they are tried and as the host names them: GetToolchain()
// passes /opt/cuda, Arch's, and /usr/local/cuda, NVIDIA's installers'.
std::vector<fs::path> cudaRoots;
};
// Pure path resolution: an env override wins, then a toolchain installed
// beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on
// PATH. Never runs a process, so hostTriple and clangVersion stay empty.
// nvcc is not left to the shell's PATH lookup but searched for here,
// PATH included, so a build that cannot find one can say where it looked.
Toolchain ResolveToolchain(const ToolchainInputs& inputs);
// ResolveToolchain over the real environment plus the two clang probes,
// computed once and cached. Never throws.