Crafter.Build/implementations/Crafter.Build-Toolchain.cpp
Jorijn van der Graaf 3c8f4ddb54
fix(build): read what a source declares and imports with clang-scan-deps
GetInterfacesAndImplementations found the module declarations and the
imports of a configuration's sources by searching their text with
regular expressions, after deleting the comments that fit on one line.
The expressions skipped neither string literals nor comments that span
lines, knew nothing of the preprocessor, and wanted one space after
`import` and none before its semicolon (#45). An implementation source
that held "export module std;" in a string literal was taken for a unit
of a module std, and listing it threw "Module std not found not found".
An import in a comment that spans lines or under #if 0 was followed.
`import  X;` and `import X ;` were missed, so their unit had no edge to
the module it imports and could be compiled before that module's BMI was
written.

What a .cppm or .cpp declares and imports now comes from clang-scan-deps
-format=p1689, which preprocesses the source with the configuration's
C++ compile command, the one Build() compiles every unit of it with:
strings, comments, spacing, macros and #if come out as they do for the
compiler. GetInterfacesAndImplementations only lists the sources, in the
new interfaceSources and implementationSources. Build() reads them
(ReadSources) once the configuration's dependencies and external
dependencies are built: the command takes their include paths, and a
source may include headers of an external dependency, which are not
there before it is fetched. From what it read, Build() makes the
configuration's modules and units, its `interfaces` and
`implementations`, and places each import on a module of the
configuration or of what it is built on, whose own Build() has read its
sources by then. It makes those of its own configuration alone, as the
reset of the units' state did before it.

A build pass builds a directory once, for whichever configuration of it
asks first, and the loader can make two configurations of one directory:
one project loaded along two paths with its args in two orders, which it
keeps apart and VariantId, sorting the args, does not. Only the one that
was built has the modules that build read, so the result of a build now
names the configuration it ran on (BuildResult::built), and a
dependency's modules are looked up through the pass's record of its
directory. 6.4.1 had every configuration's modules from the listing and
took such a graph for one with two builds of a module, which it refused;
it is now built, once, and the units of both sides have their edges.

A scan is kept in the build directory as an object is, in scans/ or, for
a source outside cfg.path, in scans-outside/, as JSON of the command it
was taken with and of what clang-scan-deps wrote, with the dependency
file clang-scan-deps wrote beside it, which lists the source and every
file it included. A build scans a source again unless its scan is newer
than every file that dependency file lists, was taken with the same
command and can be read, so a build with nothing changed runs no
clang-scan-deps. Both files are written beside their places and renamed
into them, as the archive and the list of objects are, for another
crafter-build that may be building the same clone.

A configuration's modules are known only once its build has read its
sources, so the refusals of a module that two configurations of the
graph build (DuplicateModuleError, #41) and of interface units that
import each other (ImportCycleError) now come there: once the
dependencies are built, before any .cppm or .cpp of the configuration is
compiled. They came before the configuration made a directory or built a
dependency. The contributor guide names clang-scan-deps among the
prerequisites and among what :Toolchain resolves, has a test look at the
modules of a configuration only after building it, and has the gotcha
for the new order.

ResolvePendingImports and the pendingImports of the unit classes go.
They placed the imports that a scan at listing time could not, once the
dependencies were wired up, and with the imports placed when the
dependencies are built there is nothing pending. The tests that looked
at a configuration's modules and units before building now look after it
(DependencyLink, ModuleInterface, StaticLib, ConcurrentDependencyReset
and the disabled TransitiveInterfaceChange), IncrementalInterfaceChange
checks the edge that the build of a consumer gives it when its
dependency was assigned after its sources were listed, and ImportCycle
and DuplicateModule check that the refused configuration compiled
nothing of its own. The workarounds for the old scanner are not needed:
MingwSysroot writes its stand-in std module as a plain literal again,
JobLimit writes the declarations of the sources it generates as plain
literals, and Lint's comment on its fixture file no longer gives the
scanner as the reason for it.

The messages of the regex code stay where they still apply. The one for
a source that declares a unit of a module the configuration does not
have loses its doubled "not found", and applies to an implementation
source that declares one, such as an implementation partition
(`module X:P;`). An implementation unit written `module X;` declares no
unit for clang-scan-deps but imports X, and an import needs no module of
the configuration: the compile reports a module no one builds. A .cppm
that declares an implementation partition is built as a partition of its
module, where it was refused as declaring no module.

The Toolchain gains clangScanDeps, resolved as llvm-ar is: in the bin/
of the LLVM prefix, else by name on PATH. The Flatpak has
/app/bin/clang-scan-deps.

Fixes #45
2026-11-27 09:25:53 +01:00

532 lines
27 KiB
C++

// 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/<id>/<arch>/<branch> line
// in the [Application] group of a .flatpak-info; empty when it has none.
std::pair<std::string, std::string> 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<std::string_view> 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-<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;
fs::path ViewedPrefix;
std::atomic<bool> 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 <prefix>/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::uint32_t>(std::hash<std::string>{}(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";
tc.clangScanDeps = "clang-scan-deps";
} 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";
tc.clangScanDeps = tc.prefix / "bin" / "clang-scan-deps";
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
// <prefix>/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<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);
}
}
// 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<std::string> 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<std::string>& value) { return value ? std::format("={}", *value) : std::string("unset"); };
tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to<std::string>(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder));
}
// The static runtime beside that nvcc, for the link of a configuration
// with CUDA sources. Looked for without throwing: a lib64 that cannot be
// looked into, through a link loop or for want of permission, counts as
// one without it.
if (!tc.nvcc.empty()) {
const fs::path archive = tc.nvcc.parent_path().parent_path() / "lib64" / "libcudart_static.a";
if (std::error_code ec; fs::exists(archive, ec)) tc.cudaRuntime = archive;
}
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<char>(file), std::istreambuf_iterator<char>());
}
}
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<const fs::path> 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<std::string>{}(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<fs::path> 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;
}