diff --git a/AGENTS.template.md b/AGENTS.template.md index 2a93992..6a8ea07 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -122,7 +122,7 @@ Beyond the rules: - There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. - Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. -- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`) and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. +- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. ## Design rules diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 20567d6..e7e04a1 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -1145,7 +1145,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath))) { const Toolchain& toolchain = GetToolchain(); if (toolchain.nvcc.empty()) { @@ -1155,11 +1156,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map& seen, bool linked = true) { + if (!seen.insert(&config).second) return false; + if (linked && !config.cuda.empty() && config.cudaArch == "native") return true; + return std::ranges::any_of(config.dependencies, [&seen](const Configuration* dep) { return HasNativeCuda(*dep, seen, dep->type != ConfigurationType::Executable); }); + } +} + std::string Crafter::BundleFlatpakApp(const Configuration& config) { if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused; const FlatpakExport app = ExportOf(config); @@ -1753,6 +1769,9 @@ std::string Crafter::BundleFlatpakApp(const Configuration& config) { if (config.march == "native") { Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string())); } + if (std::unordered_set seen; HasNativeCuda(config, seen)) { + Progress::Diagnostic(std::format("{} holds CUDA code built with --cuda-arch=native, for this machine's GPUs and with no PTX, so it may not run on another machine's GPU; for others, build with --cuda-arch=all-major", bundle.string())); + } if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string()); return ""; } @@ -2000,6 +2019,9 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span 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; } @@ -328,6 +367,9 @@ const Toolchain& Crafter::GetToolchain() { } 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"); diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index 19a7047..d8b8901 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -504,6 +504,16 @@ export namespace Crafter { std::vector implementations; std::vector cFiles; std::vector cuda; + // The GPU architecture nvcc compiles `cuda` for, as its -arch takes + // one. "native", the default, compiles for the GPUs of the machine + // that builds, as march's default does for its CPU; with none to be + // seen, nvcc warns and uses its own default. Like -march=native it is + // for a program that runs where it is built: it carries no PTX, which + // a newer GPU could compile when it loads the program. "sm_89" is one + // architecture with its PTX; "all-major" or "all" is for a program + // that runs elsewhere. ApplyStandardArgs sets it from + // CRAFTER_BUILD_CUDA_ARCH and --cuda-arch=. + std::string cudaArch = "native"; std::vector dependencies; std::vector files; // Build-time-only source files this configuration exposes to its own @@ -593,9 +603,9 @@ export namespace Crafter { void ResolvePendingImports(); // Declare a test. Sources default to `tests//main.cpp` resolved // against this Configuration's path; target/march/mtune/sysroot/debug - // are inherited from this Configuration so cross-arch projects don't - // have to re-specify. Returns a builder for chaining defines, deps, - // etc. Defined in Crafter.Build:Test. + // and cudaArch are inherited from this Configuration so cross-arch + // projects don't have to re-specify. Returns a builder for chaining + // defines, deps, etc. Defined in Crafter.Build:Test. struct TestBuilder AddTest(std::string_view name); // Same as AddTest, but compiles the parent's `interfaces` directly // into this test's Configuration (rather than going through a dep). @@ -625,7 +635,7 @@ export namespace Crafter { // Suffix that uniquely identifies this Configuration's compile state. // target+march+mtune are spelled out for readability; the rest // (type, debug, sysroot, defines, compileFlags, the std module, the - // toolchain) + // toolchain, the GPU architecture and the nvcc of CUDA sources) // collapse into a short hash so two Configurations sharing a path but // with different compile state can't clobber each other's outputs. std::string VariantId() const { return VariantId(GetToolchain()); } @@ -690,6 +700,25 @@ export namespace Crafter { } compileKey += "|T:"; compileKey += toolchain.Key(); + // The GPU architecture decides what a .cu compiles into, and so + // does the toolkit whose nvcc compiles it, which CUDA_PATH can + // switch and an update can replace at the same path, so the nvcc + // is keyed by what it is (Toolchain::nvccStamp), and native by the + // GPUs it resolves to (Toolchain::cudaNativeKey). None of them + // need touch the files whose times decide whether a .cu is + // compiled again, so each needs a directory of its own. Only keyed + // with CUDA sources, so every other configuration keeps the + // directory it had. + if (!cuda.empty()) { + compileKey += "|C:"; + compileKey += cudaArch; + compileKey += '|'; + compileKey += toolchain.nvccStamp; + if (cudaArch == "native") { + compileKey += '|'; + compileKey += toolchain.cudaNativeKey; + } + } // A Flatpak lays its bin dir out unlike the executable as linked, // so the two never share one. Only keyed for a Flatpak, so every // other configuration keeps the directory it had. @@ -867,6 +896,7 @@ export namespace Crafter { // --target= cfg.target = // --march= cfg.march = // --mtune= cfg.mtune = + // --cuda-arch= cfg.cudaArch = // --lib cfg.type promoted Executable → LibraryStatic // --shared cfg.type promoted LibraryStatic → LibraryDynamic // --packaging= cfg.packaging = None or Flatpak (none, flatpak), @@ -878,7 +908,8 @@ export namespace Crafter { // LibraryDynamic regardless of arg order; each is a no-op when the // baseline doesn't match (e.g. --shared on an Executable, or --lib on a // pre-set library). - // $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE seed march/mtune. + // $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE / $CRAFTER_BUILD_CUDA_ARCH + // seed march/mtune/cudaArch. // Env applies first, then args, so CLI wins over env wins over caller's // pre-set defaults. Returns an ArgQuery over the same span so projects // can query their own flags (`--timing`, ...) without re-rolling the diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 604f6d1..e3bb39b 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -67,6 +67,17 @@ export namespace Crafter { // for want of a CUDA toolkit. fs::path nvcc; std::string nvccError; + // What that nvcc is, for VariantId: its canonical path, size and + // modification time, which change when the toolkit is updated or + // replaced at the same path, as the path alone does not. Empty + // without an nvcc. + std::string nvccStamp; + // What -arch=native compiles for on this machine, for VariantId: the + // NVIDIA display devices the PCI bus lists, by address and device ID, + // and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose among + // them and number them, each unset apart from empty. Empty without an + // nvcc. + std::string cudaNativeKey; // The Flatpak runtime crafter-build runs on, from the // runtime=runtime/// line of /.flatpak-info: // "x86_64" and "26.08" in the Flatpak, both empty outside one. A @@ -125,6 +136,19 @@ export namespace Crafter { // 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 cudaRoots; + // The PCI devices sysfs lists, one directory each with its vendor, + // device and class: GetToolchain() passes /sys/bus/pci/devices, which + // the sandbox shows too. What -arch=native compiles for is keyed by + // the NVIDIA display devices among them. + fs::path pciDevices; + // CUDA_VISIBLE_DEVICES, which chooses the GPUs -arch=native compiles + // for, when it is set: set but empty hides them all, which is not the + // same as unset, so it is kept apart from env, which holds non-empty + // values alone. + std::optional cudaVisibleDevices; + // CUDA_DEVICE_ORDER, when it is set: it decides which GPU a number in + // CUDA_VISIBLE_DEVICES means, by PCI address or by speed. + std::optional cudaDeviceOrder; }; // Pure path resolution: an env override wins, then a toolchain installed // beside crafter-build (/bin/clang++), then bare names on diff --git a/tests/StandardArgs/main.cpp b/tests/StandardArgs/main.cpp index 3a21241..e7d6d25 100644 --- a/tests/StandardArgs/main.cpp +++ b/tests/StandardArgs/main.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +#include import std; import Crafter.Build; using namespace Crafter; @@ -33,6 +34,31 @@ int main() { Check(cfg.mtune == "cortex-a72", "--mtune= should overwrite cfg.mtune"); } + // --cuda-arch= is nvcc's -arch for cfg.cuda, as --march= is the CPU's, + // and it defaults to native as march does. + { + Configuration plain; + Check(plain.cudaArch == "native", "the GPU architecture defaults to native, like march"); + Configuration cfg; + std::array raw = { "--cuda-arch=all-major" }; + ApplyStandardArgs(cfg, raw); + Check(cfg.cudaArch == "all-major", "--cuda-arch= sets cfg.cudaArch"); + Check(cfg.projectArgs.empty(), "--cuda-arch= is not a project arg"); + } + { + // CRAFTER_BUILD_CUDA_ARCH sets it as CRAFTER_BUILD_MARCH sets march, + // and the command line wins over it. + setenv("CRAFTER_BUILD_CUDA_ARCH", "sm_86", 1); + Configuration fromEnv; + ApplyStandardArgs(fromEnv, {}); + Check(fromEnv.cudaArch == "sm_86", "CRAFTER_BUILD_CUDA_ARCH sets cfg.cudaArch"); + Configuration both; + std::array raw = { "--cuda-arch=sm_120" }; + ApplyStandardArgs(both, raw); + Check(both.cudaArch == "sm_120", "--cuda-arch= wins over CRAFTER_BUILD_CUDA_ARCH"); + unsetenv("CRAFTER_BUILD_CUDA_ARCH"); + } + // --sysroot= sets cfg.sysroot (cross-compiles against a foreign root, // e.g. an Alpine aarch64 tree; also picked up by the std.cppm lookup // and the qemu test-runner's QEMU_LD_PREFIX). diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index 849c36a..6ab8186 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -302,6 +302,65 @@ int main() { Check(ResolveToolchain(in).nvcc.empty(), "a link to itself ends, and finds nothing"); fs::remove_all(host); } + { + // What VariantId keys a CUDA configuration's nvcc by: its canonical + // path, size and time, which an nvcc replaced at its path changes, + // as it does not change the path. + const fs::path toolkit = scratch / "stamped"; + Program(toolkit / "bin/nvcc"); + ToolchainInputs in; + in.env["CUDA_PATH"] = toolkit.string(); + const std::string before = ResolveToolchain(in).nvccStamp; + Check(before.starts_with(std::format("{}|", fs::canonical(toolkit / "bin/nvcc").string())), std::format("the stamp names the nvcc where its links lead (got '{}')", before)); + std::ofstream(toolkit / "bin/nvcc", std::ios::app) << "13.5"; + Check(ResolveToolchain(in).nvccStamp != before, "an nvcc replaced at its path stamps differently"); + Check(ResolveToolchain({}).nvccStamp.empty(), "no nvcc, no stamp"); + } + { + // What VariantId keys -arch=native by: the NVIDIA display devices the + // PCI bus lists, by slot and model, and CUDA_VISIBLE_DEVICES and + // CUDA_DEVICE_ORDER. Another GPU, the same GPUs in each other's slots, + // or another choice or numbering among them keys it differently; a + // GPU's audio function, another NVIDIA class, and another vendor's GPU + // do not count. + const fs::path toolkit = scratch / "native/toolkit"; + Program(toolkit / "bin/nvcc"); + const fs::path pci = scratch / "native/pci"; + const auto device = [&pci](std::string_view address, std::string_view vendor, std::string_view id, std::string_view type) { + fs::create_directories(pci / address); + std::ofstream(pci / address / "vendor") << vendor << "\n"; + std::ofstream(pci / address / "device") << id << "\n"; + std::ofstream(pci / address / "class") << type << "\n"; + }; + device("0000:34:00.0", "0x10de", "0x2684", "0x030000"); + device("0000:34:00.1", "0x10de", "0x22ba", "0x040300"); + device("0000:00:02.0", "0x8086", "0xa780", "0x030000"); + ToolchainInputs in; + in.env["CUDA_PATH"] = toolkit.string(); + in.pciDevices = pci; + const std::string one = ResolveToolchain(in).cudaNativeKey; + Check(one.contains("0x2684") && !one.contains("0x22ba") && !one.contains("0xa780"), std::format("native is keyed by the NVIDIA display devices alone (got '{}')", one)); + device("0000:ca:00.0", "0x10de", "0x2b85", "0x030200"); + const std::string two = ResolveToolchain(in).cudaNativeKey; + Check(two != one && two.contains("0x2b85"), std::format("another GPU keys it differently (got '{}')", two)); + in.cudaVisibleDevices = "1"; + const std::string chosen = ResolveToolchain(in).cudaNativeKey; + Check(chosen != two, "and so does CUDA_VISIBLE_DEVICES"); + in.cudaVisibleDevices = ""; + const std::string hidden = ResolveToolchain(in).cudaNativeKey; + Check(hidden != two && hidden != chosen, std::format("an empty CUDA_VISIBLE_DEVICES, which hides every GPU, keys apart from an unset one (got '{}')", hidden)); + in.cudaVisibleDevices.reset(); + Check(ResolveToolchain(in).cudaNativeKey == two, "unset again, the key is as it was"); + in.cudaDeviceOrder = "PCI_BUS_ID"; + Check(ResolveToolchain(in).cudaNativeKey != two, "CUDA_DEVICE_ORDER, which numbers the GPUs, keys it differently"); + in.cudaDeviceOrder.reset(); + device("0000:34:00.0", "0x10de", "0x2b85", "0x030200"); + device("0000:ca:00.0", "0x10de", "0x2684", "0x030000"); + const std::string swapped = ResolveToolchain(in).cudaNativeKey; + Check(swapped != two, std::format("so do the same GPUs in each other's slots (got '{}')", swapped)); + in.env.erase("CUDA_PATH"); + Check(ResolveToolchain(in).cudaNativeKey.empty(), "no nvcc, no key"); + } { // The cache key separates toolchains that would build different // PCMs and nothing else. diff --git a/tests/VariantId/main.cpp b/tests/VariantId/main.cpp index 0fc170c..11ab9ff 100644 --- a/tests/VariantId/main.cpp +++ b/tests/VariantId/main.cpp @@ -128,6 +128,42 @@ int main() { b.march = "x86-64-v3"; Check(a.VariantId() != b.VariantId(), "march change perturbs VariantId"); } + { + // The GPU architecture decides what a .cu compiles into, and it need + // not touch the files whose times decide whether a .cu is compiled + // again, so it keys the directory of a configuration with CUDA + // sources, and only of one. + Configuration a = MakeBase(); + a.cuda = { "/tmp/variant-id-test/kernel" }; + Configuration b = MakeBase(); + b.cuda = a.cuda; + b.cudaArch = "sm_89"; + Check(a.VariantId() != b.VariantId(), "cudaArch change perturbs the VariantId of a configuration with CUDA sources"); + Configuration c = MakeBase(); + Configuration d = MakeBase(); + d.cudaArch = "sm_89"; + Check(c.VariantId() == d.VariantId(), "without CUDA sources, cudaArch leaves VariantId alone"); + // So does the nvcc that compiles them, by what it is: CUDA_PATH can + // name another toolkit, and an update can replace one at its path, + // and the old one's objects must not pass for the new one's. + const Toolchain one = GetToolchain(); + Toolchain other = one; + other.nvccStamp = "/opt/other-cuda/bin/nvcc|1|1"; + Toolchain updated = other; + updated.nvccStamp = "/opt/other-cuda/bin/nvcc|2|2"; + Check(a.VariantId(one) != a.VariantId(other), "another nvcc perturbs the VariantId of a configuration with CUDA sources"); + Check(a.VariantId(other) != a.VariantId(updated), "so does an nvcc updated at the same path"); + Check(c.VariantId(one) == c.VariantId(other), "without CUDA sources, the nvcc leaves VariantId alone"); + // native is what nvcc finds on the machine, so the GPUs it finds key + // it as well, and only it. + Toolchain first = one; + first.cudaNativeKey = "0x2684|"; + Toolchain swapped = one; + swapped.cudaNativeKey = "0x2b85|"; + Check(a.VariantId(first) != a.VariantId(swapped), "another GPU perturbs the VariantId of a configuration with CUDA sources for native"); + Check(b.VariantId(first) == b.VariantId(swapped), "but not for a named architecture"); + Check(c.VariantId(first) == c.VariantId(swapped), "nor without CUDA sources"); + } { // A project flag the framework can't interpret still decides what gets // compiled and bundled, so it has to key into VariantId. Otherwise both