// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; // Supplied on the command line by build.sh and project.cpp (from the // CRAFTER_BUILD_VERSION environment variable or `git describe`); a build // that passes nothing is a development build. #ifndef CRAFTER_BUILD_VERSION #define CRAFTER_BUILD_VERSION "0.0.0-dev" #endif module Crafter.Build:Toolchain_impl; import std; import :Toolchain; import :Platform; namespace fs = std::filesystem; using namespace Crafter; namespace { constexpr std::string_view EnvVars[] = { "CRAFTER_BUILD_LLVM_DIR", "CRAFTER_BUILD_LIBCXX_DIR", "CRAFTER_BUILD_LIBCLANG", "CRAFTER_BUILD_WASI_SYSROOT", "CRAFTER_BUILD_FLATPAK_INFO", "CRAFTER_MINGW_DIR", "CUDA_PATH", "PATH", }; // The arch and branch of the runtime=runtime/// line // in the [Application] group of a .flatpak-info; empty when it has none. std::pair FlatpakRuntimeOf(std::string_view info) { bool inApplication = false; for (std::size_t begin = 0; begin < info.size();) { std::size_t end = info.find('\n', begin); if (end == std::string_view::npos) end = info.size(); std::string_view line = info.substr(begin, end - begin); begin = end + 1; if (line.ends_with('\r')) line.remove_suffix(1); if (line.starts_with("[")) { inApplication = line == "[Application]"; continue; } if (!inApplication || !line.starts_with("runtime=")) continue; std::vector parts; std::string_view ref = line.substr(std::string_view("runtime=").size()); for (std::size_t at = 0;;) { const std::size_t slash = ref.find('/', at); parts.push_back(ref.substr(at, slash == std::string_view::npos ? std::string_view::npos : slash - at)); if (slash == std::string_view::npos) break; at = slash + 1; } if (parts.size() == 4 && parts[0] == "runtime" && !parts[2].empty() && !parts[3].empty()) { return {std::string(parts[2]), std::string(parts[3])}; } } return {}; } std::string_view Env(const ToolchainInputs& in, std::string_view name) { auto it = in.env.find(name); return it == in.env.end() ? std::string_view{} : std::string_view(it->second); } // "Arch Linux clang version 22.1.8" / "clang version 22.1.8" -> "22.1.8". std::string ShortVersion(std::string_view versionLine) { constexpr std::string_view Marker = "version "; std::size_t at = versionLine.find(Marker); if (at == std::string_view::npos) return "unknown"; std::string_view rest = versionLine.substr(at + Marker.size()); std::size_t end = rest.find_first_of(" \t("); return std::string(rest.substr(0, end)); } std::string Trimmed(std::string s) { while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) s.pop_back(); return s; } // `link` made a symbolic link to `target`, or found one already. Another // crafter-build may make the same link at the same moment, which is as // good as making it; a link to anything else is an error. void EnsureSymlink(const fs::path& target, const fs::path& link) { std::error_code ec; if (fs::read_symlink(link, ec) == target) return; fs::create_directories(link.parent_path()); fs::create_directory_symlink(target, link, ec); std::error_code ignored; if (ec && fs::read_symlink(link, ignored) != target) { throw fs::filesystem_error("cannot make a link", target, link, ec); } } // `dir` made absolute and spelled one way, once, when the toolchain is // resolved. The mingw prefix ends up as the target of links and in the // names of build and cache directories: a relative path read later from // another working directory would name something else, and /opt/mingw/ // next to /opt/mingw would rebuild everything for the same directory. fs::path PrefixPath(const fs::path& dir) { fs::path normal = fs::absolute(dir).lexically_normal(); if (!normal.has_filename() && normal.has_relative_path()) normal = normal.parent_path(); 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- 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; fs::path ViewedPrefix; std::atomic ViewMade = false; } std::string Toolchain::LibcxxCompileFlags() const { if (libcxxDir.empty()) return {}; return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string()); } // clang searches its per-target runtime directory and the system library // paths for -lc++, not /lib, so a toolchain outside /usr with the // classic layout needs the search path as well as the run-time path. fs::path Toolchain::LibcxxLibDir() const { if (!libcxxDir.empty()) return libcxxDir / "lib"; if (!prefix.empty() && prefix != "/usr") return prefix / "lib"; return {}; } std::string Toolchain::LibcxxLinkFlags() const { const fs::path lib = LibcxxLibDir(); if (lib.empty()) return {}; return std::format(" -L{} -Wl,-rpath,{}", lib.string(), lib.string()); } std::string Toolchain::LibcxxSearchFlags() const { const fs::path lib = LibcxxLibDir(); if (lib.empty()) return {}; return std::format(" -L{}", lib.string()); } std::string Toolchain::Key() const { std::string identity; for (const std::string& part : {clangxx.string(), clangVersion, libcxxDir.string(), stdCppm.string()}) { identity += part; identity += '\0'; } return std::format("{}-{:08x}", ShortVersion(clangVersion), static_cast(std::hash{}(identity))); } Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { Toolchain tc; // 1. The compiler: an explicit prefix, else one installed beside // crafter-build, else PATH. An explicit prefix without a clang++ is an // error rather than a fallback, for the same reason CRAFTER_BUILD_LIBCLANG // is exclusive: an override that silently yields to something else // cannot be used to diagnose which compiler is in play. if (std::string_view dir = Env(in, "CRAFTER_BUILD_LLVM_DIR"); !dir.empty()) { tc.prefix = fs::path(dir); if (!fs::exists(tc.prefix / "bin" / "clang++")) { tc.error = std::format("clang++ not found at {} (CRAFTER_BUILD_LLVM_DIR)", (tc.prefix / "bin" / "clang++").string()); } } else if (!in.crafterPrefix.empty() && fs::exists(in.crafterPrefix / "bin" / "clang++")) { tc.prefix = in.crafterPrefix; } if (tc.prefix.empty()) { tc.clangxx = "clang++"; tc.clang = "clang"; tc.llvmAr = "llvm-ar"; tc.llvmReadelf = "llvm-readelf"; } else { tc.clangxx = tc.prefix / "bin" / "clang++"; tc.clang = tc.prefix / "bin" / "clang"; tc.llvmAr = tc.prefix / "bin" / "llvm-ar"; tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf"; if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) { tc.llvmIncludeDir = tc.prefix / "include"; } } // 2. libclang. The override is exclusive and unchecked on purpose: a // broken path must fail loudly when dlopened, not be papered over. if (std::string_view pinned = Env(in, "CRAFTER_BUILD_LIBCLANG"); !pinned.empty()) { tc.libclang = fs::path(pinned); } else if (!tc.prefix.empty() && fs::exists(tc.prefix / "lib" / "libclang.so")) { tc.libclang = tc.prefix / "lib" / "libclang.so"; } // 3. libc++ and its std module source. The compiler's own copy lives at // /share/libc++/v1 when the prefix carries libc++; the system // copy is the last resort either way. The headers of the same install // say which release the source belongs to. fs::path libcxxRoot = "/usr"; if (std::string_view dir = Env(in, "CRAFTER_BUILD_LIBCXX_DIR"); !dir.empty()) { tc.libcxxDir = fs::path(dir); libcxxRoot = tc.libcxxDir; } else if (!tc.prefix.empty() && fs::exists(tc.prefix / "share" / "libc++" / "v1" / "std.cppm")) { libcxxRoot = tc.prefix; } tc.stdCppm = libcxxRoot / "share" / "libc++" / "v1" / "std.cppm"; tc.libcxxVersion = LibcxxVersion(libcxxRoot / "include" / "c++" / "v1"); if (!in.crafterPrefix.empty()) { tc.stdModulesDir = in.crafterPrefix / "share" / "crafter-build" / "libc++-modules"; } // 4. Sysroots for the cross targets that have a conventional location. if (std::string_view dir = Env(in, "CRAFTER_BUILD_WASI_SYSROOT"); !dir.empty()) { tc.wasiSysroot = fs::path(dir); } else if (!tc.prefix.empty() && fs::exists(tc.prefix / "share" / "wasi-sysroot")) { tc.wasiSysroot = tc.prefix / "share" / "wasi-sysroot"; } else { tc.wasiSysroot = "/usr/share/wasi-sysroot"; } if (std::string_view dir = Env(in, "CRAFTER_MINGW_DIR"); !dir.empty()) { tc.mingwPrefix = PrefixPath(fs::path(dir)); // A prefix that holds a Linux system as well as mingw-w64, /usr // itself, has that system's C library in include/: features.h, which // every glibc and musl header includes and mingw-w64 has no use for. // One that holds mingw-w64 alone stays the sysroot, so Windows // libraries installed into its include/ and lib/ stay visible. tc.mingwPrefixIsSystem = fs::exists(tc.mingwPrefix / "include" / "features.h"); } else if (!in.hostRoot.empty() && fs::exists(in.hostRoot / "usr" / "x86_64-w64-mingw32")) { // The sandbox has no mingw-w64 of its own, and no mingw gcc on PATH // for clang to find one by. The host's /usr is the host's system, // whether or not its C library's headers are installed. 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 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); } } // What VariantId keys a CUDA configuration's nvcc by. Its path stays // when the toolkit behind it is updated, by a package at /opt/cuda or by // /usr/local/cuda pointed at another release, and the objects the old // nvcc compiled would be kept. The binary's canonical path, size and // time change with it, and reading them starts no process. if (!tc.nvcc.empty()) { std::error_code ec; fs::path real = fs::canonical(tc.nvcc, ec); if (ec) real = tc.nvcc; const std::uintmax_t size = fs::file_size(real, ec); const auto time = fs::last_write_time(real, ec).time_since_epoch().count(); tc.nvccStamp = std::format("{}|{}|{}", real.string(), size, time); } // What VariantId keys -arch=native by: nvcc compiles it for the GPUs it // finds, so a GPU of another model, the same GPUs in each other's slots, // or CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER choosing another or, // empty, none, has to build in a directory of its own, where the word // alone would keep an object compiled for the old GPU, with no PTX for the // new one. The NVIDIA display devices (class 0x03) by PCI address and // device ID, in the order of their addresses, from sysfs, which starts no // process; an entry that cannot be read counts as none, and nothing here // throws. It is crafter-build's reading of the machine, not nvcc's: a // change it cannot see, such as a GPU bound to another driver, keeps the // key. if (!tc.nvcc.empty()) { std::vector gpus; std::error_code ec; for (fs::directory_iterator it(in.pciDevices, ec), end; !ec && it != end; it.increment(ec)) { const auto field = [&it](std::string_view name) { std::string value; std::ifstream(it->path() / name) >> value; return value; }; if (field("vendor") == "0x10de" && field("class").starts_with("0x03")) gpus.push_back(std::format("{}={}", it->path().filename().string(), field("device"))); } std::ranges::sort(gpus); const auto spelled = [](const std::optional& value) { return value ? std::format("={}", *value) : std::string("unset"); }; tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder)); } std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); return tc; } const Toolchain& Crafter::GetToolchain() { static const Toolchain Resolved = []() { ToolchainInputs in; for (std::string_view name : EnvVars) { if (const char* value = std::getenv(std::string(name).c_str()); value && *value) { in.env.emplace(std::string(name), value); } } // GetCrafterBuildHome throws when no share/crafter-build is found // near the executable; a toolchain can still come from PATH then. try { 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" }; in.pciDevices = "/sys/bus/pci/devices"; if (const char* value = std::getenv("CUDA_VISIBLE_DEVICES")) in.cudaVisibleDevices = value; if (const char* value = std::getenv("CUDA_DEVICE_ORDER")) in.cudaDeviceOrder = value; { 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"); if (std::ifstream file(info, std::ios::binary); file) { in.flatpakInfo.assign(std::istreambuf_iterator(file), std::istreambuf_iterator()); } } Toolchain tc = ResolveToolchain(in); if (!tc.error.empty()) return tc; CommandResult triple = RunCommandChecked(std::format("{} -print-target-triple", tc.clangxx.string())); if (triple.exitCode != 0) { tc.error = std::format("could not run {} (exit {}): {}", tc.clangxx.string(), triple.exitCode, Trimmed(triple.output)); if (tc.prefix.empty()) tc.error += "; install clang or set CRAFTER_BUILD_LLVM_DIR"; return tc; } tc.hostTriple = Trimmed(std::move(triple.output)); CommandResult version = RunCommandChecked(std::format("{} --version", tc.clangxx.string())); if (version.exitCode == 0) { std::string first = version.output.substr(0, version.output.find('\n')); tc.clangVersion = Trimmed(std::move(first)); } return tc; }(); return Resolved; } const Toolchain& Crafter::RequireToolchain() { const Toolchain& tc = GetToolchain(); if (!tc.error.empty()) throw std::runtime_error(tc.error); return tc; } fs::path Crafter::MakeMingwSysroot(const fs::path& prefix, std::span parents) { std::string reasons; for (const fs::path& parent : parents) { // One view per prefix: two shells with different CRAFTER_MINGW_DIRs // share one cache and would otherwise rewrite each other's. const fs::path sysroot = parent / "mingw-sysroot" / std::format("{:016x}", std::hash{}(prefix.string())); try { // All clang's mingw driver takes from a sysroot other than its // include/ and the rest of its lib/: the mingw-w64 tree (headers, // libraries, and libstdc++ where a distro's cross gcc installs // it) and gcc's per-target directory (crtbegin.o, libgcc, and the // version that names libstdc++'s header directory), which // openSUSE keeps under lib64. A link to nothing is skipped like a // missing directory. for (std::string_view entry : {"x86_64-w64-mingw32", "lib/gcc", "lib64/gcc"}) { EnsureSymlink(prefix / entry, sysroot / entry); } return sysroot; } catch (const std::exception& e) { reasons += std::format("; {}", e.what()); } } throw std::runtime_error(std::format("cannot make a sysroot that shows clang only the mingw-w64 parts of {}{}", prefix.string(), reasons)); } const fs::path& Crafter::MingwSysroot() { // Made on first use rather than by GetToolchain(), so that only what // compiles for the mingw target, a build or an AST lint of one, writes // anything for it, and a failure surfaces as that command's error // instead of on every command. static const fs::path Sysroot = []() -> fs::path { const Toolchain& tc = GetToolchain(); if (!tc.mingwPrefixIsSystem) return tc.mingwPrefix; // In the cache, or where the XDG spec promises symbolic links when // the cache's filesystem takes none (vfat, exFAT, CIFS without unix // extensions), which costs nothing else crafter-build caches. // Absolute, because CMake runs the compiler from directories of its // own. std::vector parents = { fs::absolute(GetCacheDir()) }; if (const char* runtime = std::getenv("XDG_RUNTIME_DIR"); runtime && *runtime) { parents.push_back(fs::absolute(fs::path(runtime) / "crafter.build")); } fs::path view = MakeMingwSysroot(tc.mingwPrefix, parents); MadeView = view; ViewedPrefix = tc.mingwPrefix; ViewMade.store(true, std::memory_order_release); return view; }(); return Sysroot; } std::string Crafter::MingwViewToPrefix(std::string text) { if (!ViewMade.load(std::memory_order_acquire)) return text; // With the separator, so a --sysroot= naming the view itself, in a // command line the output quotes, stays what was run. const std::string view = (MadeView / "").string(); const std::string prefix = (ViewedPrefix / "").string(); for (std::size_t at = text.find(view); at != std::string::npos; at = text.find(view, at + prefix.size())) { text.replace(at, view.size(), prefix); } return text; } std::int32_t Crafter::LibcxxVersion(const fs::path& includeDir) { // "# define _LIBCPP_VERSION 230102", the one place libc++ states its // release in a form the preprocessor does not have to be run for. constexpr std::string_view Marker = "define _LIBCPP_VERSION "; std::ifstream config(includeDir / "__config"); std::string line; while (std::getline(config, line)) { const std::size_t at = line.find(Marker); if (at == std::string::npos) continue; const std::string_view digits = std::string_view(line).substr(at + Marker.size()); std::int32_t version = 0; if (std::from_chars(digits.data(), digits.data() + digits.size(), version).ec == std::errc{}) return version; } return 0; } std::string Crafter::LibcxxVersionString(std::int32_t version) { return std::format("{}.{}.{}", version / 10000, version / 100 % 100, version % 100); } StdModuleSource Crafter::SysrootStdModule(const Toolchain& tc, const fs::path& sysroot) { const fs::path own = sysroot / "usr" / "share" / "libc++" / "v1" / "std.cppm"; if (fs::exists(own)) return {own, {}}; const fs::path includeDir = sysroot / "usr" / "include" / "c++" / "v1"; if (!fs::exists(includeDir / "__config")) { return {{}, std::format("sysroot {} has no libc++ headers at {}; install its libc++ development package", sysroot.string(), includeDir.string())}; } const std::int32_t wanted = LibcxxVersion(includeDir); const bool comparable = wanted != 0 && tc.libcxxVersion != 0; // Releases are matched on the major version: a release branch only takes // fixes, so 22.1.3 headers and the 22.1.8 module source name the same // declarations. if (comparable && wanted / 10000 == tc.libcxxVersion / 10000 && fs::exists(tc.stdCppm)) return {tc.stdCppm, {}}; if (wanted != 0 && !tc.stdModulesDir.empty()) { const fs::path shipped = tc.stdModulesDir / std::to_string(wanted / 10000) / "std.cppm"; if (fs::exists(shipped)) return {shipped, {}}; } // One of the two releases is unknown, so there is nothing to compare: // hand over the toolchain's source and let the compile decide, which is // what happened for every sysroot before releases were compared. if (!comparable && fs::exists(tc.stdCppm)) return {tc.stdCppm, {}}; const std::string sysrootRelease = wanted != 0 ? LibcxxVersionString(wanted) : std::string("of an unknown release"); const std::string toolchainSource = !fs::exists(tc.stdCppm) ? std::string("the toolchain has no std module source at all") : std::format("the toolchain's is for libc++ {}", LibcxxVersionString(tc.libcxxVersion)); return {{}, std::format("sysroot {} carries libc++ {} without its std module source, and crafter-build has none for that release ({}); install the share/libc++/v1 directory of that libc++ release (std.cppm and std/) as {}", sysroot.string(), sysrootRelease, toolchainSource, own.parent_path().string())}; } std::string_view Crafter::CrafterBuildVersion() { return CRAFTER_BUILD_VERSION; }