From 21380151785d5608dbaaef5f75295d3bdfed375c Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 19 Nov 2026 09:20:32 +0100 Subject: [PATCH 01/27] fix(build): write a static library's archive anew The archive step of a static library ran `llvm-ar rcs` on the archive the build before had left. `r` adds to an archive that is there: it replaces the members it is given and keeps every other member as it is. The object of a source that had left the configuration therefore stayed in the library, ahead of the members added after it. The link takes a symbol from the first archive member that defines it. So after a source of a static library had been renamed, the library held the object of the file under its old name and, after it, the one of the file under its new name, and whatever was built on the library went on linking the first. The object of a source taken out of the project stayed in the library the same way. The step now writes its archive under a name of its own, beside the archive's place, and Build() moves it there once the step has succeeded, so the archive holds the objects that step lists and no others. It is moved into place, and the old archive not removed first, because another crafter-build may be linking against the library at that moment: a project loaded with GitProject is built in its clone in the cache, which every project that names the same source shares, and nothing keeps two crafter-builds from building it at once. llvm-ar put the new archive in the place of the old one in one step, so such a link found one of the two, and with the move it still does. A step that fails leaves the archive of the build before, as it did, and the next build runs the step again. build.sh has written the bootstrap's archive anew since 046609f, for the same reason, by removing it first. --- implementations/Crafter.Build-Clang.cpp | 91 +++++++++++++++++++++---- 1 file changed, 79 insertions(+), 12 deletions(-) diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index f512509..85b860c 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -763,6 +763,35 @@ namespace { d.programEntries = placed; return WriteFlatpakFiles(d); } + + // The name a file is written under before MoveIntoPlace gives it its + // own: beside its place, so that the move is a rename, and no other + // write's, in this process or in another. A build writes files that a + // step of another crafter-build may be reading at that moment: a + // project loaded with GitProject is built in its clone in the cache, + // which every project that names the same source shares, and nothing + // keeps two crafter-builds from building it at once. The name is made + // of random bits and not of the process's id: a crafter-build that + // runs as a Flatpak has the process ids of its own sandbox, and two of + // them the same ones. + fs::path WrittenBeside(const fs::path& file) { + std::random_device random; + return fs::path(file) += std::format(".{:08x}{:08x}.tmp", random(), random()); + } + + // Moves `written` to `file`. The rename puts it there in one step: what + // opens `file` finds the file of before or this one, never none and + // never part of one, and what has the file of before open goes on + // reading that one. Returns what went wrong, with `written` removed; + // empty when nothing did. + std::string MoveIntoPlace(const fs::path& written, const fs::path& file) { + std::error_code ec; + fs::rename(written, file, ec); + if (!ec) return ""; + std::string failed = std::format("cannot move {} to {}: {}", written.string(), file.string(), ec.message()); + fs::remove(written, ec); + return failed; + } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { @@ -1524,11 +1553,23 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map Date: Thu, 19 Nov 2026 09:20:32 +0100 Subject: [PATCH 02/27] test(build): a source that leaves a static library leaves its archive StaticLibSourceRemoved builds a static library and a program on it, on a fresh copy of its fixture outside the checkout. The library has three sources: lib/first.cpp and lib/second.cpp each define Value(), returning 1 and 2, and lib/extra.cpp defines a function nothing calls. It is built three times, by configurations of one name and directory: from the first and the extra source, from the first alone, and from the second in the first's place, as the project of a renamed source lists it. The program prints 1, 1 and 2, and `llvm-ar t` lists the archive's members as first_impl.o and extra_impl.o, then first_impl.o, then second_impl.o. While the second and the third build run, a thread of the test looks for the archive again and again and has to find it every time: the new archive is moved into the place of the old one, where a build that removed the old one first would leave whatever links the library at that moment without it. Before the fix the second build's archive listed first_impl.o and extra_impl.o, and the third's those two and second_impl.o, with a program that printed 1. --- project.cpp | 1 + .../fixture/lib/extra.cpp | 6 + .../fixture/lib/first.cpp | 4 + .../fixture/lib/second.cpp | 4 + tests/StaticLibSourceRemoved/fixture/main.cpp | 13 ++ tests/StaticLibSourceRemoved/main.cpp | 168 ++++++++++++++++++ 6 files changed, 196 insertions(+) create mode 100644 tests/StaticLibSourceRemoved/fixture/lib/extra.cpp create mode 100644 tests/StaticLibSourceRemoved/fixture/lib/first.cpp create mode 100644 tests/StaticLibSourceRemoved/fixture/lib/second.cpp create mode 100644 tests/StaticLibSourceRemoved/fixture/main.cpp create mode 100644 tests/StaticLibSourceRemoved/main.cpp diff --git a/project.cpp b/project.cpp index adaaddf..294f04f 100644 --- a/project.cpp +++ b/project.cpp @@ -247,6 +247,7 @@ extern "C" Configuration CrafterBuildProject(std::span a if (linuxTarget) { cfg.AddTest("HelloWorld").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StaticLib").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("StaticLibSourceRemoved").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ModuleInterface").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("DependencyLink").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("SharedLibraryRuns").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/StaticLibSourceRemoved/fixture/lib/extra.cpp b/tests/StaticLibSourceRemoved/fixture/lib/extra.cpp new file mode 100644 index 0000000..f4c38a0 --- /dev/null +++ b/tests/StaticLibSourceRemoved/fixture/lib/extra.cpp @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Nothing calls this: the test looks for the object of this file among the +// members of the library's archive. +int Extra() { return 3; } diff --git a/tests/StaticLibSourceRemoved/fixture/lib/first.cpp b/tests/StaticLibSourceRemoved/fixture/lib/first.cpp new file mode 100644 index 0000000..3d8e490 --- /dev/null +++ b/tests/StaticLibSourceRemoved/fixture/lib/first.cpp @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int Value() { return 1; } diff --git a/tests/StaticLibSourceRemoved/fixture/lib/second.cpp b/tests/StaticLibSourceRemoved/fixture/lib/second.cpp new file mode 100644 index 0000000..4e04aac --- /dev/null +++ b/tests/StaticLibSourceRemoved/fixture/lib/second.cpp @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int Value() { return 2; } diff --git a/tests/StaticLibSourceRemoved/fixture/main.cpp b/tests/StaticLibSourceRemoved/fixture/main.cpp new file mode 100644 index 0000000..7d987b8 --- /dev/null +++ b/tests/StaticLibSourceRemoved/fixture/main.cpp @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +int Value(); + +// Prints what the library's Value() returns: 1 from lib/first.cpp, 2 from +// lib/second.cpp, whichever the library was built from. +int main() { + std::printf("%d", Value()); + return 0; +} diff --git a/tests/StaticLibSourceRemoved/main.cpp b/tests/StaticLibSourceRemoved/main.cpp new file mode 100644 index 0000000..51f19a0 --- /dev/null +++ b/tests/StaticLibSourceRemoved/main.cpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A static library holds the objects of the sources its configuration lists +// and no others. Its archive used to be updated where it lay: `llvm-ar rcs` +// into an archive that is there replaces the members it is given and leaves +// every other member as it is, so the object of a source that had left the +// project stayed in the library. The link takes a symbol from the first +// member that defines it, and a member left behind comes before the ones +// added after it: once a source had been renamed, whatever was built on the +// library went on linking the object of the file under its old name. +// +// The fixture's library has three sources. lib/first.cpp and lib/second.cpp +// each define Value(), returning 1 and 2, and lib/extra.cpp defines a +// function nothing calls. The library is built three times, by +// configurations of one name and directory, so into one archive: from the +// first and the extra source; from the first alone, the extra one taken out +// of the project and nothing else changed; and from the second in the +// first's place, as the project of a renamed source lists it. Each time the +// archive has to hold the objects of the sources listed and no other, and +// the program built on the library to print what the Value() listed returns. +// +// The archive also has to be in its place for as long as it is written +// anew: a library that another project is built on may be linked by that +// project's crafter-build at any moment, where both build it in one clone +// in the cache. While the second and the third build run, a thread looks +// for the archive again and again. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // Built into the fixture's own bin/ and build/, which an earlier run + // would have left with the last archive in them: a copy that starts + // with neither. + fs::path StageFixture() { + const fs::path source = fs::current_path() / "tests" / "StaticLibSourceRemoved" / "fixture"; + const fs::path staged = fs::temp_directory_path() / "crafter-build-static-lib-source-removed"; + fs::remove_all(staged); + fs::copy(source, staged, fs::copy_options::recursive); + return staged; + } + + // The library, of the lib/.cpp listed. One name and one + // directory whichever sources it lists, so one build directory and one + // archive: the same library before and after a source leaves it. + std::unique_ptr MakeLib(const fs::path& staged, std::vector sources) { + std::unique_ptr lib = std::make_unique(); + lib->path = staged / "lib"; + lib->name = "value"; + lib->outputName = "value"; + lib->target = HostTarget(); + lib->type = ConfigurationType::LibraryStatic; + std::array ifaces = {}; + lib->GetInterfacesAndImplementations(ifaces, sources); + return lib; + } + + Configuration MakeApp(const fs::path& staged, Configuration* lib) { + Configuration app; + app.path = staged; + app.name = "value-app"; + app.outputName = "value-app"; + app.target = HostTarget(); + app.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + app.dependencies = { lib }; + return app; + } + + bool BuildOk(Configuration& app, std::string_view label) { + // A fresh record for each pass: one that already holds the library's + // build would hand it to the next pass unbuilt. + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult r = Build(app, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "FAIL: {} failed: {}", label, r.result); + ++Failures; + return false; + } + return true; + } + + // Builds `app` as BuildOk does, with a thread looking for `archive` from + // before the build starts until it has ended: whether the build + // succeeded and the archive was there every time. + bool BuildOkWithArchiveInPlace(Configuration& app, const fs::path& archive, std::string_view label) { + std::atomic missing{false}; + bool built = false; + { + std::jthread watcher([&archive, &missing](std::stop_token stop) { + while (!stop.stop_requested()) { + std::error_code ec; + if (!fs::exists(archive, ec)) missing = true; + } + }); + built = BuildOk(app, label); + // Leaving the scope stops the watcher and waits for it. + } + Check(!missing, std::format("{}: the archive is in its place for as long as the build writes it anew", label)); + return built; + } + + void CheckPrints(const Configuration& app, std::string_view expected, std::string_view label) { + const auto r = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30)); + Check(r.exitCode == 0 && r.output == expected, std::format("{}: the program printed '{}' (exit {}), expected '{}'", label, r.output, r.exitCode, expected)); + } + + // The members of `lib`'s archive, as `llvm-ar t` lists them, have to be + // `expected`, one to a line. + void CheckMembers(const Configuration& lib, std::string_view expected, std::string_view label) { + const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(lib).string())), std::chrono::seconds(30)); + Check(members.exitCode == 0 && members.output == expected, std::format("{}: llvm-ar t lists '{}' (exit {}), expected '{}'", label, members.output, members.exitCode, expected)); + } +} + +int main() { + const fs::path staged = StageFixture(); + + const std::unique_ptr both = MakeLib(staged, { "first", "extra" }); + Configuration withExtra = MakeApp(staged, both.get()); + if (!BuildOk(withExtra, "the build with lib/first.cpp and lib/extra.cpp")) return 1; + CheckPrints(withExtra, "1", "built with lib/first.cpp and lib/extra.cpp"); + CheckMembers(*both, "first_impl.o\nextra_impl.o\n", "the archive of lib/first.cpp and lib/extra.cpp"); + + // What the passes below rest on: were the configurations built into + // directories of their own, each archive would be made from nothing and + // the later passes would prove nothing. + const fs::path archive = ExpectedOutput(*both); + + // No source is compiled for this one and no object is newer than the + // archive: that the library lists one object fewer is all that changed. + const std::unique_ptr alone = MakeLib(staged, { "first" }); + Check(ExpectedOutput(*alone) == archive, "the library is one archive whichever sources it lists"); + Configuration withoutExtra = MakeApp(staged, alone.get()); + if (BuildOkWithArchiveInPlace(withoutExtra, archive, "the build with lib/extra.cpp taken out")) { + CheckPrints(withoutExtra, "1", "built with lib/extra.cpp taken out"); + CheckMembers(*alone, "first_impl.o\n", "the archive with lib/extra.cpp taken out"); + } + + const std::unique_ptr renamed = MakeLib(staged, { "second" }); + Check(ExpectedOutput(*renamed) == archive, "and when another source is in the first's place"); + Configuration afterRename = MakeApp(staged, renamed.get()); + if (BuildOkWithArchiveInPlace(afterRename, archive, "the build with lib/second.cpp in the place of lib/first.cpp")) { + CheckPrints(afterRename, "2", "built with lib/second.cpp in the place of lib/first.cpp"); + CheckMembers(*renamed, "second_impl.o\n", "the archive with lib/second.cpp in the place of lib/first.cpp"); + } + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From 93eca17e575e428a6256d9b05dc4b67e68e5e382 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 19 Nov 2026 10:33:33 +0100 Subject: [PATCH 03/27] fix(build): give a link its objects in a response file Build() wrote the path of every object of a configuration into its link or archive command. A command is run by a shell, which is given it as one argument, and Linux holds one argument to 32 pages: 131,072 bytes with pages of 4 KiB, the terminating byte included. Once the objects' paths left the command longer than that, popen started no shell and the build ended with "popen() failed!". Issue #50 notes the limit, and that a response file for the objects would take it away. The step now reads its objects from a file that the command names with @, .objects in the build directory, one object to a line. clang and llvm-ar both take arguments from such a response file, so the link of an executable or a shared library and the archive step of a static library are handed their objects the same way, and the command is as long for a thousand sources as for one. Build() keeps the objects as a list for that, where it joined their paths into the command as it went over the sources. Each line is quoted for the reader of a response file, which differs from the shell's: it takes a backslash inside quotes to quote the character after it. The file is written before every run of the step, and one that cannot be written fails the build: the list of an earlier build would otherwise stay in its place and the step would read its objects. It is written under a name of its own beside its place and moved there, as the archive of a static library is, so that a step of another crafter-build which reads the list at that moment reads the list it opened, whole, or the new one. The record that decides whether an unchanged build links again held the command, which held the objects. It now holds the command and, under it, the list. The command only names the file, so taking a source out of a configuration can leave the command as it was, with no object newer than the output, as the second build of StaticLibSourceRemoved does: the list is then all that says the step has to run again. --- implementations/Crafter.Build-Clang.cpp | 72 ++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 8 deletions(-) diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 85b860c..88aca5a 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -792,6 +792,22 @@ namespace { fs::remove(written, ec); return failed; } + + // `argument` as one argument in a response file, the file of further + // arguments a command names with @. clang and llvm-ar split such a file + // at whitespace, keep what stands in quotes together, and take a + // backslash to quote the character after it, inside quotes as well. + // That last is why this is not ShellQuote: the shell keeps a backslash + // in single quotes as it is. + std::string ResponseFileArgument(std::string_view argument) { + std::string quoted = "\""; + for (const char c : argument) { + if (c == '"' || c == '\\') quoted.push_back('\\'); + quoted.push_back(c); + } + quoted.push_back('"'); + return quoted; + } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { @@ -1146,7 +1162,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map objects; std::set libSet; std::set runtimeSet; std::set publicFlagSet; @@ -1204,8 +1222,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapCheck(pcmDir, externalFloor)) { buildResult.repack = true; } - files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string()); + objects.push_back(buildDir / std::format("{}.o", interface->path.filename().string())); for(std::unique_ptr& part : interface->partitions) { - files += std::format(" {}/{}.o", buildDir.string(), part->path.filename().string()); + objects.push_back(buildDir / std::format("{}.o", part->path.filename().string())); } } @@ -1410,7 +1428,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map(recorded)), std::istreambuf_iterator()); - if (previous != linkCommand) buildResult.repack = true; + if (previous != linked) buildResult.repack = true; } if(buildResult.repack) { @@ -1633,6 +1669,26 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map Date: Thu, 19 Nov 2026 10:33:33 +0100 Subject: [PATCH 04/27] test(build): a link of more objects than one argument holds LinkManyObjects makes a project six directories deep, each with a name of 200 characters, with 120 C sources and a main.cpp that adds up what each of them returns. Every object lies in the project's build directory, so the test first checks that 120 times the length of that directory's path is more than 131,072 bytes. It then builds the sources three ways: as one executable, as a static library and as a shared library, the libraries each with an executable of main.cpp built on it. Each of the three programs prints the sum. It then opens the list the static library's archive step read, builds the library again with one source fewer, and reads what it had opened: the 120 lines of the first build, while the list in its place has the 119 of the second. Before the fix each of the three builds ended with "popen() failed!": the executable's at its link, the other two at the archive step and the link of the library. No list was written, so the test found none to open. --- project.cpp | 1 + tests/LinkManyObjects/main.cpp | 168 +++++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 tests/LinkManyObjects/main.cpp diff --git a/project.cpp b/project.cpp index 294f04f..d412813 100644 --- a/project.cpp +++ b/project.cpp @@ -248,6 +248,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("HelloWorld").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StaticLib").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StaticLibSourceRemoved").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("LinkManyObjects").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ModuleInterface").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("DependencyLink").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("SharedLibraryRuns").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/LinkManyObjects/main.cpp b/tests/LinkManyObjects/main.cpp new file mode 100644 index 0000000..57a9be6 --- /dev/null +++ b/tests/LinkManyObjects/main.cpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A configuration is linked from however many objects it has. Build() used +// to write the path of every object into the link or archive command, and a +// command is handed to a shell as one argument, which Linux holds to 32 +// pages: 131,072 bytes with pages of 4 KiB, the terminating byte included. +// With objects whose paths came to more, no shell started, and the build +// ended with "popen() failed!". +// +// The test makes a project six directories deep, each with a name of 200 +// characters, so that the path of its build directory alone is long, and +// gives it 120 C sources and a main.cpp that adds up what each of them +// returns. Every object lies in the build directory, so the paths of the +// 120 come to more than one argument holds. It builds the sources three +// ways: as one executable, whose link is given the objects, as a static +// library, whose archive step is, and as a shared library, the two +// libraries each with an executable of main.cpp built on it. Every program +// has to print the sum, which it does only when every object reached its +// link. +// +// The step reads its objects from a list in the build directory, and a step +// may be reading that list when the next build writes another: a library +// that two projects are built on is built by the crafter-build of each, in +// one clone in the cache. So the test holds the static library's list open, +// as a step that reads it does, builds the library again with one source +// fewer, and then reads what it has open: that has to be the whole list of +// the first build, not the next list or part of either. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + void Write(const fs::path& file, std::string_view text) { + std::ofstream(file, std::ios::binary | std::ios::trunc) << text; + } + + constexpr std::int32_t Sources = 120; + // What every program prints: source i returns i. + constexpr std::int32_t Sum = Sources * (Sources - 1) / 2; + // The most one argument of a command may be where a page is 4 KiB. + constexpr std::size_t ArgumentLimit = 32 * 4096; + + // A configuration in `project` that is linked for the machine that + // builds. + Configuration Named(const fs::path& project, std::string_view name, ConfigurationType type) { + Configuration cfg; + cfg.path = project; + cfg.name = std::string(name); + cfg.outputName = std::string(name); + cfg.target = HostTarget(); + cfg.type = type; + return cfg; + } + + // An executable of main.cpp alone. + Configuration Program(const fs::path& project, std::string_view name) { + Configuration cfg = Named(project, name, ConfigurationType::Executable); + std::array ifaces = {}; + std::array impls = { "main" }; + cfg.GetInterfacesAndImplementations(ifaces, impls); + return cfg; + } + + // What went wrong building `cfg`; empty when nothing did. Before the + // fix the build threw where the shell did not start. + std::string BuildError(Configuration& cfg) { + try { + std::unordered_map> depResults; + std::mutex depMutex; + return Build(cfg, depResults, depMutex).result; + } catch (const std::exception& e) { + return std::format("Build() threw: {}", e.what()); + } + } + + // Builds `cfg` and runs what it links. + void CheckBuildsAndPrintsSum(Configuration& cfg, std::string_view label) { + const std::string error = BuildError(cfg); + Check(error.empty(), std::format("{} builds: {}", label, error)); + if (!error.empty()) return; + const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30)); + Check(run.exitCode == 0 && run.output == std::to_string(Sum), std::format("{}: the program printed '{}' (exit {}), expected {}", label, run.output, run.exitCode, Sum)); + } + + // How many lines `text` has. + std::int64_t Lines(std::string_view text) { + return std::ranges::count(text, '\n'); + } +} + +int main() { + const fs::path root = fs::temp_directory_path() / "crafter-build-link-many-objects"; + fs::remove_all(root); + fs::path project = root; + for (const char letter : std::string_view("abcdef")) project /= std::string(200, letter); + fs::create_directories(project); + + // Without their extension and whole, as cFiles are read against the + // working directory. + std::vector sources; + std::string declarations; + std::string sum; + for (std::int32_t i = 0; i < Sources; ++i) { + const fs::path source = project / std::format("unit{}", i); + Write(fs::path(source) += ".c", std::format("int unit_{0}(void) {{ return {0}; }}\n", i)); + sources.push_back(source); + declarations += std::format("extern \"C\" int unit_{}(void);\n", i); + sum += std::format(" + unit_{}()", i); + } + // printf by its declaration, so that main.cpp, which is compiled once + // for each of the three programs, needs no header and no module. + Write(project / "main.cpp", std::format("extern \"C\" int printf(const char* format, ...);\n{}int main() {{ printf(\"%d\", 0{}); return 0; }}\n", declarations, sum)); + + Configuration whole = Program(project, "many"); + whole.cFiles = sources; + // What the test rests on: with a shorter list the builds below would + // have passed before the fix as well. Each object lies in the build + // directory, wherever in it, so its path is longer than that + // directory's. + const std::size_t listed = static_cast(Sources) * whole.BuildDir().string().size(); + Check(listed > ArgumentLimit, std::format("the paths of the {} objects come to more than {} bytes, more than the {} one argument may be", Sources, listed, ArgumentLimit)); + CheckBuildsAndPrintsSum(whole, "an executable of the sources"); + + Configuration archive = Named(project, "many-static", ConfigurationType::LibraryStatic); + archive.cFiles = sources; + Configuration onArchive = Program(project, "on-static"); + onArchive.dependencies = { &archive }; + CheckBuildsAndPrintsSum(onArchive, "an executable built on a static library of the sources"); + + Configuration shared = Named(project, "many-shared", ConfigurationType::LibraryDynamic); + shared.cFiles = sources; + Configuration onShared = Program(project, "on-shared"); + onShared.dependencies = { &shared }; + CheckBuildsAndPrintsSum(onShared, "an executable built on a shared library of the sources"); + + // The static library's list, opened as its archive step opens it, and + // not read yet. + const fs::path list = archive.BuildDir() / "many-static.objects"; + std::ifstream opened(list, std::ios::binary); + Check(opened.is_open(), std::format("the archive step read its objects from {}", list.string())); + Configuration fewer = Named(project, "many-static", ConfigurationType::LibraryStatic); + fewer.cFiles.assign(sources.begin(), sources.end() - 1); + const std::string error = BuildError(fewer); + Check(error.empty(), std::format("the static library builds again with one source fewer: {}", error)); + const std::string held((std::istreambuf_iterator(opened)), std::istreambuf_iterator()); + Check(Lines(held) == Sources, std::format("a list that is open when the next build writes its own is still the whole list it was: {} lines read, {} objects listed", Lines(held), Sources)); + std::ifstream next(list, std::ios::binary); + const std::string written((std::istreambuf_iterator(next)), std::istreambuf_iterator()); + Check(Lines(written) == Sources - 1, std::format("and the list in its place is the next build's: {} lines, {} objects listed", Lines(written), Sources - 1)); + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From 7f8089474b4c01731ef4a0a99920b682eaebd8e1 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 19 Nov 2026 11:02:39 +0100 Subject: [PATCH 05/27] fix(build): name a source's object from its path The object of an implementation unit was named from its file's name alone, /_impl.o, and that of a C or CUDA source likewise, _source.o. Two sources of one configuration with the same file name in different directories were therefore compiled into one object, each over the other, with one dependency file between them, and the link was given that object twice (issue #50). A build of an a/Thing.cpp and a b/Thing.cpp that each define a function failed at the link, with duplicate symbols of one of the two and no word of the other. A debug build of two such files that define nothing another file names succeeded, and its program had one file's code twice and the other's not at all. A .c and a .cu of one name shared an object in one directory as well. An object, with its dependency file beside it, is now named from where its source lies: under /objects by the source's path from the configuration's directory, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source outside that directory, under /objects-outside by its whole path. A .cu's object ends in _cuda.o; a .cpp's still ends in _impl.o and a .c's in _source.o. Two sources then have one object only when their paths are one once . and .. are taken out of them: any other two differ by path or by ending in one of the two directories, and the two directories share nothing, whatever a project calls its own directories. They are directories of their own, and not the build directory itself, because that one holds files named after other things: an interface unit's object, the record of the link and the list of its objects and, for an executable, the BMIs. ObjectPath gives that name, exported beside ExpectedOutput for what looks at an object from outside Build(). Build() names each object by the same rule, once, as it goes over the sources, and the list it keeps of them for the link is what the check whether an object is newer than the output reads as well. Before, each put the name together for itself: Implementation::Check, Implementation::Schedule, and Build() where it compiles C and CUDA sources, lists the link's objects and checks whether to link again. Implementation::Check and Schedule are given the object, where they put its name together from the build directory. The job that compiles a source makes the directory of its object first, since the compiler makes none. The C compile quotes its source, dependency file and object for the shell, as the CUDA compile does: the object of a source outside the configuration's directory holds that source's whole path, and so directories the command did not name before, the working directory's among them where the source is listed relative to it. The progress line of the compile of a .cpp, .c or .cu names the source by the path its object is named from, "Compiling a/Thing.cpp" where it was "Compiling Thing.cpp" for both, and so does the error for a .cu without an nvcc. What else changes: every implementation unit and every C and CUDA source has its object in a new place, so an existing build directory compiles them once more. The objects under the old names stay where they are, unused; a static library's archive does not keep them, being written anew. Interface units are as they were: a BMI is found by its module's name, so two interface files of one name would have to be one module. A source that a configuration lists twice is also as it was, compiled twice into its one object, which the link is given twice. In IncrementalHeaderChange, IncrementalInterfaceChange, StdPcmRebuild and TransitiveInterfaceChange, the lines that spelled out an object's old name take it from ObjectPath. Fixes #50 --- implementations/Crafter.Build-Clang.cpp | 160 ++++++++++++------ .../Crafter.Build-Implementation.cpp | 12 +- interfaces/Crafter.Build-Clang.cppm | 30 ++++ interfaces/Crafter.Build-Implementation.cppm | 14 +- tests/IncrementalHeaderChange/main.cpp | 8 +- tests/IncrementalInterfaceChange/main.cpp | 2 +- tests/StdPcmRebuild/main.cpp | 2 +- tests/TransitiveInterfaceChange/main.cpp | 4 +- 8 files changed, 162 insertions(+), 70 deletions(-) diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 88aca5a..bff76b7 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -320,6 +320,73 @@ fs::path Crafter::ExpectedOutput(const Configuration& config) { return mingwTarget ? dir / std::format("{}.dll", config.outputName) : dir / std::format("lib{}.so", config.outputName); } +namespace { + // `path` resolved against the working directory, with no `.` or `..` in + // it and no separator at its end. + fs::path WithoutSeparator(fs::path path) { + path = fs::absolute(path).lexically_normal(); + return path.has_filename() ? path : path.parent_path(); + } + + // What the name of a source's object ends in, by the source's + // extension: one ending for each kind of source, so a .c beside a .cu + // of its name has an object of its own. Empty for an extension Build() + // compiles no source of. + std::string_view ObjectSuffix(std::string_view extension) { + if (extension == ".cpp") return "_impl.o"; + if (extension == ".c") return "_source.o"; + if (extension == ".cu") return "_cuda.o"; + return ""; + } + + // ObjectPath's rule for the sources of one configuration, with what it + // takes from the configuration worked out once for all of them. + class SourceLayout { + public: + SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside") {} + + // The object of the source a configuration lists as `listed`, which + // is its path without its extension, `extension`. + fs::path Object(const fs::path& listed, std::string_view extension) const { + fs::path object = fs::absolute(listed).lexically_normal(); + object += ObjectSuffix(extension); + const fs::path within = Within(object); + return within.empty() ? outside / object.relative_path() : inside / within; + } + + // That source as the progress line of its compile names it: by its + // path from the configuration's directory, or by its whole path + // when it lies outside that directory. + std::string Shown(const fs::path& listed, std::string_view extension) const { + fs::path source = fs::absolute(listed).lexically_normal(); + source += extension; + const fs::path within = Within(source); + return within.empty() ? source.string() : within.string(); + } + + private: + // The path of `resolved` from the configuration's directory; empty + // when it does not lie in that directory. + fs::path Within(const fs::path& resolved) const { + const fs::path relative = resolved.lexically_relative(directory); + if (relative.empty() || relative == "." || *relative.begin() == "..") return {}; + return relative; + } + + fs::path directory; + fs::path inside; + fs::path outside; + }; +} + +fs::path Crafter::ObjectPath(const Configuration& config, const fs::path& source) { + const std::string extension = source.extension().string(); + if (ObjectSuffix(extension).empty()) throw std::invalid_argument(std::format("{} is not a .cpp, .c or .cu source", source.string())); + fs::path listed = source; + listed.replace_extension(); + return SourceLayout(config.path, config.BuildDir()).Object(listed, extension); +} + CompileCommand Crafter::GetCompileCommand(const Configuration& config) { CompileCommand out; out.stdPcmDir = StdPcmDir(config); @@ -884,6 +951,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map placed = {ExpectedOutput(config).filename().string()}; - const auto withoutSeparator = [](fs::path path) { - path = fs::absolute(path).lexically_normal(); - return path.has_filename() ? path : path.parent_path(); - }; - const fs::path outputRoot = withoutSeparator(outputDir); + const fs::path outputRoot = WithoutSeparator(outputDir); const auto place = [&](const fs::path& destination, const fs::path& source) { - const fs::path normal = withoutSeparator(destination); + const fs::path normal = WithoutSeparator(destination); if (normal != outputRoot) { placed.insert(normal.lexically_relative(outputRoot).begin()->string()); return; @@ -1222,22 +1288,36 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { - jobs.Add(std::format("Compiling {}.c", cFile.filename().string()), [command = std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())] { + // The job makes the directory of its object, which is one for + // the source's own directory: the compiler makes none. + // + // The source, the dependency file and the object are quoted + // for the shell, as the CUDA compile below quotes its own. The + // object of a source outside the configuration's directory is + // named by that source's whole path, and so holds directories + // this command did not name while an object lay in the build + // directory itself: the working directory's, where the source + // is listed relative to it. A build from a directory with a + // space in its name would have stopped here. + jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".c")), [directory = object.parent_path(), command = std::format("{8} {0} --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7} -o {9}", ShellQuote(srcPath), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, ShellQuote(std::format("{}.d", objPath)), GetToolchain().clang.string(), ShellQuote(objPath))] { + fs::create_directories(directory); return RunBuildCommand(command); }); } } for (const fs::path& cFile : config.cuda) { - const std::string objPath = std::format("{}_source.o", (buildDir / cFile.filename()).string()); - objects.emplace_back(objPath); + const fs::path object = layout.Object(cFile, ".cu"); + objects.push_back(object); + const std::string objPath = object.string(); const std::string srcPath = std::format("{}.cu", cFile.string()); // nvcc writes the depfile clang writes for a C source (-MD -MF): the // .cu and every header it read, the toolkit's and the system's among @@ -1249,10 +1329,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { const Toolchain& toolchain = GetToolchain(); if (toolchain.nvcc.empty()) { - jobs.Fail(std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError)); + jobs.Fail(std::format("cannot compile {}: {}", layout.Shown(cFile, ".cu"), toolchain.nvccError)); break; } - jobs.Add(std::format("Compiling {}.cu", cFile.filename().string()), [command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] { + jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".cu")), [directory = object.parent_path(), command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] { + fs::create_directories(directory); return RunBuildCommand(command); }); } @@ -1424,11 +1505,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map consumerMtime; - }; - for (const std::unique_ptr& iface : config.interfaces) { - if (objNewer(buildDir / std::format("{}.o", iface->path.filename().string()))) { + const fs::file_time_type written = fs::last_write_time(object, ec); + if (!ec && written > consumerMtime) { buildResult.repack = true; break; } - bool partHit = false; - for (const std::unique_ptr& part : iface->partitions) { - if (objNewer(buildDir / std::format("{}.o", part->path.filename().string()))) { - partHit = true; - break; - } - } - if (partHit) { buildResult.repack = true; break; } - } - if (!buildResult.repack) { - for (const Implementation& impl : config.implementations) { - if (objNewer(buildDir / std::format("{}_impl.o", impl.path.filename().string()))) { - buildResult.repack = true; - break; - } - } - } - // C and CUDA objects are archive members too, and their compile - // loop above is the only thing that knows it rebuilt one — it - // sets no repack flag, so without this a .c edit recompiled the - // object and then linked nothing. - if (!buildResult.repack) { - auto sourceObjNewer = [&](const std::vector& sources) { - for (const fs::path& source : sources) { - if (objNewer(buildDir / std::format("{}_source.o", source.filename().string()))) return true; - } - return false; - }; - if (sourceObjNewer(config.cFiles) || sourceObjNewer(config.cuda)) { - buildResult.repack = true; - } } } } diff --git a/implementations/Crafter.Build-Implementation.cpp b/implementations/Crafter.Build-Implementation.cpp index afc0ecf..132c0cd 100644 --- a/implementations/Crafter.Build-Implementation.cpp +++ b/implementations/Crafter.Build-Implementation.cpp @@ -13,8 +13,8 @@ namespace Crafter { Implementation::Implementation(fs::path&& path) : path(std::move(path)) { } - bool Implementation::Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor) const { - std::string objPath = std::format("{}_impl.o", (buildDir/path.filename()).string()); + bool Implementation::Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor) const { + std::string objPath = object.string(); std::string cppPath = std::format("{}.cpp", path.string()); // The depfile clang wrote beside the object lists the headers this TU // included; nothing else in the configuration knows about them, since @@ -36,7 +36,7 @@ namespace Crafter { } return false; } - void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const { + void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const { std::vector after; for(ModulePartition* dependency : partitionDependencies) { if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); @@ -50,7 +50,11 @@ namespace Crafter { // module rebuilt in place, for a mingw-w64 or libc++ update under // the same compiler, left the objects importing it as they were, and // the next build only relinked them. - jobs.Add(std::format("Compiling {}.cpp", path.filename().string()), [command = std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())] { + // + // The job makes the directory of its object, which is one for the + // source's own directory (ObjectPath): the compiler makes none. + jobs.Add(std::format("Compiling {}", shown), [directory = object.parent_path(), command = std::format("{0} {1}.cpp -c -MD -MF {2}.d -fmodule-file-deps -o {2}", clang, path.string(), object.string())] { + fs::create_directories(directory); return RunBuildCommand(command); }, after); } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index 5146bb9..d33e52a 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -804,6 +804,36 @@ export namespace Crafter { // disagree about the file name. fs::path ExpectedOutput(const Configuration& config); + // Where Build leaves the object of `source`, one of this Configuration's + // implementation units (.cpp), C sources (.c) or CUDA sources (.cu), + // given with its extension; a relative `source` is taken against the + // working directory, as Build takes cFiles and cuda. The dependency file + // the compiler writes lies beside it, as .d. + // + // The object is named from where the source lies: under + // BuildDir()/objects by the source's path from the Configuration's + // `path`, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source + // outside that directory, under BuildDir()/objects-outside by its whole + // path. The name ends in _impl.o for a .cpp, _source.o for a .c and + // _cuda.o for a .cu. So two sources have one object only when their + // paths are one once `.` and `..` are taken out of them as they are + // written: any other two differ by path or by ending in one of the two + // directories, and the two directories share nothing. + // + // Objects were named from the file name alone, in BuildDir() itself: + // a/Thing.cpp and b/Thing.cpp were both compiled into Thing_impl.o, + // each over the other, and the link was given that object twice. The + // link then failed, or, in a debug build of two sources that define + // nothing another file names, gave a program with one source's code + // twice and the other's not at all (issue #50). + // + // An interface unit's object is not named here. It lies in BuildDir() + // itself, named by the unit's file name alone, as its BMI is: clang + // looks a BMI up by its module's name, so two interface files of one + // name would have to be one module. Throws std::invalid_argument for a + // `source` with any other extension. + fs::path ObjectPath(const Configuration& config, const fs::path& source); + // `crafter-build install`: makes the Flatpak of the files/ `config` was // built as (see Packaging::Flatpak), with its permissions, puts it into // the project's repo, and installs it for this user from a user remote diff --git a/interfaces/Crafter.Build-Implementation.cppm b/interfaces/Crafter.Build-Implementation.cppm index f6e06a7..f18f0a9 100644 --- a/interfaces/Crafter.Build-Implementation.cppm +++ b/interfaces/Crafter.Build-Implementation.cppm @@ -19,10 +19,14 @@ namespace Crafter { std::vector pendingImports; fs::path path; Implementation(fs::path&& path); - bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const; - // Adds the job that compiles this unit to `jobs`, after the BMIs of - // the stale interface units it imports (ModulePartition::Schedule, - // Module::Schedule). For a unit Check found stale. - void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const; + // Whether `object`, the object Build() keeps for this unit + // (ObjectPath), has to be written again. + bool Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const; + // Adds the job that compiles this unit into `object` to `jobs`, after + // the BMIs of the stale interface units it imports + // (ModulePartition::Schedule, Module::Schedule), whose own objects go + // to `buildDir`. For a unit Check found stale. `shown` is the source + // as the job's progress line names it. + void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const; }; } diff --git a/tests/IncrementalHeaderChange/main.cpp b/tests/IncrementalHeaderChange/main.cpp index bda0682..ae946ca 100644 --- a/tests/IncrementalHeaderChange/main.cpp +++ b/tests/IncrementalHeaderChange/main.cpp @@ -111,9 +111,9 @@ int main() { // source, and the consumer that imports the module. fs::path interfacePcm = lib->PcmDir() / "Widget.pcm"; fs::path interfaceObject = lib->BuildDir() / "Widget.o"; - fs::path libraryObject = lib->BuildDir() / "Widget_impl.o"; - fs::path counterObject = lib->BuildDir() / "counter_source.o"; - fs::path consumerObject = app.BuildDir() / "main_impl.o"; + fs::path libraryObject = ObjectPath(*lib, staged / "lib" / "Widget.cpp"); + fs::path counterObject = ObjectPath(*lib, staged / "lib" / "counter.c"); + fs::path consumerObject = ObjectPath(app, staged / "main.cpp"); if (!BuildOk(app, "first pass")) { std::println(std::cerr, "{} assertions failed", Failures); @@ -187,7 +187,7 @@ int main() { // safe reading is "rebuild it once". { std::array before = stamps(); - fs::remove(lib->BuildDir() / "Widget_impl.o.d"); + fs::remove(fs::path(libraryObject) += ".d"); if (BuildOk(app, "missing depfile pass")) { std::array after = stamps(); Check(after[2] > before[2], "an object whose dependency record is missing is rebuilt"); diff --git a/tests/IncrementalInterfaceChange/main.cpp b/tests/IncrementalInterfaceChange/main.cpp index a570060..92c2d3d 100644 --- a/tests/IncrementalInterfaceChange/main.cpp +++ b/tests/IncrementalInterfaceChange/main.cpp @@ -169,7 +169,7 @@ int main() { std::unique_ptr lib = MakeLib(staged); Configuration app = MakeConsumerScannedBeforeDependencies(staged, lib.get()); fs::path binary = app.BinDir() / "widget-app"; - fs::path consumerObject = app.BuildDir() / "main_impl.o"; + fs::path consumerObject = ObjectPath(app, staged / "main.cpp"); if (BuildOk(app, "first pass")) { auto first = RunCommandWithTimeout(binary.string(), std::chrono::seconds(30)); diff --git a/tests/StdPcmRebuild/main.cpp b/tests/StdPcmRebuild/main.cpp index 291bee6..6fb1241 100644 --- a/tests/StdPcmRebuild/main.cpp +++ b/tests/StdPcmRebuild/main.cpp @@ -57,7 +57,7 @@ int main() { BuildResult built = BuildOnce(cfg); Check(built.result.empty(), std::format("the project builds: {}", built.result)); - const fs::path object = cfg.BuildDir() / "main_impl.o"; + const fs::path object = ObjectPath(cfg, project / "main.cpp"); const fs::path stdPcm = StdPcmDir(cfg) / "std.pcm"; Check(fs::exists(object) && fs::exists(stdPcm), std::format("{} and {} exist", object.string(), stdPcm.string())); if (!fs::exists(object) || !fs::exists(stdPcm)) return 1; diff --git a/tests/TransitiveInterfaceChange/main.cpp b/tests/TransitiveInterfaceChange/main.cpp index 1449319..4c423a6 100644 --- a/tests/TransitiveInterfaceChange/main.cpp +++ b/tests/TransitiveInterfaceChange/main.cpp @@ -206,8 +206,8 @@ int main() { fs::path binary = app.BinDir() / "consumer"; fs::path widgetInterfaceObject = widget->BuildDir() / "Widget.o"; - fs::path widgetImplObject = widget->BuildDir() / "Widget_impl.o"; - fs::path consumerObject = app.BuildDir() / "main_impl.o"; + fs::path widgetImplObject = ObjectPath(*widget, staged / "widget" / "Widget.cpp"); + fs::path consumerObject = ObjectPath(app, staged / "main.cpp"); if (BuildOk(app, "first pass")) { CheckAgrees(binary, "first pass"); From f9bd5333da112e38a0c531b16fb9d1a46dbd892d Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 19 Nov 2026 11:02:39 +0100 Subject: [PATCH 06/27] test(build): sources of one file name, and where their objects go SameNamedSources builds configurations whose sources share file names, on a fresh copy of its fixture outside the checkout, and runs what they link. `names` is an executable of an a/Thing.cpp and a b/Thing.cpp, the C sources a/unit.c and b/unit.c, a b/Thing.c beside the b/Thing.cpp and a Thing.cpp in a directory beside the configuration's own; its program prints what each returns, the first time and again after a header that only a/Thing.cpp includes has changed and after b/Thing.cpp and b/unit.c have. `registry` is a debug executable of an a/Self.cpp and a b/Self.cpp that register themselves when the program starts, which prints that each did so once. `things` is a static library of a/Thing.cpp, b/Thing.cpp, b/Thing.c and the two unit.c, and `things-app` a program of main.cpp and ../shared/Thing.cpp built on it, which prints what `names` does. `outside` is a static library of one C source that lies outside its configuration's directory and is listed relative to the working directory, built from a working directory with a space in its name; `llvm-ar t` lists its object. ObjectPath asks the rule for the objects of sources without building anything: in the configuration's directory and in directories of it, of one file name in two directories, a .cpp, a .c and a .cu of one name in one directory, outside the directory, and under a directory of the configuration's own that is named objects-outside and holds the whole path of the source outside. No two of them get one object. A path spelled with . and .., a relative source, and a source of a configuration whose path ends in a separator or is ./ are each given the object of the file they lead to, and a .cppm, a .h and a file without an extension are refused. CudaCompile gains a static library of its kernel.cu and a kernel.c beside it, whose archive lists kernel_source.o and kernel_cuda.o. Before the fix SameNamedSources failed at the link of `names`, with duplicate symbols, and of `things-app`, with undefined ones, and its `registry` printed that one of the two sources had registered twice and the other not at all. `outside` built before the fix as well, its object lying in the build directory then: it is there for the path the fix gives that object. --- project.cpp | 2 + tests/CudaCompile/fixture/kernel.c | 5 + tests/CudaCompile/main.cpp | 32 ++- tests/ObjectPath/main.cpp | 114 ++++++++++ .../fixture/names/a/Thing.cpp | 6 + .../fixture/names/a/limit-grown.h.in | 4 + .../SameNamedSources/fixture/names/a/limit.h | 4 + tests/SameNamedSources/fixture/names/a/unit.c | 4 + .../fixture/names/b/Thing-grown.cpp.in | 4 + .../SameNamedSources/fixture/names/b/Thing.c | 4 + .../fixture/names/b/Thing.cpp | 4 + .../fixture/names/b/unit-grown.c.in | 4 + tests/SameNamedSources/fixture/names/b/unit.c | 4 + tests/SameNamedSources/fixture/names/main.cpp | 18 ++ .../fixture/registry/a/Self.cpp | 10 + .../fixture/registry/b/Self.cpp | 10 + .../fixture/registry/main.cpp | 19 ++ .../SameNamedSources/fixture/shared/Thing.cpp | 4 + tests/SameNamedSources/main.cpp | 208 ++++++++++++++++++ 19 files changed, 456 insertions(+), 4 deletions(-) create mode 100644 tests/CudaCompile/fixture/kernel.c create mode 100644 tests/ObjectPath/main.cpp create mode 100644 tests/SameNamedSources/fixture/names/a/Thing.cpp create mode 100644 tests/SameNamedSources/fixture/names/a/limit-grown.h.in create mode 100644 tests/SameNamedSources/fixture/names/a/limit.h create mode 100644 tests/SameNamedSources/fixture/names/a/unit.c create mode 100644 tests/SameNamedSources/fixture/names/b/Thing-grown.cpp.in create mode 100644 tests/SameNamedSources/fixture/names/b/Thing.c create mode 100644 tests/SameNamedSources/fixture/names/b/Thing.cpp create mode 100644 tests/SameNamedSources/fixture/names/b/unit-grown.c.in create mode 100644 tests/SameNamedSources/fixture/names/b/unit.c create mode 100644 tests/SameNamedSources/fixture/names/main.cpp create mode 100644 tests/SameNamedSources/fixture/registry/a/Self.cpp create mode 100644 tests/SameNamedSources/fixture/registry/b/Self.cpp create mode 100644 tests/SameNamedSources/fixture/registry/main.cpp create mode 100644 tests/SameNamedSources/fixture/shared/Thing.cpp create mode 100644 tests/SameNamedSources/main.cpp diff --git a/project.cpp b/project.cpp index d412813..3292236 100644 --- a/project.cpp +++ b/project.cpp @@ -249,6 +249,8 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("StaticLib").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StaticLibSourceRemoved").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("LinkManyObjects").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("SameNamedSources").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("ObjectPath").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ModuleInterface").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("DependencyLink").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("SharedLibraryRuns").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/CudaCompile/fixture/kernel.c b/tests/CudaCompile/fixture/kernel.c new file mode 100644 index 0000000..60210d0 --- /dev/null +++ b/tests/CudaCompile/fixture/kernel.c @@ -0,0 +1,5 @@ +/* SPDX-License-Identifier: LGPL-3.0-only + SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */ + +/* A C source of kernel.cu's name, in its directory. */ +int KernelInC(void) { return 1; } diff --git a/tests/CudaCompile/main.cpp b/tests/CudaCompile/main.cpp index 05531f9..9f1dee9 100644 --- a/tests/CudaCompile/main.cpp +++ b/tests/CudaCompile/main.cpp @@ -28,11 +28,14 @@ using namespace Crafter; // 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 +// clang++ adds -lm to every C++ link. Another 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. +// the static archive. A last one is a static library of the .cu and a C source +// of its name beside it: the archive has to hold an object of each, where the +// two used to be compiled into one (issue #50). 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; @@ -259,6 +262,27 @@ int main() { 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)); } + { + // A C source of the .cu's name beside it, in a static library: each + // has an object of its own, and the archive lists the two. Both used + // to be compiled into kernel_source.o, each over the other (issue + // #50). + const fs::path twins = scratch / "twins"; + fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", twins, fs::copy_options::recursive); + Configuration kernels; + kernels.path = twins; + kernels.name = "twins"; + kernels.outputName = "twins"; + kernels.type = ConfigurationType::LibraryStatic; + kernels.cFiles = { twins / "kernel" }; + kernels.cuda = { twins / "kernel" }; + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult built = Build(kernels, depResults, depMutex); + Check(built.result.empty(), std::format("a library of a kernel.c and a kernel.cu in one directory builds: {}", built.result)); + const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(kernels).string())), std::chrono::seconds(30)); + Check(members.exitCode == 0 && members.output == "kernel_source.o\nkernel_cuda.o\n", std::format("with an object of each in its archive: llvm-ar t lists '{}' (exit {})", members.output, members.exitCode)); + } fs::remove_all(scratch, ec); return Failures == 0 ? 0 : 1; diff --git a/tests/ObjectPath/main.cpp b/tests/ObjectPath/main.cpp new file mode 100644 index 0000000..5fa7942 --- /dev/null +++ b/tests/ObjectPath/main.cpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// ObjectPath names the object of a source from where the source lies, so +// that two sources have one object only when their paths, with . and .. +// taken out of them, are one: by its path from the configuration's +// directory under BuildDir()/objects, by its whole path under +// BuildDir()/objects-outside when it lies outside that directory, and with +// an ending of its own for a .cpp, a .c and a .cu. Named from the file name +// alone, a/Thing.cpp and b/Thing.cpp shared an object (issue #50), and so +// did a Thing.c and a Thing.cu in one directory. +// +// Nothing is built here: the rule is asked for the object of sources that +// need not exist, which is how the CUDA ending is checked on a machine +// without nvcc, and the tree of outside sources against a directory of the +// configuration's own that is named like it. SameNamedSources builds +// configurations with such sources. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + Configuration Named(const fs::path& path) { + Configuration cfg; + cfg.path = path; + cfg.name = "paths"; + cfg.outputName = "paths"; + cfg.target = HostTarget(); + return cfg; + } +} + +int main() { + // Never made: the rule reads no file. + const fs::path root = fs::temp_directory_path() / "crafter-build-object-path"; + const Configuration cfg = Named(root / "project"); + const fs::path inside = cfg.BuildDir() / "objects"; + const fs::path outside = cfg.BuildDir() / "objects-outside"; + + // Every source asked about below with the object it was given, to see + // at the end that no two of them were given one. + std::vector> given; + const auto expect = [&](const fs::path& source, const fs::path& object, std::string_view what) { + const fs::path got = ObjectPath(cfg, source); + Check(got == object, std::format("{}: {} has the object {}, expected {}", what, source.string(), got.string(), object.string())); + given.emplace_back(source, got); + }; + + expect(cfg.path / "main.cpp", inside / "main_impl.o", "a source in the configuration's directory itself"); + expect(cfg.path / "a" / "Thing.cpp", inside / "a" / "Thing_impl.o", "a source in a directory of it"); + expect(cfg.path / "b" / "Thing.cpp", inside / "b" / "Thing_impl.o", "a source of the same file name in another directory"); + expect(cfg.path / "a" / "Thing.c", inside / "a" / "Thing_source.o", "a C source beside a C++ one of its name"); + expect(cfg.path / "a" / "Thing.cu", inside / "a" / "Thing_cuda.o", "a CUDA source beside a C one of its name"); + expect(cfg.path / "implementations" / "Crafter.Build-Clang.cpp", inside / "implementations" / "Crafter.Build-Clang_impl.o", "a file name with a dot in it"); + + // Outside the configuration's directory: by the whole path, in a tree + // of its own. + const fs::path shared = root / "shared" / "Thing.cpp"; + expect(shared, outside / (root / "shared" / "Thing_impl.o").relative_path(), "a source beside the configuration's directory"); + expect(root / "project-more" / "Thing.cpp", outside / (root / "project-more" / "Thing_impl.o").relative_path(), "a source in a directory whose name begins with the configuration's"); + // A directory of the configuration's own named like that tree, with + // the whole path of the outside source in it: an object of the first + // tree all the same. + const fs::path mimic = cfg.path / "objects-outside" / shared.relative_path(); + expect(mimic, inside / "objects-outside" / (root / "shared" / "Thing_impl.o").relative_path(), "a source under a directory of the configuration's named objects-outside"); + + for (std::size_t i = 0; i < given.size(); ++i) { + for (std::size_t j = i + 1; j < given.size(); ++j) { + Check(given[i].second != given[j].second, std::format("{} and {} have one object, {}", given[i].first.string(), given[j].first.string(), given[i].second.string())); + } + } + + // One source however its path is spelled. + Check(ObjectPath(cfg, cfg.path / "b" / ".." / "a" / "." / "Thing.cpp") == inside / "a" / "Thing_impl.o", "a path with . and .. in it names the source it leads to"); + Check(ObjectPath(cfg, cfg.path / ".." / "shared" / "Thing.cpp") == ObjectPath(cfg, shared), "a path that leaves the configuration's directory through .. names the source outside it"); + Check(ObjectPath(cfg, fs::path("sources") / "Thing.c") == ObjectPath(cfg, fs::current_path() / "sources" / "Thing.c"), "a relative source is taken against the working directory"); + + // The configuration's directory however it is spelled: with a + // separator at its end, or relative as a project file's "./" is. + const Configuration trailing = Named(root / "project" / ""); + Check(ObjectPath(trailing, root / "project" / "a" / "Thing.cpp") == trailing.BuildDir() / "objects" / "a" / "Thing_impl.o", std::format("a configuration whose path ends in a separator: {}", ObjectPath(trailing, root / "project" / "a" / "Thing.cpp").string())); + const Configuration relative = Named("./"); + Check(ObjectPath(relative, fs::path("lib") / "unit.c") == relative.BuildDir() / "objects" / "lib" / "unit_source.o", std::format("a relative source of a configuration whose path is ./: {}", ObjectPath(relative, fs::path("lib") / "unit.c").string())); + Check(ObjectPath(relative, fs::current_path() / "lib" / "unit.c") == relative.BuildDir() / "objects" / "lib" / "unit_source.o", "and the same source by its whole path"); + + // An interface unit's object is not ObjectPath's to name, nor is any + // other file's. + for (const std::string_view name : {"Thing.cppm", "Thing.h", "Thing"}) { + bool refused = false; + try { + ObjectPath(cfg, cfg.path / name); + } catch (const std::invalid_argument&) { + refused = true; + } + Check(refused, std::format("{} is refused: not a .cpp, .c or .cu", name)); + } + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/SameNamedSources/fixture/names/a/Thing.cpp b/tests/SameNamedSources/fixture/names/a/Thing.cpp new file mode 100644 index 0000000..0103582 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/a/Thing.cpp @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include "limit.h" + +int A() { return LIMIT; } diff --git a/tests/SameNamedSources/fixture/names/a/limit-grown.h.in b/tests/SameNamedSources/fixture/names/a/limit-grown.h.in new file mode 100644 index 0000000..849b87f --- /dev/null +++ b/tests/SameNamedSources/fixture/names/a/limit-grown.h.in @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#define LIMIT 100 diff --git a/tests/SameNamedSources/fixture/names/a/limit.h b/tests/SameNamedSources/fixture/names/a/limit.h new file mode 100644 index 0000000..f157774 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/a/limit.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#define LIMIT 1 diff --git a/tests/SameNamedSources/fixture/names/a/unit.c b/tests/SameNamedSources/fixture/names/a/unit.c new file mode 100644 index 0000000..ba3a047 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/a/unit.c @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: LGPL-3.0-only + SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */ + +int AUnit(void) { return 4; } diff --git a/tests/SameNamedSources/fixture/names/b/Thing-grown.cpp.in b/tests/SameNamedSources/fixture/names/b/Thing-grown.cpp.in new file mode 100644 index 0000000..9446514 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/b/Thing-grown.cpp.in @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int B() { return 200; } diff --git a/tests/SameNamedSources/fixture/names/b/Thing.c b/tests/SameNamedSources/fixture/names/b/Thing.c new file mode 100644 index 0000000..7d79d5e --- /dev/null +++ b/tests/SameNamedSources/fixture/names/b/Thing.c @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: LGPL-3.0-only + SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */ + +int BThingInC(void) { return 16; } diff --git a/tests/SameNamedSources/fixture/names/b/Thing.cpp b/tests/SameNamedSources/fixture/names/b/Thing.cpp new file mode 100644 index 0000000..4da64c0 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/b/Thing.cpp @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int B() { return 2; } diff --git a/tests/SameNamedSources/fixture/names/b/unit-grown.c.in b/tests/SameNamedSources/fixture/names/b/unit-grown.c.in new file mode 100644 index 0000000..6e686bf --- /dev/null +++ b/tests/SameNamedSources/fixture/names/b/unit-grown.c.in @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: LGPL-3.0-only + SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */ + +int BUnit(void) { return 800; } diff --git a/tests/SameNamedSources/fixture/names/b/unit.c b/tests/SameNamedSources/fixture/names/b/unit.c new file mode 100644 index 0000000..5f43f40 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/b/unit.c @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: LGPL-3.0-only + SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */ + +int BUnit(void) { return 8; } diff --git a/tests/SameNamedSources/fixture/names/main.cpp b/tests/SameNamedSources/fixture/names/main.cpp new file mode 100644 index 0000000..61d8d59 --- /dev/null +++ b/tests/SameNamedSources/fixture/names/main.cpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +int A(); +int B(); +int Shared(); +extern "C" int AUnit(void); +extern "C" int BUnit(void); +extern "C" int BThingInC(void); + +// Prints what each of the other sources returns, a/Thing.cpp's first: every +// one of them has to be in the program, and as it stands now. +int main() { + std::printf("%d %d %d %d %d %d", A(), B(), AUnit(), BUnit(), BThingInC(), Shared()); + return 0; +} diff --git a/tests/SameNamedSources/fixture/registry/a/Self.cpp b/tests/SameNamedSources/fixture/registry/a/Self.cpp new file mode 100644 index 0000000..00dc0f6 --- /dev/null +++ b/tests/SameNamedSources/fixture/registry/a/Self.cpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +void Register(int source); + +// Nothing in this file is named by another: it is in the program for what it +// does when the program starts. +namespace { + const int registered = (Register(1), 0); +} diff --git a/tests/SameNamedSources/fixture/registry/b/Self.cpp b/tests/SameNamedSources/fixture/registry/b/Self.cpp new file mode 100644 index 0000000..c787ff4 --- /dev/null +++ b/tests/SameNamedSources/fixture/registry/b/Self.cpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +void Register(int source); + +// Nothing in this file is named by another: it is in the program for what it +// does when the program starts. +namespace { + const int registered = (Register(2), 0); +} diff --git a/tests/SameNamedSources/fixture/registry/main.cpp b/tests/SameNamedSources/fixture/registry/main.cpp new file mode 100644 index 0000000..e525637 --- /dev/null +++ b/tests/SameNamedSources/fixture/registry/main.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +namespace { + // How often each source has registered: [1] is a/Self.cpp's count and + // [2] is b/Self.cpp's. + int Registered[3]; +} + +// Called by a/Self.cpp with 1 and by b/Self.cpp with 2, as the program starts. +void Register(int source) { ++Registered[source]; } + +// Prints the two counts: "1 1" when each of the two is in the program once. +int main() { + std::printf("%d %d", Registered[1], Registered[2]); + return 0; +} diff --git a/tests/SameNamedSources/fixture/shared/Thing.cpp b/tests/SameNamedSources/fixture/shared/Thing.cpp new file mode 100644 index 0000000..e97a057 --- /dev/null +++ b/tests/SameNamedSources/fixture/shared/Thing.cpp @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int Shared() { return 32; } diff --git a/tests/SameNamedSources/main.cpp b/tests/SameNamedSources/main.cpp new file mode 100644 index 0000000..6a425fe --- /dev/null +++ b/tests/SameNamedSources/main.cpp @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// Two sources of one configuration may have the same file name in different +// directories: each has an object of its own. An object used to be named +// from its source's file name alone, so a/Thing.cpp and b/Thing.cpp were +// compiled into one Thing_impl.o, each over the other, and the link was +// given that object twice (issue #50). A build of sources that define what +// another file calls failed at the link, with duplicate symbols of one of +// them and no word of the other. A debug build of sources that define +// nothing another file names, and are in the program for what they do when +// it starts, succeeded: the program had one of them twice and the other not +// at all. +// +// The fixture has both. `names` is an executable of a/Thing.cpp and +// b/Thing.cpp, the C sources a/unit.c and b/unit.c, a b/Thing.c beside the +// b/Thing.cpp, and a Thing.cpp in a directory beside the configuration's +// own; its program prints what each of them returns. A header only +// a/Thing.cpp includes is then changed, and after that b/Thing.cpp and +// b/unit.c: each time the program has to print the new values of the +// sources that changed and the values the others had. `registry` is a debug +// executable of a/Self.cpp and b/Self.cpp, which register themselves when +// the program starts, and prints how often each did. `things` is a static +// library of a/Thing.cpp, b/Thing.cpp, b/Thing.c and the two unit.c, whose +// archive then holds members of one name, and `things-app` a program of +// main.cpp and ../shared/Thing.cpp built on it. +// +// The object of a source outside its configuration's directory is named by +// the source's whole path, so that path holds every directory above the +// source. `outside`, which the test makes last, is a static library of one +// such C source, listed relative to the working directory and built from a +// working directory with a space in its name: the object's path then holds +// the space, where neither the source as listed nor the build directory +// does, and has to reach the compiler and the archive as one path. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // The fixture is changed during the run, so it is a copy outside the + // checkout that is built. + fs::path StageFixture() { + const fs::path source = fs::current_path() / "tests" / "SameNamedSources" / "fixture"; + const fs::path staged = fs::temp_directory_path() / "crafter-build-same-named-sources"; + fs::remove_all(staged); + fs::copy(source, staged, fs::copy_options::recursive); + return staged; + } + + // Puts -grown.in in the place of `file`. The other + // text is a file of the fixture rather than a string here, so that the + // one under the source's name is the only one a build sees. + void Grow(const fs::path& file) { + const fs::path grown = file.parent_path() / std::format("{}-grown{}.in", file.stem().string(), file.extension().string()); + fs::copy_file(grown, file, fs::copy_options::overwrite_existing); + // copy_file gives the copy the time of what it copied, which would + // leave the changed file older than the object built from it. + fs::last_write_time(file, fs::file_time_type::clock::now()); + } + + // The C sources of `names`, without their extensions and whole: cFiles + // are read against the working directory, not against cfg.path. + std::vector CSources(const fs::path& staged) { + return { staged / "names" / "a" / "unit", staged / "names" / "b" / "unit", staged / "names" / "b" / "Thing" }; + } + + // The issue's first case, and more of the kind: every source defines + // something main.cpp calls. ../shared/Thing lies outside the + // configuration's directory. + Configuration MakeNames(const fs::path& staged) { + Configuration cfg; + cfg.path = staged / "names"; + cfg.name = "names"; + cfg.outputName = "names"; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main", "a/Thing", "b/Thing", "../shared/Thing" }; + cfg.GetInterfacesAndImplementations(ifaces, impls); + cfg.cFiles = CSources(staged); + return cfg; + } + + // The issue's second case: a debug build of sources nothing names. + Configuration MakeRegistry(const fs::path& staged) { + Configuration cfg; + cfg.path = staged / "registry"; + cfg.name = "registry"; + cfg.outputName = "registry"; + cfg.target = HostTarget(); + cfg.debug = true; + cfg.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main", "a/Self", "b/Self" }; + cfg.GetInterfacesAndImplementations(ifaces, impls); + return cfg; + } + + // a/Thing.cpp, b/Thing.cpp and the C sources of `names` as a static + // library. + std::unique_ptr MakeThings(const fs::path& staged) { + std::unique_ptr lib = std::make_unique(); + lib->path = staged / "names"; + lib->name = "things"; + lib->outputName = "things"; + lib->target = HostTarget(); + lib->type = ConfigurationType::LibraryStatic; + std::array ifaces = {}; + std::array impls = { "a/Thing", "b/Thing" }; + lib->GetInterfacesAndImplementations(ifaces, impls); + lib->cFiles = CSources(staged); + return lib; + } + + Configuration MakeThingsApp(const fs::path& staged, Configuration* things) { + Configuration cfg; + cfg.path = staged / "names"; + cfg.name = "things-app"; + cfg.outputName = "things-app"; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main", "../shared/Thing" }; + cfg.GetInterfacesAndImplementations(ifaces, impls); + cfg.dependencies = { things }; + return cfg; + } + + bool BuildOk(Configuration& cfg, std::string_view label) { + // A fresh record for each pass: one that holds a configuration's + // build already would hand it to the next pass unbuilt. + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult r = Build(cfg, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "FAIL: {} failed: {}", label, r.result); + ++Failures; + return false; + } + return true; + } + + void CheckPrints(const Configuration& cfg, std::string_view expected, std::string_view label) { + const auto r = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30)); + Check(r.exitCode == 0 && r.output == expected, std::format("{}: the program printed '{}' (exit {}), expected '{}'", label, r.output, r.exitCode, expected)); + } +} + +int main() { + const fs::path staged = StageFixture(); + + // A() B() AUnit() BUnit() BThingInC() Shared(), see the fixture's + // names/main.cpp. + Configuration names = MakeNames(staged); + if (BuildOk(names, "the build of names")) CheckPrints(names, "1 2 4 8 16 32", "names"); + + Grow(staged / "names" / "a" / "limit.h"); + if (BuildOk(names, "the build of names after a header of a/Thing.cpp changed")) CheckPrints(names, "100 2 4 8 16 32", "names after a header of a/Thing.cpp changed"); + + Grow(staged / "names" / "b" / "Thing.cpp"); + Grow(staged / "names" / "b" / "unit.c"); + if (BuildOk(names, "the build of names after b/Thing.cpp and b/unit.c changed")) CheckPrints(names, "100 200 4 800 16 32", "names after b/Thing.cpp and b/unit.c changed"); + + // How often a/Self.cpp registered, then b/Self.cpp. + Configuration registry = MakeRegistry(staged); + if (BuildOk(registry, "the debug build of registry")) CheckPrints(registry, "1 1", "registry"); + + // The sources as they are after the changes above. + const std::unique_ptr things = MakeThings(staged); + Configuration app = MakeThingsApp(staged, things.get()); + if (BuildOk(app, "the build of things-app on the static library things")) CheckPrints(app, "100 200 4 800 16 32", "things-app"); + + // Last, because it changes the working directory of the test: a + // relative cfg.path and a relative C source are read against it. + const fs::path spaced = staged / "with space"; + fs::create_directories(spaced / "app"); + fs::create_directories(spaced / "shared"); + std::ofstream(spaced / "shared" / "unit.c") << "int Outside(void) { return 64; }\n"; + fs::current_path(spaced / "app"); + Configuration outside; + outside.path = "./"; + outside.name = "outside"; + outside.outputName = "outside"; + outside.target = HostTarget(); + outside.type = ConfigurationType::LibraryStatic; + outside.cFiles = { "../shared/unit" }; + if (BuildOk(outside, "the build of outside, from a working directory with a space in its name")) { + const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(outside).string())), std::chrono::seconds(30)); + Check(members.exitCode == 0 && members.output == "unit_source.o\n", std::format("outside: llvm-ar t lists '{}' (exit {}), expected the object of ../shared/unit.c", members.output, members.exitCode)); + } + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From 9df82bc2729d49a50ba1255b371057ff6976c4c0 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 19 Nov 2026 11:02:39 +0100 Subject: [PATCH 07/27] docs: where a source's object goes, and what a link reads The README's "Writing a project.cpp" says that a .cpp, .c or .cu of a configuration is compiled into an object named from its path, under objects/ in the build directory at the source's path from cfg.path, or under objects-outside/ at its whole path for a source outside cfg.path; that two sources may therefore have the same file name in different directories, and a .c lie beside a .cpp or a .cu of its name; that the progress line of such a source's compile names it by that path; and that the link and a static library's archive step read their objects from .objects in the build directory. The contributor guide gains two rules beside the one on output paths. ObjectPath() names an object, which is not to be named from its source's file name, and a step that takes every object of a configuration reads them from a response file. And a static library's archive and the list of a step's objects are written under another name beside them and renamed into place, as anything else that a link or archive step of another crafter-build may be reading is to be: two crafter-builds can build a project loaded with GitProject at once, in the clone the cache keeps for its source. --- AGENTS.template.md | 2 ++ README.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/AGENTS.template.md b/AGENTS.template.md index b282736..3f41e6b 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -124,6 +124,8 @@ Beyond the rules: - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. - Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its `JobGroup` in `Build()`, after the jobs whose output it reads; run a step that stands by itself, as a link does, through `RunBuildCommand`, which runs on a worker of `JobPool::Process()` whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: a `JobGroup` made on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group. - 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()`. +- `ObjectPath()` names the object of a `.cpp`, `.c` or `.cu`, from where its source lies: `objects/a/Thing_impl.o` in the build directory for `a/Thing.cpp`. Do not name one from its source's file name: two sources of one name in different directories then share an object, each compiled over the other (issue #50). A step that takes every object of a configuration reads them from a response file, as the link does, and not from its command, which the system holds to a length. +- A static library's archive and the list of objects a step reads are written under another name beside them and renamed into place (`WrittenBeside` and `MoveIntoPlace` in `Crafter.Build-Clang.cpp`), not removed first or written over where they lie: a link or archive step of another crafter-build may be reading them. Two crafter-builds can build a project loaded with `GitProject` at once, in the clone the cache keeps for its source, and one then links against the library, or reads that list, while the other writes it. Write anything else such a step reads the same way. - 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/README.md b/README.md index 2cacd19..762e84c 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ extern "C" Configuration CrafterBuildProject(std::span a Run `crafter-build` in that directory, outputs land at `bin/myapp----/myapp` and intermediates at `build/myapp----/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build, in its own directory, where its shaders, `cfg.files` and assets are; a wasm32 one runs under wasmtime, or wasmer where there is no wasmtime, with no directory given to it, and one built for the browser (`EnableWasiBrowserRuntime`) is served over HTTP from that directory instead. +A `.cpp`, `.c` or `.cu` of a configuration is compiled into an object named from its path: `a/Thing.cpp` into `objects/a/Thing_impl.o` in that `build/` directory, at the source's path from `cfg.path`, and a source outside `cfg.path` into `objects-outside/` there, at its whole path. Two sources may therefore have the same file name in different directories, and a `.c` may lie beside a `.cpp` or a `.cu` of its name. The progress line of such a source's compile names it by the same path, `Compiling a/Thing.cpp`. The link, and the archive step of a static library, read their objects from a file in that directory, `.objects`, so the command is no longer for many sources than for one. + crafter-build orders a configuration's units by the `import` lines of its sources: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused before anything of it is built, with an error that names the units in the order they wait. The imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under `#if 0` counts too, and such text can make a round in a project the compiler accepts. A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. From a99647ecffd57db64459bcff1ac6e684064ff414 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 19 Nov 2026 11:02:39 +0100 Subject: [PATCH 08/27] docs(packaging): add the 6.4.1 release entry 6.4.1 gives each .cpp, .c and .cu of a configuration an object named from its path, so that two sources no longer share one for having the same file name (#50), writes a static library's archive anew, so that it does not keep the object of a source that left the project, and has the link and the archive step read their objects from a file, so that their paths no longer make the command too long to run. A patch, by the version rule: the notes have Fixes and nothing New or Breaking. The range changes what Implementation::Check and Schedule take, which interfaces/ exports, and adds ObjectPath beside ExpectedOutput, for the tests that look at an object. Check and Schedule are what Build() itself checks and compiles an implementation unit with, as Compile() was, which 6.3.0 took off the same class as "internal and not user facing" (12e8b90), and no project.cpp of this checkout or of the ones beside it calls either. --- .../flatpak/net.catcrafts.CrafterBuild.metainfo.xml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml index 33429c4..af1f4fa 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml @@ -26,6 +26,16 @@ + + +

Fixes

+
    +
  • Two sources of a configuration may have the same file name in different directories, a/Thing.cpp beside b/Thing.cpp, and a .c may lie beside a .cu of its name (#50). An object was named from its source's file name alone, so two such sources were compiled into one object, each over the other, and the link was given that object twice: it failed, or, in a debug build of sources that define nothing another file names, gave a program with one file's code twice and the other's not at all. A .cpp, .c or .cu is now compiled into an object named from its path: in the build directory under objects/, at the source's path from cfg.path, or under objects-outside/ at its whole path when it lies outside that directory, and the progress line of its compile names it by that path. An existing build directory compiles those sources once more.
  • +
  • A static library holds the objects of the sources its configuration lists and no others. Its archive was added to where it lay, which kept the object of a source that had left the project: once a source had been renamed, what was built on the library went on linking the object of the file under its old name.
  • +
  • A configuration of many sources links. The path of every object was written into the link or archive command, which the shell that runs it is given as one argument, and Linux holds one argument to 131,072 bytes on x86_64: with objects whose paths came to more, the build ended with popen() failed!. The link and the archive step now read their objects from a file in the build directory.
  • +
+
+

New

From 3c8f4ddb54bc900702036a4fbe5569b122dbf7f6 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:25:53 +0100 Subject: [PATCH 09/27] 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 --- AGENTS.template.md | 7 +- implementations/Crafter.Build-Clang.cpp | 894 ++++++++++++------ .../Crafter.Build-Implementation.cpp | 4 +- implementations/Crafter.Build-Interface.cpp | 8 +- implementations/Crafter.Build-Lint.cpp | 15 +- implementations/Crafter.Build-Test.cpp | 13 +- implementations/Crafter.Build-Toolchain.cpp | 2 + interfaces/Crafter.Build-Clang.cppm | 45 +- interfaces/Crafter.Build-Implementation.cppm | 5 +- interfaces/Crafter.Build-Interface.cppm | 32 +- interfaces/Crafter.Build-Platform.cppm | 8 +- interfaces/Crafter.Build-Test.cppm | 4 +- interfaces/Crafter.Build-Toolchain.cppm | 13 +- tests/ConcurrentDependencyReset/main.cpp | 29 +- tests/DependencyLink/main.cpp | 17 +- tests/DuplicateModule/main.cpp | 21 +- tests/ImportCycle/main.cpp | 29 +- .../fixture/lib/Widget.cppm | 6 +- tests/IncrementalHeaderChange/main.cpp | 2 +- .../fixture/lib/Widget-grown.cppm.in | 5 +- tests/IncrementalInterfaceChange/main.cpp | 94 +- tests/JobLimit/main.cpp | 17 +- tests/Lint/main.cpp | 5 +- tests/MingwSysroot/main.cpp | 5 +- tests/ModuleInterface/main.cpp | 20 +- tests/StaticLib/main.cpp | 22 +- tests/ToolchainResolve/main.cpp | 4 + tests/TransitiveInterfaceChange/main.cpp | 66 +- 28 files changed, 861 insertions(+), 531 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 3f41e6b..5f92432 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -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, 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, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. 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. +- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, clang-scan-deps, 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, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. 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 `LoadConfigurations` and `LoadProject` (compile and load `project.cpp`), the host PCM cache and `#pragma crafter dependency`. - `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`. @@ -40,7 +40,7 @@ Partitions and what they own: The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop. -Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. +Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime, and `clang-scan-deps`, which a build reads what each C++ source declares and imports with), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. ```bash ./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/ @@ -93,6 +93,7 @@ Conventions the existing tests follow: - Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"` and removes it on the next run. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. - Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. - Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. +- `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first. - A test that needs the host's flatpak goes through `RunHostFlatpak`, skips (77) with the reason `HostFlatpakUnavailable` gives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a private `FLATPAK_USER_DIR` under its fixture's `build/`, as `FlatpakInstall` does. It never runs an installed app: `flatpak run` makes `~/.var/app/` in the real home. - A test that packages a Flatpak stages the runtime: it writes a `.flatpak-info` whose `[Application]` group has a `runtime=runtime/org.freedesktop.Sdk/x86_64/26.08` line, as the parser takes only that group's, and points `CRAFTER_BUILD_FLATPAK_INFO` at it with `setenv`, first thing in `main`, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak; `FlatpakNative` stages an empty one for the native case. @@ -205,7 +206,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. - The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel ` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. - An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. -- The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then. +- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. 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 holding the command it was taken with and what clang-scan-deps wrote, with a dependency file beside it, and taken again when the command differs, when the source or a file the dependency file lists is newer, and when it cannot be read. A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build. - Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - A CMake external whose recorded configure inputs (`/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. - The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps. diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index bff76b7..3b367e3 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -23,229 +23,467 @@ using namespace Crafter; namespace { - // Map one `import X;` name onto either a module this Configuration owns or - // one exported by a Configuration reachable through its dependency DAG, - // appending the matching staleness edge. False means nothing in reach - // provides X — either it's supplied from outside the graph (`std`) or the - // dependency isn't wired up *yet*, which is why callers remember the name. - bool ResolveImportName(Configuration& cfg, const std::string& importName, std::vector& localDeps, std::vector>& externalDeps) { - for(const std::unique_ptr& interface : cfg.interfaces) { - if(interface->name == importName) { - localDeps.push_back(interface.get()); + // A JSON value: what clang-scan-deps writes of a source, and what Build() + // keeps of that. The members of an object are its `items`, each with + // its `key`. + struct Json { + enum class Kind { Null, Boolean, Number, String, Array, Object }; + Kind kind = Kind::Null; + bool boolean = false; + // A string's value, or a number as it is written. + std::string text; + std::vector items; + std::string key; + + // The member of an object named `name`; nullptr when the object has + // none, and for a value that is no object. + const Json* Member(std::string_view name) const { + if (kind != Kind::Object) return nullptr; + for (const Json& item : items) { + if (item.key == name) return &item; + } + return nullptr; + } + }; + + // Reads the one JSON value (RFC 8259) a text holds. There is no JSON + // library in the tree, and what clang-scan-deps writes is JSON. + class JsonReader { + public: + explicit JsonReader(std::string_view text) : text(text) {} + + // The value, with nothing after it but white space; nullopt for a + // text that holds anything else. + std::optional Read() { + Json value; + if (!Value(value, 0)) return std::nullopt; + SkipSpace(); + if (at != text.size()) return std::nullopt; + return value; + } + + private: + // Deeper than anything clang-scan-deps writes, and shallow enough + // that a text which is not its output cannot exhaust the stack. + static constexpr std::size_t MaxDepth = 64; + + bool Value(Json& value, std::size_t depth) { + SkipSpace(); + if (at == text.size() || depth > MaxDepth) return false; + if (text[at] == '{') return Object(value, depth); + if (text[at] == '[') return Array(value, depth); + if (text[at] == '"') { + value.kind = Json::Kind::String; + return String(value.text); + } + if (Word("true")) { + value.kind = Json::Kind::Boolean; + value.boolean = true; return true; } + if (Word("false")) { + value.kind = Json::Kind::Boolean; + return true; + } + if (Word("null")) return true; + return Number(value); + } + + bool Object(Json& value, std::size_t depth) { + value.kind = Json::Kind::Object; + ++at; + SkipSpace(); + if (Take('}')) return true; + do { + SkipSpace(); + Json member; + if (!String(member.key)) return false; + SkipSpace(); + if (!Take(':') || !Value(member, depth + 1)) return false; + value.items.push_back(std::move(member)); + SkipSpace(); + } while (Take(',')); + return Take('}'); + } + + bool Array(Json& value, std::size_t depth) { + value.kind = Json::Kind::Array; + ++at; + SkipSpace(); + if (Take(']')) return true; + do { + Json element; + if (!Value(element, depth + 1)) return false; + value.items.push_back(std::move(element)); + SkipSpace(); + } while (Take(',')); + return Take(']'); + } + + // The string that starts at the cursor, its escapes undone, into + // `out`. + bool String(std::string& out) { + if (!Take('"')) return false; + while (at < text.size()) { + const char c = text[at++]; + if (c == '"') return true; + // A control character is only ever escaped. + if (static_cast(c) < 0x20) return false; + if (c != '\\') { + out.push_back(c); + continue; + } + if (at == text.size()) return false; + switch (text[at++]) { + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case '/': out.push_back('/'); break; + case 'b': out.push_back('\b'); break; + case 'f': out.push_back('\f'); break; + case 'n': out.push_back('\n'); break; + case 'r': out.push_back('\r'); break; + case 't': out.push_back('\t'); break; + case 'u': { + std::uint32_t code = 0; + if (!Hex(code)) return false; + // A character past the first 65,536 is written as + // two escapes, a high surrogate and then a low one. + if (code >= 0xD800 && code <= 0xDBFF) { + std::uint32_t low = 0; + if (!Take('\\') || !Take('u') || !Hex(low) || low < 0xDC00 || low > 0xDFFF) return false; + code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00); + } else if (code >= 0xDC00 && code <= 0xDFFF) { + return false; + } + AppendUtf8(out, code); + break; + } + default: return false; + } + } + return false; + } + + // The four hexadecimal digits at the cursor, as the number they + // spell, into `code`. + bool Hex(std::uint32_t& code) { + if (text.size() - at < 4) return false; + for (const std::size_t end = at + 4; at < end; ++at) { + const char c = text[at]; + std::uint32_t digit = 0; + if (c >= '0' && c <= '9') { + digit = static_cast(c - '0'); + } else if (c >= 'a' && c <= 'f') { + digit = static_cast(c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + digit = static_cast(c - 'A' + 10); + } else { + return false; + } + code = code * 16 + digit; + } + return true; + } + + static void AppendUtf8(std::string& out, std::uint32_t code) { + if (code < 0x80) { + out.push_back(static_cast(code)); + } else if (code < 0x800) { + out.push_back(static_cast(0xC0 | (code >> 6))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } else if (code < 0x10000) { + out.push_back(static_cast(0xE0 | (code >> 12))); + out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } else { + out.push_back(static_cast(0xF0 | (code >> 18))); + out.push_back(static_cast(0x80 | ((code >> 12) & 0x3F))); + out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } } - std::unordered_set seen; - std::function walk = [&](Configuration* depCfg) -> bool { - if (!seen.insert(depCfg).second) return false; - for(const std::unique_ptr& depInterface : depCfg->interfaces) { - if(depInterface->name == importName) { - fs::path depPcmPath = std::format("{}.pcm", (depCfg->PcmDir() / depInterface->path.filename()).string()); - externalDeps.emplace_back(depInterface.get(), std::move(depPcmPath)); - return true; - } + // The number at the cursor, kept as it is written: no number that + // clang-scan-deps writes is read. + bool Number(Json& value) { + const std::size_t start = at; + Take('-'); + if (!Digits()) return false; + if (Take('.') && !Digits()) return false; + if (Take('e') || Take('E')) { + if (!Take('+')) Take('-'); + if (!Digits()) return false; } - for(Configuration* sub : depCfg->dependencies) { - if (walk(sub)) return true; + value.kind = Json::Kind::Number; + value.text = std::string(text.substr(start, at - start)); + return true; + } + + bool Digits() { + const std::size_t start = at; + while (at < text.size() && text[at] >= '0' && text[at] <= '9') ++at; + return at > start; + } + + bool Word(std::string_view word) { + if (!text.substr(at).starts_with(word)) return false; + at += word.size(); + return true; + } + + bool Take(char c) { + if (at == text.size() || text[at] != c) return false; + ++at; + return true; + } + + void SkipSpace() { + while (at < text.size() && (text[at] == ' ' || text[at] == '\t' || text[at] == '\n' || text[at] == '\r')) ++at; + } + + std::string_view text; + std::size_t at = 0; + }; + + // What one source declares and imports, as clang-scan-deps read it. + struct ScannedUnit { + // The unit of a module it is by its declaration: `X` for the primary + // interface of module X, `X:P` for X's partition P. Empty for a + // source that is neither, as an implementation unit of X written + // `module X;` is, which imports X instead. + std::string provides; + // The modules and partitions it imports, each by its whole name: an + // `import :P;` in a unit of X is `X:P`. + std::vector imports; + }; + + // The unit `document` describes, as clang-scan-deps describes a single + // source in its P1689 format; nullopt for a document of any other shape. + std::optional ReadP1689(const Json& document) { + const Json* rules = document.Member("rules"); + if (rules == nullptr || rules->kind != Json::Kind::Array || rules->items.size() != 1) return std::nullopt; + const Json& rule = rules->items.front(); + // The logical name of each entry of the rule's array `name`, which + // need not be there; false when it is there and is not such an + // array. + const auto names = [&rule](std::string_view name, std::vector& out) { + const Json* entries = rule.Member(name); + if (entries == nullptr) return true; + if (entries->kind != Json::Kind::Array) return false; + for (const Json& entry : entries->items) { + const Json* logical = entry.Member("logical-name"); + if (logical == nullptr || logical->kind != Json::Kind::String) return false; + out.push_back(logical->text); + } + return true; + }; + std::vector provided; + ScannedUnit unit; + if (!names("provides", provided) || provided.size() > 1 || !names("requires", unit.imports)) return std::nullopt; + if (!provided.empty()) unit.provides = std::move(provided.front()); + return unit; + } + + std::optional ReadWholeFile(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + if (!in) return std::nullopt; + std::stringstream buffer; + buffer << in.rdbuf(); + return std::move(buffer).str(); + } + + // The dependency file of the scan Build() keeps at `scan`, beside it: the + // source and every file it included, as a rule for `scan`. + fs::path ScanDepfile(const fs::path& scan) { + return fs::path(scan) += ".d"; + } + + // The scan of a source that Build() keeps at `scan`, when it holds for + // `command`: it was taken with that command, after the source and every + // file the source included were last written (NewestPrerequisite of + // its dependency file). nullopt when it does not, and when it cannot be + // read; the source is then scanned again. + std::optional CurrentScan(const fs::path& scan, std::string_view command) { + std::error_code ec; + const fs::file_time_type written = fs::last_write_time(scan, ec); + if (ec || NewestPrerequisite(ScanDepfile(scan)) >= written) return std::nullopt; + const std::optional text = ReadWholeFile(scan); + if (!text) return std::nullopt; + const std::optional kept = JsonReader(*text).Read(); + if (!kept) return std::nullopt; + const Json* scannedWith = kept->Member("command"); + const Json* p1689 = kept->Member("p1689"); + if (scannedWith == nullptr || scannedWith->kind != Json::Kind::String || scannedWith->text != command || p1689 == nullptr) return std::nullopt; + return ReadP1689(*p1689); + } + + // A unit's name split at its colon: {"X", ""} for the module X, + // {"X", "P"} for X's partition P. + std::pair SplitUnitName(std::string_view name) { + const std::size_t colon = name.find(':'); + if (colon == std::string_view::npos) return {name, {}}; + return {name.substr(0, colon), name.substr(colon + 1)}; + } + + Module* FindModule(std::span> modules, std::string_view name) { + for (const std::unique_ptr& candidate : modules) { + if (candidate->name == name) return candidate.get(); + } + return nullptr; + } + + // The configuration whose build the pass ran for the directory a + // dependency is built into, and so the one that holds the modules of + // that build (BuildResult::built): the dependency itself, or another + // configuration of its directory. + using BuiltConfiguration = std::function; + + // Adds the staleness edge of an import of the module `name` by a unit of + // a configuration whose own modules are `local` and which is built on + // `dependencies`: to the module among `local`, else to the first found + // among the modules of the dependencies and of what they are built on, + // each as `builtIn` gives it, with the BMI that one's build writes, + // unless the unit has that edge already. A module none of them has, + // `std` or one from outside the build, gets no edge. The dependencies + // have been built when this is called, and so have read their sources: + // their modules are known. + void AddImport(std::span> local, std::span dependencies, const BuiltConfiguration& builtIn, std::string_view name, std::vector& localDeps, std::vector>& externalDeps) { + if (Module* own = FindModule(local, name)) { + if (!std::ranges::contains(localDeps, own)) localDeps.push_back(own); + return; + } + std::unordered_set seen; + std::function walk = [&](const Configuration& listed) -> bool { + const Configuration& depCfg = builtIn(listed); + if (!seen.insert(&depCfg).second) return false; + if (Module* found = FindModule(depCfg.interfaces, name)) { + if (!std::ranges::contains(externalDeps, found, &std::pair::first)) { + externalDeps.emplace_back(found, std::format("{}.pcm", (depCfg.PcmDir() / found->path.filename()).string())); + } + return true; + } + for (const Configuration* sub : depCfg.dependencies) { + if (walk(*sub)) return true; } return false; }; - - for(Configuration* depCfg : cfg.dependencies) { - if (walk(depCfg)) return true; + for (const Configuration* depCfg : dependencies) { + if (walk(*depCfg)) return; } - return false; } -} -void Configuration::ResolvePendingImports() { - // Same resolution the scan used, and against both dependency kinds — a - // second GetInterfacesAndImplementations call can add interfaces that an - // earlier batch's import was looking for, so a pending name may land on a - // local module and not just an external one. - auto sweep = [this](std::vector& pending, std::vector& localDeps, std::vector>& externalDeps) { - std::erase_if(pending, [&](const std::string& name) { - return ResolveImportName(*this, name, localDeps, externalDeps); - }); + // The modules and units of a configuration as the scans of its sources + // describe them, before Build() gives them to the configuration. + struct ModuleGraph { + std::vector> interfaces; + std::vector implementations; }; - for(const std::unique_ptr& interface : interfaces) { - sweep(interface->pendingImports, interface->moduleDependencies, interface->externalModuleDependencies); - for(const std::unique_ptr& partition : interface->partitions) { - sweep(partition->pendingImports, partition->moduleDependencies, partition->externalModuleDependencies); + + // Makes the modules and units of `config` from `interfaceScans` and + // `implementationScans`, the scans of its interfaceSources and of its + // implementationSources in the order they are listed in, with its + // dependencies as `builtIn` gives them. Returns why it could not, empty + // when it could. + std::string MakeModuleGraph(const Configuration& config, std::span interfaceScans, std::span implementationScans, const BuiltConfiguration& builtIn, ModuleGraph& graph) { + // A unit is named by its source without the extension. + const auto stem = [](const fs::path& source) { + fs::path stemmed = source; + stemmed.replace_extension(); + return stemmed; + }; + // The unit each interface source is: its module, and for a + // partition the partition as well. + std::vector moduleOf(interfaceScans.size(), nullptr); + std::vector partitionOf(interfaceScans.size(), nullptr); + // The primary interfaces first, so that a partition finds its module + // in whatever order the two are listed. + for (std::size_t i = 0; i < interfaceScans.size(); ++i) { + const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); + if (moduleName.empty()) return std::format("No module declaration found in {}", config.interfaceSources[i].string()); + if (!partitionName.empty()) continue; + graph.interfaces.push_back(std::make_unique(std::string(moduleName), stem(config.interfaceSources[i]))); + moduleOf[i] = graph.interfaces.back().get(); } - } - for(Implementation& implementation : implementations) { - sweep(implementation.pendingImports, implementation.moduleDependencies, implementation.externalModuleDependencies); + for (std::size_t i = 0; i < interfaceScans.size(); ++i) { + const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); + if (partitionName.empty()) continue; + Module* owner = FindModule(graph.interfaces, moduleName); + if (owner == nullptr) return std::format("Module {} not found, referenced in {}", moduleName, config.interfaceSources[i].string()); + owner->partitions.push_back(std::make_unique(std::string(partitionName), stem(config.interfaceSources[i]))); + moduleOf[i] = owner; + partitionOf[i] = owner->partitions.back().get(); + } + + // The partition an import of `X:P` names: a partition of the module + // X among this configuration's interface sources. X is the importing + // unit's own module, since only its partitions can be imported. + // nullptr when there is none. + const auto partitionNamed = [&graph](std::string_view moduleName, std::string_view partitionName) -> ModulePartition* { + const Module* owner = FindModule(graph.interfaces, moduleName); + if (owner == nullptr) return nullptr; + for (const std::unique_ptr& partition : owner->partitions) { + if (partition->name == partitionName) return partition.get(); + } + return nullptr; + }; + + for (std::size_t i = 0; i < interfaceScans.size(); ++i) { + ModulePartition* partition = partitionOf[i]; + for (const std::string& name : interfaceScans[i].imports) { + const auto [moduleName, partitionName] = SplitUnitName(name); + if (partitionName.empty()) { + if (partition != nullptr) { + AddImport(graph.interfaces, config.dependencies, builtIn, name, partition->moduleDependencies, partition->externalModuleDependencies); + } else { + AddImport(graph.interfaces, config.dependencies, builtIn, name, moduleOf[i]->moduleDependencies, moduleOf[i]->externalModuleDependencies); + } + continue; + } + ModulePartition* imported = partitionNamed(moduleName, partitionName); + if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, config.interfaceSources[i].string()); + // A primary interface needs no edge to its own partitions: it + // is checked and built after every one of them (Module::Check, + // Module::Schedule). + if (partition != nullptr && !std::ranges::contains(partition->partitionDependencies, imported)) partition->partitionDependencies.push_back(imported); + } + } + + for (std::size_t i = 0; i < implementationScans.size(); ++i) { + const fs::path& source = config.implementationSources[i]; + Implementation& implementation = graph.implementations.emplace_back(stem(source)); + // A source that is a unit of a module by its declaration, as an + // implementation partition (`module X:P;`) is, belongs to a + // module of this configuration. + if (const std::string_view moduleName = SplitUnitName(implementationScans[i].provides).first; !moduleName.empty() && FindModule(graph.interfaces, moduleName) == nullptr) { + return std::format("Module {} not found, referenced in {}", moduleName, source.string()); + } + for (const std::string& name : implementationScans[i].imports) { + const auto [moduleName, partitionName] = SplitUnitName(name); + if (partitionName.empty()) { + AddImport(graph.interfaces, config.dependencies, builtIn, name, implementation.moduleDependencies, implementation.externalModuleDependencies); + continue; + } + ModulePartition* imported = partitionNamed(moduleName, partitionName); + if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, source.string()); + if (!std::ranges::contains(implementation.partitionDependencies, imported)) implementation.partitionDependencies.push_back(imported); + } + } + return ""; } } void Configuration::GetInterfacesAndImplementations(std::span interfaces, std::span implementations) { - auto resolveImport = [this](const std::string& importName, std::vector& localDeps, std::vector>& externalDeps, std::vector& pending) { - if (!ResolveImportName(*this, importName, localDeps, externalDeps)) { - pending.push_back(importName); - } - }; - - std::vector> tempModulePaths = std::vector>(interfaces.size()); - for(std::uint16_t i = 0; i < interfaces.size(); i++){ - // Resolve to absolute now so the stored path survives cwd changes - // (matters for GitProject deps loaded from a different working dir). - fs::path file = fs::absolute(path / interfaces[i]).lexically_normal(); - file += ".cppm"; - std::ifstream t(file); - std::stringstream buffer; - buffer << t.rdbuf(); - std::string fileContent = buffer.str(); - fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); - fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); - tempModulePaths[i] = {file, fileContent, nullptr, nullptr}; + // Absolute now, so that a path stays the same file when the working + // directory changes, as it does around the load of a GitProject. + for (const fs::path& listed : interfaces) { + fs::path source = fs::absolute(path / listed).lexically_normal(); + source += ".cppm"; + interfaceSources.push_back(std::move(source)); } - - // Primary interface units first, so the partition pass below can find their - // parent Module. They stay in tempModulePaths — a primary unit's own - // `import X;` lines are layout dependencies exactly like a partition's, and - // dropping the entry here is what left them unrecorded (issue #26). Marked - // by a null partition slot with the Module slot filled in. - for(std::tuple& file : tempModulePaths) { - std::smatch match; - if (std::regex_search(std::get<1>(file), match, std::regex(R"(export module ([a-zA-Z0-9_\.\-]+);)"))) { - fs::path pthCpy = std::get<0>(file); - pthCpy.replace_extension(""); - this->interfaces.push_back(std::make_unique(std::move(match[1].str()), std::move(pthCpy))); - std::get<3>(file) = this->interfaces.back().get(); - } - } - - for(std::uint16_t i = 0; i < tempModulePaths.size(); i++) { - std::smatch match; - if (std::get<3>(tempModulePaths[i]) != nullptr) { - continue; - } - if (std::regex_search(std::get<1>(tempModulePaths[i]), match, std::regex(R"(export module ([a-zA-Z_0-9\.\-]+):([a-zA-Z_0-9\.\-]+);)"))) { - for(const std::unique_ptr& modulee : this->interfaces) { - if(modulee->name == match[1]) { - std::string name = match[2].str(); - fs::path pthCpy = std::get<0>(tempModulePaths[i]); - pthCpy.replace_extension(""); - std::unique_ptr partition = std::make_unique(std::move(name), std::move(pthCpy)); - std::get<2>(tempModulePaths[i]) = partition.get(); - modulee->partitions.push_back(std::move(partition)); - std::get<3>(tempModulePaths[i]) = modulee.get(); - goto next; - } - } - throw std::runtime_error(std::format("Module {} not found, referenced in {}", match[1].str(), std::get<0>(tempModulePaths[i]).string())); - } else { - throw std::runtime_error(std::format("No module declaration found in {}", std::get<0>(tempModulePaths[i]).string())); - } - next:; - } - - for(std::tuple& file : tempModulePaths) { - ModulePartition* partition = std::get<2>(file); - Module* parentModule = std::get<3>(file); - const std::string& fileContent = std::get<1>(file); - - // Primary interface unit: record only its module imports. Its - // `[export] import :Part;` lines need no edge — Module::Check walks - // every partition it owns and Module::Schedule puts the primary - // interface after all of them, so partitions are covered wholesale. - if (partition == nullptr) { - std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); - std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern); - std::sregex_iterator primaryLast; - while (primaryCurrent != primaryLast) { - std::smatch match = *primaryCurrent; - resolveImport(match[1].str(), parentModule->moduleDependencies, parentModule->externalModuleDependencies, parentModule->pendingImports); - ++primaryCurrent; - } - continue; - } - - std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); - std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); - std::sregex_iterator lastMatch; - while (currentMatch != lastMatch) { - std::smatch match = *currentMatch; - for(std::unique_ptr& sibling : parentModule->partitions) { - if(sibling->name == match[1]) { - partition->partitionDependencies.push_back(sibling.get()); - goto next2; - } - } - throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", parentModule->name, match[1].str(), std::get<0>(file).string())); - next2: ++currentMatch; - } - - std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); - std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); - while (modCurrent != lastMatch) { - std::smatch match = *modCurrent; - resolveImport(match[1].str(), partition->moduleDependencies, partition->externalModuleDependencies, partition->pendingImports); - ++modCurrent; - } - } - - for(const fs::path& tempFile : implementations) { - fs::path file = fs::absolute(path / tempFile).lexically_normal(); - file += ".cpp"; - std::ifstream t(file); - std::stringstream buffer; - buffer << t.rdbuf(); - std::string fileContent = buffer.str(); - fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); - fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); - std::smatch match; - fs::path fileCopy = file; - fileCopy.replace_extension(""); - Implementation& implementation = this->implementations.emplace_back(std::move(fileCopy)); - if (std::regex_search(fileContent, match, std::regex(R"(module ([a-zA-Z0-9_\.\-]+)(:[a-zA-Z0-9_\.\-]+)?\s*;)"))) { - const bool isPartitionImpl = match[2].length() > 0; - for(const std::unique_ptr& interface : this->interfaces) { - if(interface->name == match[1]) { - if (!isPartitionImpl) { - implementation.moduleDependencies.push_back(interface.get()); - } - std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); - std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); - std::sregex_iterator lastMatch; - while (currentMatch != lastMatch) { - std::smatch match2 = *currentMatch; - for(const std::unique_ptr& partition : interface->partitions) { - if(partition->name == match2[1]) { - implementation.partitionDependencies.push_back(partition.get()); - goto next3; - } - } - throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", match[1].str(), match2[1].str(), file.string())); - next3: ++currentMatch; - } - - std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); - std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); - while (modCurrent != lastMatch) { - std::smatch match2 = *modCurrent; - if (match2[1] != match[1]) { - resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); - } - ++modCurrent; - } - goto next4; - } - } - throw std::runtime_error(std::format("Module {} not found not found, referenced in {}", match[1].str(), file.string())); - next4:; - } else { - std::regex pattern(R"(import ([a-zA-Z_\-0-9\.]+);)"); - std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), pattern); - std::sregex_iterator lastMatch; - while (currentMatch != lastMatch) { - std::smatch match2 = *currentMatch; - resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); - ++currentMatch; - } - } + for (const fs::path& listed : implementations) { + fs::path source = fs::absolute(path / listed).lexically_normal(); + source += ".cpp"; + implementationSources.push_back(std::move(source)); } } @@ -340,10 +578,12 @@ namespace { } // ObjectPath's rule for the sources of one configuration, with what it - // takes from the configuration worked out once for all of them. + // takes from the configuration worked out once for all of them, and the + // same rule for where Build() keeps the scan of each interface and + // implementation source. class SourceLayout { public: - SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside") {} + SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside"), scansInside(buildDir / "scans"), scansOutside(buildDir / "scans-outside") {} // The object of the source a configuration lists as `listed`, which // is its path without its extension, `extension`. @@ -354,14 +594,32 @@ namespace { return within.empty() ? outside / object.relative_path() : inside / within; } + // Where the scan of `source`, given with its extension, is kept: + // named as Object() names an object, under scans/ and + // scans-outside/, by the source's own name with .json after it, as + // in scans/a/Thing.cppm.json, so that a .cppm and a .cpp of one + // name have one each. + fs::path Scan(const fs::path& source) const { + fs::path scan = fs::absolute(source).lexically_normal(); + scan += ".json"; + const fs::path within = Within(scan); + return within.empty() ? scansOutside / scan.relative_path() : scansInside / within; + } + // That source as the progress line of its compile names it: by its // path from the configuration's directory, or by its whole path // when it lies outside that directory. std::string Shown(const fs::path& listed, std::string_view extension) const { fs::path source = fs::absolute(listed).lexically_normal(); source += extension; - const fs::path within = Within(source); - return within.empty() ? source.string() : within.string(); + return Shown(source); + } + + // The same for a source given with its extension. + std::string Shown(const fs::path& source) const { + const fs::path resolved = fs::absolute(source).lexically_normal(); + const fs::path within = Within(resolved); + return within.empty() ? resolved.string() : within.string(); } private: @@ -376,6 +634,8 @@ namespace { fs::path directory; fs::path inside; fs::path outside; + fs::path scansInside; + fs::path scansOutside; }; } @@ -591,8 +851,13 @@ namespace { // that it was the build they had been compiled against. The program then // linked code compiled against two layouts of the same types, and ran // (issue #41). Empty when the dependencies agree, otherwise the error, - // naming the path to each of the two builds. - std::string DuplicateModuleError(const Configuration& config) { + // naming the path to each of the two builds. Asked once Build() has read + // the sources of `config`: the modules of a configuration are what the + // build that read its sources found (Configuration::interfaces), and + // those of each dependency are known once it is built. A dependency is + // taken as `builtIn` gives it, so two configurations that the pass + // builds into one directory are one build of their modules, not two. + std::string DuplicateModuleError(const Configuration& config, const BuiltConfiguration& builtIn) { struct Owner { const Configuration* cfg; std::string chain; @@ -603,7 +868,8 @@ namespace { std::unordered_map owners; std::unordered_set visited; std::string error; - std::function walk = [&](const Configuration& c, const std::string& chain) { + std::function walk = [&](const Configuration& listed, const std::string& chain) { + const Configuration& c = &listed == &config ? config : builtIn(listed); if (!error.empty() || !visited.insert(&c).second) return; for (const std::unique_ptr& iface : c.interfaces) { const auto [it, inserted] = owners.emplace(iface->name, Owner{ &c, chain }); @@ -625,11 +891,6 @@ namespace { // unit's jobs, by following the imports, and would follow a round of // them without end. When each unit had a thread that waited for the // units it imports, such a build hung with no compiler running. - // - // The imports are the scanner's, which reads one in a string literal, in - // a comment that spans lines or under `#if 0` as it reads any other - // (issue #45): the units named are where to look for one of those as - // well, and the error says so, since the compiler sees no round there. std::string ImportCycleError(const Configuration& config) { struct Unit { std::string name; @@ -679,7 +940,7 @@ namespace { }; for (const void* unit : declared) visit(units.at(unit)); if (round.empty()) return ""; - return std::format("{}: these interface units are each built after the next, so none can be built first: {}. A unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. The imports are read from the source text without compiling it: one in a string literal, in a comment that spans lines or under #if 0 counts too.", config.name, round); + return std::format("{}: these interface units are each built after the next, so none can be built first: {}. A unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions.", config.name, round); } // What a wasm32 configuration cannot be built with now that every unit @@ -875,6 +1136,92 @@ namespace { quoted.push_back('"'); return quoted; } + + // Has `scanner`, clang-scan-deps, read `source` as `command` compiles it, + // and keeps what it found at `scan` for CurrentScan: a JSON object of the + // command and of the P1689 description the scanner wrote, with the + // dependency file of what the source included beside it. Both are + // written beside their places and moved into them (WrittenBeside), as + // another crafter-build may be reading them. Returns what went wrong, + // empty when nothing did, and then leaves what it found in `found`. + std::string ScanSource(const fs::path& scanner, std::string_view command, const fs::path& source, const fs::path& scan, ScannedUnit& found) { + std::error_code ec; + fs::create_directories(scan.parent_path()); + const fs::path description = WrittenBeside(scan); + const fs::path depfile = WrittenBeside(ScanDepfile(scan)); + // -w: what the preprocessor warns of, the compile of the source + // reports. The command's own output is named `scan`, so that the + // dependency file is the rule for the scan. + const std::string failed = RunBuildCommand(std::format("{} -format=p1689 -o {} -- {} -w {} -c -MD -MF {} -o {}", ShellQuote(scanner.string()), ShellQuote(description.string()), command, ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string()))); + const std::optional written = ReadWholeFile(description); + fs::remove(description, ec); + if (!failed.empty()) { + fs::remove(depfile, ec); + return failed; + } + const std::optional document = written ? JsonReader(*written).Read() : std::nullopt; + std::optional unit = document ? ReadP1689(*document) : std::nullopt; + if (!unit) { + fs::remove(depfile, ec); + return std::format("clang-scan-deps wrote no description of {} that crafter-build can read: {}", source.string(), written.value_or("")); + } + const fs::path kept = WrittenBeside(scan); + std::ofstream out(kept, std::ios::binary | std::ios::trunc); + out << std::format("{{\"command\": {}, \"p1689\": {}}}\n", JsonQuote(command), *written); + out.close(); + if (out.fail()) { + fs::remove(kept, ec); + fs::remove(depfile, ec); + return std::format("cannot write {}, the scan of {}", kept.string(), source.string()); + } + // The dependency file first. Should the second move fail, the scan + // of before is left beside the dependency file of now, which lists + // what the source includes now; the other way round, the scan of + // now would be left beside the dependency file of before, which may + // miss a header the source includes now, and an edit of that header + // would not have the source scanned again. + if (std::string moved = MoveIntoPlace(depfile, ScanDepfile(scan)); !moved.empty()) { + fs::remove(kept, ec); + return moved; + } + if (std::string moved = MoveIntoPlace(kept, scan); !moved.empty()) return moved; + found = std::move(*unit); + return ""; + } + + // Reads what each interface and implementation source of `config` + // declares and imports, with `command`, the command they are compiled + // with, and gives the configuration the modules and units that makes. A + // source whose scan is current (CurrentScan) is not read again; the + // others are scanned at once, each a job on the workers of the process. + // Returns why it could not, empty when it could; the configuration then + // keeps the modules and units it had. Its dependencies are taken as + // `builtIn` gives them. + std::string ReadSources(Configuration& config, std::string_view command, const SourceLayout& layout, const BuiltConfiguration& builtIn) { + std::vector sources = config.interfaceSources; + sources.insert(sources.end(), config.implementationSources.begin(), config.implementationSources.end()); + std::vector scans(sources.size()); + { + JobGroup scanning; + for (std::size_t i = 0; i < sources.size(); ++i) { + fs::path scan = layout.Scan(sources[i]); + if (std::optional current = CurrentScan(scan, command)) { + scans[i] = std::move(*current); + continue; + } + scanning.Add(std::format("Scanning {}", layout.Shown(sources[i])), [&scans, i, scanner = GetToolchain().clangScanDeps, command = std::string(command), source = sources[i], scan = std::move(scan)] { + return ScanSource(scanner, command, source, scan, scans[i]); + }); + } + if (std::string failed = scanning.Wait(); !failed.empty()) return failed; + } + const std::span scanned(scans); + ModuleGraph graph; + if (std::string error = MakeModuleGraph(config, scanned.first(config.interfaceSources.size()), scanned.subspan(config.interfaceSources.size()), builtIn, graph); !error.empty()) return error; + config.interfaces = std::move(graph.interfaces); + config.implementations = std::move(graph.implementations); + return ""; + } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { @@ -883,63 +1230,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapchecked = false; - iface->scheduled = false; - iface->precompileJob.reset(); - for (auto& part : iface->partitions) { - part->checked = false; - part->scheduled = false; - part->precompileJob.reset(); - } - } - - // Sources were scanned when they were declared, which for most callers is - // before `dependencies` exists — AddTest resolves tests//main.cpp and - // only then hands back a builder whose .Dependencies() supplies the library. - // Any `import ;` in such a TU resolved to nothing and so carried - // no staleness edge, which meant a member added to a dependency's interface - // rebuilt the library, relinked the consumer, and silently kept the - // consumer's object compiled against the *old* class layout (issue #27). - // Re-resolving here — the last point before mtimes are compared, with the - // DAG fully wired — closes that window for every caller rather than for the - // ones that remember to declare in the right order. - config.ResolvePendingImports(); - // With every import placed, and before this configuration makes a - // directory or builds a dependency. A configuration built on this one - // has started its own build by then: the imports just placed are this - // Build()'s to read, so no other configuration's can check them for it. - if (std::string cycle = ImportCycleError(config); !cycle.empty()) { - return {std::move(cycle), false, {}}; - } - - // As early as the duplicate-module check, so a refused build leaves no + // Before anything is spawned as well, so a refused build leaves no // directory behind and starts no thread. A Flatpak asked of a target that // cannot be one says so before anything the target itself would refuse: // that is the request to change. @@ -952,7 +1243,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map externalFloor) externalFloor = ext.latestArtifact; } + // What the interface and implementation sources declare and import, read + // only now: clang-scan-deps preprocesses each with the command it is + // compiled with, which is complete from here on, with the include paths + // of the dependencies and external dependencies just built, whose + // headers a source may include. Their modules, which the imports are + // looked up among, are known by now too, as each dependency's Build() + // has read its own sources. A Build() makes the modules and units of its + // own configuration alone: those of a dependency are its own Build()'s + // to make, and the builds of other configurations built on it may be + // reading them at this moment. + // + // A dependency's modules are those of the build the pass ran for its + // directory, which need not have been the dependency's own: OncePerPass + // builds a directory once, for whichever configuration of it asked + // first, and a configuration it did not build has no modules (see + // BuildResult::built). Every dependency has its result in the pass by + // now. + const BuiltConfiguration builtIn = [&depResults, &depMutex](const Configuration& dependency) -> const Configuration& { + std::shared_future built; + { + std::lock_guard lock(depMutex); + if (const auto found = depResults.find(dependency.PcmDir()); found != depResults.end()) built = found->second; + } + if (built.valid() && built.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { + // A build that threw has failed this one already, before it got + // here, and is taken as the dependency's own. + try { + if (const Configuration* ran = built.get().built) return *ran; + } catch (...) { + } + } + return dependency; + }; + if (std::string error = ReadSources(config, command, layout, builtIn); !error.empty()) { + jobs.Fail(std::move(error)); + return {jobs.Wait(), false, {}}; + } + buildResult.built = &config; + // Both before any .cppm or .cpp of the configuration is compiled, and + // only now that its modules are known. Its C and CUDA sources, whose + // compiles started beside the dependencies' builds, may have been. + if (std::string duplicate = DuplicateModuleError(config, builtIn); !duplicate.empty()) { + jobs.Fail(std::move(duplicate)); + return {jobs.Wait(), false, {}}; + } + if (std::string cycle = ImportCycleError(config); !cycle.empty()) { + jobs.Fail(std::move(cycle)); + return {jobs.Wait(), false, {}}; + } + // Check every interface before scheduling any of them. Schedule() puts a // unit after the stale units it imports and reads their needsRecompiling // for that, which a unit's own Check need not have set: a partition's diff --git a/implementations/Crafter.Build-Implementation.cpp b/implementations/Crafter.Build-Implementation.cpp index 132c0cd..84bbe18 100644 --- a/implementations/Crafter.Build-Implementation.cpp +++ b/implementations/Crafter.Build-Implementation.cpp @@ -17,8 +17,8 @@ namespace Crafter { std::string objPath = object.string(); std::string cppPath = std::format("{}.cpp", path.string()); // The depfile clang wrote beside the object lists the headers this TU - // included; nothing else in the configuration knows about them, since - // the source scanner only reads `import` lines. + // included when the object was compiled: inputs of the object as + // much as the source and the BMIs it imports. if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) { return true; } diff --git a/implementations/Crafter.Build-Interface.cpp b/implementations/Crafter.Build-Interface.cpp index 4a56fe0..14636dd 100644 --- a/implementations/Crafter.Build-Interface.cpp +++ b/implementations/Crafter.Build-Interface.cpp @@ -185,10 +185,10 @@ namespace Crafter { if (scheduled) return precompileJob; std::vector after; // All of the module's partitions, not the ones the primary interface - // names: the scanner records no edge for its `import :Part;` lines - // (see GetInterfacesAndImplementations). And of a module that is up - // to date as well: this is where its partitions are scheduled, and - // one of them may be without its object. + // names: Build() records no edge for its `import :Part;` lines (see + // Module::moduleDependencies). And of a module that is up to date as + // well: this is where its partitions are scheduled, and one of them + // may be without its object. for (const std::unique_ptr& partition : partitions) { if (const std::optional job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); } diff --git a/implementations/Crafter.Build-Lint.cpp b/implementations/Crafter.Build-Lint.cpp index 619fc8c..948b9e4 100644 --- a/implementations/Crafter.Build-Lint.cpp +++ b/implementations/Crafter.Build-Lint.cpp @@ -903,15 +903,10 @@ namespace { // First owner wins, matching the root-first rule dedup: a source // reachable through two configurations parses with the nearer one. auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); }; - for (const std::unique_ptr& mod : c.interfaces) { - own(fs::path(std::format("{}.cppm", mod->path.string()))); - for (const std::unique_ptr& part : mod->partitions) { - own(fs::path(std::format("{}.cppm", part->path.string()))); - } - } - for (const Implementation& impl : c.implementations) { - own(fs::path(std::format("{}.cpp", impl.path.string()))); - } + // The sources as they are listed: which module each one is a unit + // of, only a build reads. + for (const fs::path& source : c.interfaceSources) own(source); + for (const fs::path& source : c.implementationSources) own(source); // cFiles/cuda resolve against cwd at build time (see Build's compile // loops); mirror that here. for (const fs::path& cf : c.cFiles) { @@ -1206,7 +1201,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would. for (const auto& [file, owner] : files) { std::ifstream in(file, std::ios::binary); - if (!in) continue; // config parse already read it; a vanished file fails the build first + if (!in) continue; // a listed file that is not there is the build's to report std::stringstream buffer; buffer << in.rdbuf(); LintContext ctx; diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index 484300a..ab75ead 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -444,18 +444,7 @@ TestBuilder& TestBuilder::Define(std::string n, std::string v) { TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; } TestBuilder& TestBuilder::Args(std::vector a) { Ref().args = std::move(a); return *this; } TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; } -TestBuilder& TestBuilder::Dependencies(std::vector d) { - Ref().config.dependencies = std::move(d); - // AddTest already scanned tests//main.cpp, at which point this test - // had no dependencies, so every `import ;` in it came back - // unresolved. Place them now that the libraries are known — without this - // the test's object carries no staleness edge to the interfaces it consumes - // and survives a layout change to them (issue #27). Build() re-runs the - // same sweep as a backstop; doing it here keeps the Configuration coherent - // for anyone inspecting it before the build. - Ref().config.ResolvePendingImports(); - return *this; -} +TestBuilder& TestBuilder::Dependencies(std::vector d) { Ref().config.dependencies = std::move(d); return *this; } TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; } diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index 5714b3f..0edbd84 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -207,11 +207,13 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { 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"; } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index d33e52a..f73973b 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -69,6 +69,15 @@ export namespace Crafter { // path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from // these directories into files/lib. std::set runPaths; + // The configuration this is the build of: the one whose Build() ran. + // A build pass builds a directory once, so of two configurations + // that would be built into one, as the same project loaded along two + // paths with its args in two orders is, only one is built, and only + // that one has the modules the build read in the sources + // (Configuration::interfaces). What is built on the other finds them + // through this. Null where Build() stopped before it read the + // sources. + const struct Configuration* built = nullptr; }; struct Define { @@ -509,6 +518,26 @@ export namespace Crafter { // sandbox permissions any configuration may declare for the // executables built on it. FlatpakApp flatpak; + // The module interface units (.cppm) and the implementation units + // (.cpp) of the configuration, as GetInterfacesAndImplementations + // lists them: absolute, with their extensions. + std::vector interfaceSources; + std::vector implementationSources; + // What those sources are, as Build() found them the last time it read + // all of them without an error: each module whose primary interface + // unit is among interfaceSources, with its partitions, and a unit for + // each of implementationSources, with what each of them imports. + // Build() takes what a source declares and imports from + // clang-scan-deps, which preprocesses the source with the command it + // is compiled with, so it reads them as the compiler does: one in a + // string literal, in a comment or in a branch that #if leaves out is + // not there. It reads them once the configuration's dependencies and + // external dependencies are built, since the command takes their + // include paths and a source may include their headers. Empty until a + // Build() has read the sources. A pass builds a directory once, so a + // configuration whose directory it built for another keeps what it + // had, and what is built on it finds the modules of that build + // through BuildResult::built. std::vector> interfaces; std::vector implementations; std::vector cFiles; @@ -602,16 +631,14 @@ export namespace Crafter { // read, for what that one is built against (see UpdateAgentsMd). Not // part of VariantId: the notes change nothing that is compiled. DependencyNotes dependencyNotes = DependencyNotes::Transitive; + // Adds the units `interfaces` and `implementations` name to + // interfaceSources and implementationSources. Each is named without + // its extension, .cppm for an interface unit and .cpp for an + // implementation unit, and resolved against `path` and the working + // directory as they are at the call. Reads none of them: Build() + // does, with the command the configuration has by then, its defines, + // flags and dependencies set after this call included. void GetInterfacesAndImplementations(std::span interfaces, std::span implementations); - // Retry the `import X;` names GetInterfacesAndImplementations could not - // place, against the dependency DAG as it stands now. Sources are - // scanned when they're declared, but `dependencies` is often assigned - // afterwards (AddTest does exactly this), and an import that resolved to - // nothing leaves no staleness edge — so a dependency's interface could - // change and this Configuration's objects would be silently reused - // against the new layout. Build() calls this before checking mtimes; - // calling it again is harmless. - void ResolvePendingImports(); // Declare a test. Sources default to `tests//main.cpp` resolved // against this Configuration's path; target/march/mtune/sysroot/debug // and cudaArch are inherited from this Configuration so cross-arch diff --git a/interfaces/Crafter.Build-Implementation.cppm b/interfaces/Crafter.Build-Implementation.cppm index f18f0a9..a1f7785 100644 --- a/interfaces/Crafter.Build-Implementation.cppm +++ b/interfaces/Crafter.Build-Implementation.cppm @@ -11,12 +11,11 @@ namespace Crafter { export class ModulePartition; export class Implementation { public: + // What this unit imports, as in ModulePartition: for a unit of a + // module (`module X;`), the module's primary interface among them. std::vector moduleDependencies; std::vector partitionDependencies; std::vector> externalModuleDependencies; - // See ModulePartition::pendingImports — imports this TU declared that - // no reachable Configuration provided when the source was scanned. - std::vector pendingImports; fs::path path; Implementation(fs::path&& path); // Whether `object`, the object Build() keeps for this unit diff --git a/interfaces/Crafter.Build-Interface.cppm b/interfaces/Crafter.Build-Interface.cppm index dcfe960..065c9b3 100644 --- a/interfaces/Crafter.Build-Interface.cppm +++ b/interfaces/Crafter.Build-Interface.cppm @@ -10,20 +10,19 @@ namespace Crafter { export class Module; export class ModulePartition { public: + // What this unit imports, as the Build() that made it read the + // source: modules of its own configuration, partitions of its own + // module, and modules of the configurations it is built on, each of + // those with the BMI that configuration's build writes. An import of + // anything else, `std` or a module from outside the build, has no + // entry. std::vector moduleDependencies; std::vector partitionDependencies; std::vector> externalModuleDependencies; - // Names from `import X;` that matched neither a module in this - // Configuration nor one reachable through its dependencies at the time - // the source was scanned. Retried by ResolvePendingImports (see - // Crafter.Build:Clang) so a dependency wired up after - // GetInterfacesAndImplementations still produces a staleness edge. - // Names that never resolve (`std`, module-mapped externals) stay here. - std::vector pendingImports; - // The state of one Build(), which clears it before it checks: whether - // Check has run, what it found, whether Schedule has added this - // unit's jobs, and the one among them that writes its BMI, which is - // the job the units importing it come after. + // The state of the Build() that made this unit: whether Check has + // run, what it found, whether Schedule has added this unit's jobs, + // and the one among them that writes its BMI, which is the job the + // units importing it come after. bool needsRecompiling = false; bool checked = false; bool scheduled = false; @@ -58,13 +57,14 @@ namespace Crafter { public: // A primary module interface unit imports things too — `import Base;` // in `export module Widget;` is as much a layout dependency as the - // same line in a partition. Recorded on the same three vectors, with - // the same meanings, so Check() can see through them and Schedule() - // can order itself behind a sibling module in the same Configuration - // (issue #26). + // same line in a partition. Recorded as a partition records the + // modules it imports, with the same meanings, so Check() can see + // through them and Schedule() can order itself behind a sibling + // module in the same Configuration (issue #26). The partitions it + // imports need no entry: it is checked and built after all of its + // module's partitions. std::vector moduleDependencies; std::vector> externalModuleDependencies; - std::vector pendingImports; // As in ModulePartition. bool needsRecompiling = false; bool checked = false; diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index 24d98fb..1573d9a 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -164,10 +164,10 @@ namespace Crafter { // derives /share/crafter-build from the running executable's path. export fs::path GetCrafterBuildHome(); // Newest mtime among the prerequisites a compiler recorded in `depFile` - // (clang's `-MD -MF .d`). This is how a build step learns which - // headers its source pulled in: the module scanner only reads `import` - // lines, so an `#include`d file is invisible to it until the compiler - // reports what it actually opened. + // (clang's `-MD -MF .d`), or clang-scan-deps for the scan of + // a C++ source. This is how a build step learns which headers its + // source pulled in: only the tool that preprocessed the source knows + // which files its #includes opened. // // Returns file_time_type::max() when freshness cannot be proven — no // depfile (nothing has compiled this artifact since depfiles were emitted, diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index ff82b4f..2988b6a 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -24,8 +24,8 @@ export namespace Crafter { // interfaces. The builder only mutates compile state, deps, runtime // args, and requires; it deliberately does NOT expose Sources() to // avoid the double-`GetInterfacesAndImplementations` footgun (calling - // it twice would re-parse the same .cppm files into duplicate Module - // entries). + // it twice would list the same .cppm files twice, and the build would + // make a Module entry of each listing). struct TestBuilder { Configuration* parent; std::size_t index; diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 606de15..24cb930 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -7,11 +7,11 @@ namespace fs = std::filesystem; export namespace Crafter { // The compiler crafter-build drives and what sits next to it, resolved - // once per process by GetToolchain(). Every clang++, clang and llvm-ar - // the tool spawns, the libclang the linter dlopens, the std module - // source and the default sysroots come from here, so a toolchain - // installed anywhere other than /usr (the Flatpak carries its own under - // /app) needs no per-call-site knowledge. + // once per process by GetToolchain(). Every clang++, clang, llvm-ar and + // clang-scan-deps the tool spawns, the libclang the linter dlopens, the + // std module source and the default sysroots come from here, so a + // toolchain installed anywhere other than /usr (the Flatpak carries its + // own under /app) needs no per-call-site knowledge. struct Toolchain { // LLVM install prefix. Empty when the tools are bare names on PATH. fs::path prefix; @@ -20,6 +20,9 @@ export namespace Crafter { fs::path llvmAr; // What a packaged program's shared libraries are read with. fs::path llvmReadelf; + // What reads the module a C++ source declares and the modules it + // imports, by preprocessing it with its compile command (Build). + fs::path clangScanDeps; // Where clang-c/Index.h lives when it is not on the default include // path; empty otherwise. fs::path llvmIncludeDir; diff --git a/tests/ConcurrentDependencyReset/main.cpp b/tests/ConcurrentDependencyReset/main.cpp index 5a59330..76eba55 100644 --- a/tests/ConcurrentDependencyReset/main.cpp +++ b/tests/ConcurrentDependencyReset/main.cpp @@ -8,10 +8,12 @@ using namespace Crafter; // Regression for the concurrent dependency-reset deadlock (issue #16). // -// Build() resets each Module/ModulePartition's per-build state (`checked`, -// `scheduled` and the job that precompiles the unit) so a reused Configuration -// re-evaluates mtimes. That reset MUST stay scoped to the configuration being -// built. It used to recurse into cfg.dependencies — but dependency +// Each Module/ModulePartition holds the state of one build (`checked`, +// `scheduled` and the job that precompiles the unit). Build() used to reset +// it so a reused Configuration re-evaluates mtimes, and now makes the units +// anew from what it reads in the sources. Either way that MUST stay scoped +// to the configuration being built. The reset used to recurse into +// cfg.dependencies — but dependency // Configurations are shared across the build DAG and each is built // concurrently by its own Build() call. Every unit then had a thread of its // own and a `compiled` flag that the units importing it waited on, and a @@ -30,11 +32,11 @@ using namespace Crafter; // timing: build a static-lib dependency fully (its module ends up checked and // scheduled), then build a consumer that depends on it while the dependency is // already cached in depResults (so it is NOT rebuilt). A consumer that reset -// its dependencies would flip the dependency's module `checked` and -// `scheduled` flags back to false and, because the dependency never rebuilds, -// they would stay false. The consumer resets only its own modules, so the -// dependency's flags are left intact. We assert both are still set once the -// consumer build completes. +// its dependencies, or made their units anew, would leave the dependency's +// module with `checked` and `scheduled` false and, because the dependency +// never rebuilds, they would stay false. The consumer makes only its own +// units, so the dependency's flags are left intact. We assert both are still +// set once the consumer build completes. int main() { fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture"; @@ -58,11 +60,6 @@ int main() { dep.GetInterfacesAndImplementations(ifaces, impls); } - if (dep.interfaces.size() != 1) { - std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size()); - return 1; - } - { std::unordered_map> depResults; std::mutex depMutex; @@ -71,6 +68,10 @@ int main() { std::println(std::cerr, "dependency build failed: {}", r.result); return 1; } + if (dep.interfaces.size() != 1) { + std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size()); + return 1; + } if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) { std::println(std::cerr, "dependency module not marked checked and scheduled after its own build"); return 1; diff --git a/tests/DependencyLink/main.cpp b/tests/DependencyLink/main.cpp index d2c9461..eedc3e1 100644 --- a/tests/DependencyLink/main.cpp +++ b/tests/DependencyLink/main.cpp @@ -38,6 +38,15 @@ int main() { app.GetInterfacesAndImplementations(ifaces, impls); } + std::unordered_map> depResults; + std::mutex depMutex; + BuildResult r = Build(app, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "build failed: {}", r.result); + return 1; + } + + // What the build read in the sources. if (app.implementations.size() != 1) { std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size()); return 1; @@ -56,14 +65,6 @@ int main() { return 1; } - std::unordered_map> depResults; - std::mutex depMutex; - BuildResult r = Build(app, depResults, depMutex); - if (!r.result.empty()) { - std::println(std::cerr, "build failed: {}", r.result); - return 1; - } - fs::path libArchive = lib->BinDir() / "libcalc.a"; if (!fs::exists(libArchive)) { std::println(std::cerr, "dep archive not produced at {}", libArchive.string()); diff --git a/tests/DuplicateModule/main.cpp b/tests/DuplicateModule/main.cpp index b0bb3f2..6a05d73 100644 --- a/tests/DuplicateModule/main.cpp +++ b/tests/DuplicateModule/main.cpp @@ -8,13 +8,14 @@ using namespace Crafter; // A program can hold one module of each name, so Build() refuses a graph in // which two configurations export the same module: the same project loaded -// along two paths with two arg lists, say. It used to build both and put -// both on the consumer's module path. Clang took the first for every import -// of the module, the ones inside the other build's consumers included, and -// the program linked code compiled against two layouts of one struct: it -// built cleanly, then read garbage or crashed (issue #41). The fixture is -// P -> M and P -> A -> M. With --split, P gives M its args without --wide, -// which changes what M declares, while A passes them on whole. +// along two paths with two arg lists, say. It used to build both and compile +// the consumer with both on its module path. Clang took the first for every +// import of the module, the ones inside the other build's consumers +// included, and the program linked code compiled against two layouts of one +// struct: it built cleanly, then read garbage or crashed (issue #41). The +// fixture is P -> M and P -> A -> M. With --split, P gives M its args +// without --wide, which changes what M declares, while A passes them on +// whole. namespace { std::int32_t Failures = 0; @@ -53,7 +54,9 @@ int main() { const fs::path cwd = fs::current_path(); fs::current_path(scratch / "p"); try { - // Two lists for M: refused before anything is built. + // Two lists for M: refused before P compiles anything of its own. + // The modules of a configuration are known once it is built, so M is + // built twice, and A on one of the two, before P can tell. { std::array args = { "--wide", "--split" }; Configuration cfg = LoadProject("project.cpp", args); @@ -61,7 +64,7 @@ int main() { Check(!built.result.empty(), "a graph with two builds of one module fails to build"); Check(built.result.contains("module M is built twice for P"), std::format("the error names the module and the program (got: {})", built.result)); Check(built.result.contains("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result)); - Check(!fs::exists(scratch / "m" / "bin") && !fs::exists(scratch / "a" / "bin") && !fs::exists(scratch / "p" / "bin"), "nothing was built"); + Check(!fs::exists(ObjectPath(cfg, scratch / "p" / "main.cpp")) && !fs::exists(ExpectedOutput(cfg)), "P compiled and linked nothing"); } // One list along both paths: one M, and the build goes through. diff --git a/tests/ImportCycle/main.cpp b/tests/ImportCycle/main.cpp index 618d8e3..2eecefc 100644 --- a/tests/ImportCycle/main.cpp +++ b/tests/ImportCycle/main.cpp @@ -6,11 +6,11 @@ import Crafter.Build; namespace fs = std::filesystem; using namespace Crafter; -// Interface units that import each other are refused before their -// configuration builds anything, with an error naming them. No order builds -// them. Before the refusal such a build hung with no compiler running, each -// unit waiting for the units it imports, which is how this test failed then: -// by running into its timeout. +// Interface units that import each other are refused before any .cppm or +// .cpp of their configuration is compiled, with an error naming them. No +// order builds them. Before the refusal such a build hung with no compiler +// running, each unit waiting for the units it imports, which is how this +// test failed then: by running into its timeout. // // Three ways round: two partitions that import each other, a partition that // imports its own module, whose primary interface is built after all of its @@ -28,9 +28,9 @@ namespace { // Builds the interfaces of the fixture in `dir` as a library and returns // Build()'s error. On a copy outside the checkout, made anew each run: a - // build that gets past the refusal has made its directories before it - // fails, and in the checkout the next run would find them there and - // report them against a refusal that works. + // build that gets past the refusal can compile units before it fails, and + // in the checkout the next run would find them there and report them + // against a refusal that works. std::string BuildError(std::string_view dir, std::span interfaces) { const fs::path staged = fs::temp_directory_path() / "crafter-build-import-cycle" / dir; fs::remove_all(staged); @@ -49,9 +49,13 @@ namespace { std::unordered_map> depResults; std::mutex depMutex; const BuildResult built = Build(cfg, depResults, depMutex); - // Refused like a graph with a module built twice: before a directory - // is made for it. - Check(!fs::exists(cfg.BuildDir()) && !fs::exists(cfg.BinDir()), std::format("{}: the refused build left {} or {} behind", dir, cfg.BuildDir().string(), cfg.BinDir().string())); + // Refused once the build has read what the units import, which is + // before it compiles any of them: no unit has a BMI or an object. + for (const fs::path& interface : interfaces) { + const fs::path bmi = cfg.PcmDir() / std::format("{}.pcm", interface.string()); + const fs::path object = cfg.BuildDir() / std::format("{}.o", interface.string()); + Check(!fs::exists(bmi) && !fs::exists(object), std::format("{}: the refused build compiled {}", dir, interface.string())); + } return built.result; } } @@ -61,9 +65,6 @@ int main() { std::array interfaces = { "Ring", "Ring-First", "Ring-Second" }; const std::string error = BuildError("partitions", interfaces); Check(error.contains("Ring:First -> Ring:Second -> Ring:First"), std::format("partitions that import each other are named in the order they wait in, got: '{}'", error)); - // The scanner reads imports the compiler does not see, so the error - // has to say where a round nobody wrote can come from. - Check(error.contains("string literal") && error.contains("#if 0"), std::format("the error says which text the scanner reads as an import, got: '{}'", error)); } { std::array interfaces = { "Own", "Own-Part" }; diff --git a/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm b/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm index 3240a22..0f75562 100644 --- a/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm +++ b/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm @@ -2,9 +2,9 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; -// The whole point of the fixture: an input to this interface unit that the -// module scanner cannot see. WIDGET_SLOTS comes from a header, so the class -// layout below changes without Widget.cppm being touched. +// The whole point of the fixture: an input to this interface unit that is +// not its own source. WIDGET_SLOTS comes from a header, so the class layout +// below changes without Widget.cppm being touched. #include "widget-layout.h" export module Widget; import std; diff --git a/tests/IncrementalHeaderChange/main.cpp b/tests/IncrementalHeaderChange/main.cpp index ae946ca..97368b8 100644 --- a/tests/IncrementalHeaderChange/main.cpp +++ b/tests/IncrementalHeaderChange/main.cpp @@ -8,7 +8,7 @@ using namespace Crafter; // Editing a header must rebuild everything that #includes it. The staleness // check used to compare an artifact against its own source and its module -// imports only — and the module scanner reads `import` lines, so a header was +// imports only — and the module scanner read `import` lines, so a header was // invisible to it. A build after a header-only edit reported nothing to do and // left objects compiled against the previous contents: the same silent // mixed-layout binary as issue #27, reached through #include instead. diff --git a/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in b/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in index e1616a2..ec86e18 100644 --- a/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in +++ b/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in @@ -3,10 +3,7 @@ // Copied over lib/Widget.cppm mid-test to stand in for the interface edit from // issue #27: one extra data member, every signature and mangled name unchanged. -// Kept as a .cppm.in so the module scanner never treats it as a source of its -// own — and so the text does not have to live in a string literal inside the -// test, where `export module Widget;` would make the test itself look like an -// implementation unit of Widget. +// Kept as a .cppm.in so that no build takes it for a source of its own. export module Widget; import std; diff --git a/tests/IncrementalInterfaceChange/main.cpp b/tests/IncrementalInterfaceChange/main.cpp index 92c2d3d..98fe100 100644 --- a/tests/IncrementalInterfaceChange/main.cpp +++ b/tests/IncrementalInterfaceChange/main.cpp @@ -7,15 +7,17 @@ namespace fs = std::filesystem; using namespace Crafter; // Adding a data member to a class in a module interface must rebuild every -// object compiled against the old layout. The dangerous shape (issue #27) is a +// object compiled against the old layout. The dangerous shape (issue #27) was a // consumer whose sources were scanned *before* its `dependencies` were assigned: // its `import ;` matched nothing, so its object carried no staleness // edge to the interface, and a layout change rebuilt the library, relinked the // consumer, and produced a binary mixing both layouts with no error or warning. // -// `AddTest` is exactly that shape — it scans tests//main.cpp and only then +// `AddTest` is exactly that shape — it lists tests//main.cpp and only then // returns a builder whose .Dependencies() supplies the library — which is why // the original report saw the corruption in test executables specifically. +// A build reads the sources now, once the dependencies are built, so the order +// they were declared in no longer matters; the cases below hold it to that. namespace { std::int32_t Failures = 0; @@ -36,10 +38,7 @@ namespace { return staged; } - // Swap in the variant carrying the extra member. Comes from a file rather - // than a string literal here: the module scanner reads raw source, so an - // `export module Widget;` spelled inside this test would make the test look - // like an implementation unit of Widget. + // Swap in the variant carrying the extra member, kept beside the original. void GrowWidget(const fs::path& staged) { fs::copy_file(staged / "lib" / "Widget-grown.cppm.in", staged / "lib" / "Widget.cppm", fs::copy_options::overwrite_existing); // copy_file carries the source's mtime across, which would leave the @@ -60,9 +59,9 @@ namespace { return lib; } - // Scan first, wire the dependency up afterwards — the ordering that used to - // silently drop the staleness edge. - Configuration MakeConsumerScannedBeforeDependencies(const fs::path& staged, Configuration* lib) { + // Sources first, the dependency wired up afterwards — the ordering that + // used to silently drop the staleness edge. + Configuration MakeConsumerListedBeforeDependencies(const fs::path& staged, Configuration* lib) { Configuration app; app.path = staged; app.name = "widget-app"; @@ -94,45 +93,31 @@ namespace { int main() { { - // The scan leaves the unmatched import recorded rather than forgotten, - // and ResolvePendingImports places it once the library is reachable. + // The build places the consumer's import on the library's module, + // although the library became a dependency after the consumer's + // sources were listed. fs::path staged = StageFixture(); std::unique_ptr lib = MakeLib(staged); - Configuration app; - app.path = staged; - app.name = "widget-app"; - app.outputName = "widget-app"; - app.target = HostTarget(); - app.type = ConfigurationType::Executable; - std::array ifaces = {}; - std::array impls = { "main" }; - app.GetInterfacesAndImplementations(ifaces, impls); - - Check(app.implementations.size() == 1, "consumer has one implementation"); - if (app.implementations.size() == 1) { - const Implementation& impl = app.implementations[0]; - Check(impl.externalModuleDependencies.empty(), "no external dep resolvable before dependencies are assigned"); - Check(std::ranges::find(impl.pendingImports, "Widget") != impl.pendingImports.end(), "unresolved 'import Widget;' is recorded as pending"); - - app.dependencies = { lib.get() }; - app.ResolvePendingImports(); - - Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports adds the external module dep"); - if (impl.externalModuleDependencies.size() == 1) { - Check(impl.externalModuleDependencies[0].first->name == "Widget", "external dep is the Widget module"); - Check(impl.externalModuleDependencies[0].second == lib->PcmDir() / "Widget.pcm", "external dep points at the library's BMI"); + Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get()); + if (BuildOk(app, "consumer with the dependency wired up last")) { + Check(app.implementations.size() == 1, "consumer has one implementation"); + if (app.implementations.size() == 1) { + const Implementation& impl = app.implementations[0]; + Check(impl.externalModuleDependencies.size() == 1, "the import of the library's module is one external module dep"); + if (impl.externalModuleDependencies.size() == 1) { + Check(impl.externalModuleDependencies[0].first->name == "Widget", "external dep is the Widget module"); + Check(impl.externalModuleDependencies[0].second == lib->PcmDir() / "Widget.pcm", "external dep points at the library's BMI"); + } + } + // A second build makes the units anew: the edge is there once. + if (BuildOk(app, "consumer built again")) { + Check(app.implementations.size() == 1 && app.implementations[0].externalModuleDependencies.size() == 1, "a second build has the one edge again"); } - Check(std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "resolved import is no longer pending"); - - // Idempotent: a second sweep must not duplicate the edge (Build - // runs one unconditionally, on top of whatever callers already did). - app.ResolvePendingImports(); - Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent"); } } { - // AddTest is the reported path: it scans the test source, then hands + // AddTest is the reported path: it lists the test source, then hands // back a builder whose .Dependencies() names the library. fs::path staged = StageFixture(); fs::create_directories(staged / "tests" / "Consumer"); @@ -146,28 +131,31 @@ int main() { app.target = HostTarget(); app.type = ConfigurationType::Executable; // AddTest resolves tests//main against the cwd, which for a real - // run is the directory holding project.cpp. Stand in the staged project - // for the declaration so the fixture's test source is the one scanned. + // run is the directory holding project.cpp, and the test's "./" path + // is read against it when the test is built. Stand in the staged + // project for both, so the fixture's test source is the one listed + // and the test builds beside it. fs::path restore = fs::current_path(); fs::current_path(staged); app.AddTest("Consumer").Dependencies({ lib.get() }); - fs::current_path(restore); - Check(app.tests.size() == 1, "one test declared"); - if (app.tests.size() == 1 && app.tests[0].config.implementations.size() == 1) { - const Implementation& impl = app.tests[0].config.implementations[0]; - Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() resolves the test's import of the library module"); - Check(impl.pendingImports.empty() || std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "test's 'import Widget;' is no longer pending"); + if (app.tests.size() == 1 && BuildOk(app.tests[0].config, "test declared with AddTest")) { + Check(app.tests[0].config.implementations.size() == 1, "the test has one implementation"); + if (app.tests[0].config.implementations.size() == 1) { + const Implementation& impl = app.tests[0].config.implementations[0]; + Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() gives the test's import of the library module its edge"); + } } + fs::current_path(restore); } { - // End to end, and deliberately without calling ResolvePendingImports: - // the guarantee under test is that Build() closes the window on its own, - // for consumers that never knew they had to ask. + // End to end: the guarantee under test is that a build of a consumer + // declared in that order recompiles it, for consumers that never knew + // the order mattered. fs::path staged = StageFixture(); std::unique_ptr lib = MakeLib(staged); - Configuration app = MakeConsumerScannedBeforeDependencies(staged, lib.get()); + Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get()); fs::path binary = app.BinDir() / "widget-app"; fs::path consumerObject = ObjectPath(app, staged / "main.cpp"); diff --git a/tests/JobLimit/main.cpp b/tests/JobLimit/main.cpp index a6ce449..00dad75 100644 --- a/tests/JobLimit/main.cpp +++ b/tests/JobLimit/main.cpp @@ -54,13 +54,6 @@ namespace { std::ofstream(file, std::ios::binary | std::ios::trunc) << text; } - // One module or import declaration of a generated source. Put together - // here because the source scanner reads one spelled out in a string - // literal as a declaration of this file's own (issue #45). - std::string Declare(std::string_view keywords, std::string_view name) { - return std::format("{} {};\n", keywords, name); - } - // The C sources of one project, and as many C++ ones. constexpr std::int32_t PerKind = 32; // The units of one project: those sources, the module's primary @@ -83,10 +76,10 @@ namespace { // Limit:High imports Limit:Low, the primary interface both, the // module's implementation unit the primary interface, and main.cpp // the module. - Write(root / "Limit-Low.cppm", std::format("{}export int Low() {{ return 1; }}\n", Declare("export module", "Limit:Low"))); - Write(root / "Limit-High.cppm", std::format("{}{}export int High() {{ return Low() + 1; }}\n", Declare("export module", "Limit:High"), Declare("import", ":Low"))); - Write(root / "Limit.cppm", std::format("{}{}{}export int Top();\n", Declare("export module", "Limit"), Declare("export import", ":Low"), Declare("export import", ":High"))); - Write(root / "Limit-impl.cpp", std::format("{}int Top() {{ return High() + 1; }}\n", Declare("module", "Limit"))); + Write(root / "Limit-Low.cppm", "export module Limit:Low;\nexport int Low() { return 1; }\n"); + Write(root / "Limit-High.cppm", "export module Limit:High;\nimport :Low;\nexport int High() { return Low() + 1; }\n"); + Write(root / "Limit.cppm", "export module Limit;\nexport import :Low;\nexport import :High;\nexport int Top();\n"); + Write(root / "Limit-impl.cpp", "module Limit;\nint Top() { return High() + 1; }\n"); std::string declarations; std::string sum; @@ -101,7 +94,7 @@ namespace { declarations += std::format("extern \"C\" int c_unit_{0}(void);\nint cpp_unit_{0}();\n", i); sum += std::format(" + c_unit_{0}() + cpp_unit_{0}()", i); } - Write(root / "main.cpp", std::format("{}{}{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", Declare("import", "std"), Declare("import", "Limit"), declarations, sum)); + Write(root / "main.cpp", std::format("import std;\nimport Limit;\n{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", declarations, sum)); std::array interfaces = { "Limit", "Limit-Low", "Limit-High" }; cfg->GetInterfacesAndImplementations(interfaces, implementations); diff --git a/tests/Lint/main.cpp b/tests/Lint/main.cpp index d5cffc5..8db7f3b 100644 --- a/tests/Lint/main.cpp +++ b/tests/Lint/main.cpp @@ -697,9 +697,8 @@ int main() { // is five of this repo's own interfaces, 677 lines. Blanking the keyword is // byte-length preserving, so the lines reported here must match the file. // - // The source lives in fixture/ExportNamespace.cppm.in rather than inline: - // an `export module` spelled in this file's own text would be picked up by - // the build's module scanner as a real interface of this project. + // The source lives in fixture/ExportNamespace.cppm.in, copied into the + // scratch directory as Demo.cppm. { Scratch s("ast-module"); fs::copy_file(fs::current_path() / "tests" / "Lint" / "fixture" / "ExportNamespace.cppm.in", s.dir / "Demo.cppm", fs::copy_options::overwrite_existing); diff --git a/tests/MingwSysroot/main.cpp b/tests/MingwSysroot/main.cpp index 3964b36..0b5ebcd 100644 --- a/tests/MingwSysroot/main.cpp +++ b/tests/MingwSysroot/main.cpp @@ -83,10 +83,7 @@ int main() { Write(mingw / "include" / "_mingw.h", ""); Write(mingw / "include" / "crafter_probe_error.h", "#error stopped in a mingw-w64 header\n"); Write(mingw / "include" / "c++" / "15.1.0" / "memory", ""); - // Through std::format because the build's import scanner reads string - // literals as code: one holding "module std;" made this file a unit of a - // module std, and the test did not build. - Write(mingw / "include" / "c++" / "15.1.0" / "bits" / "std.cc", std::format("export module {};\n", "std")); + Write(mingw / "include" / "c++" / "15.1.0" / "bits" / "std.cc", "export module std;\n"); Write(mingw / "lib" / "libstdc++.modules.json", R"({"version": 1, "modules": [{"logical-name": "std", "source-path": "../include/c++/15.1.0/bits/std.cc", "is-std-library": true}]})"); { diff --git a/tests/ModuleInterface/main.cpp b/tests/ModuleInterface/main.cpp index baa6e7a..03ea3be 100644 --- a/tests/ModuleInterface/main.cpp +++ b/tests/ModuleInterface/main.cpp @@ -21,8 +21,16 @@ int main() { std::array impls = { "main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); - // Implementation should have picked up the import Greeter; through the - // interface list resolution in GetInterfacesAndImplementations. + std::unordered_map> depResults; + std::mutex depMutex; + BuildResult r = Build(cfg, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "build failed: {}", r.result); + return 1; + } + + // The build read main.cpp's import of Greeter and placed it on the + // module among the configuration's own interfaces. if (cfg.implementations.size() != 1) { std::println(std::cerr, "expected 1 implementation, got {}", cfg.implementations.size()); return 1; @@ -36,14 +44,6 @@ int main() { return 1; } - std::unordered_map> depResults; - std::mutex depMutex; - BuildResult r = Build(cfg, depResults, depMutex); - if (!r.result.empty()) { - std::println(std::cerr, "build failed: {}", r.result); - return 1; - } - fs::path bin = cfg.BinDir() / "greeter-app"; if (!fs::exists(bin)) { std::println(std::cerr, "binary not produced at {}", bin.string()); diff --git a/tests/StaticLib/main.cpp b/tests/StaticLib/main.cpp index 3e0a37b..54e7235 100644 --- a/tests/StaticLib/main.cpp +++ b/tests/StaticLib/main.cpp @@ -7,9 +7,9 @@ namespace fs = std::filesystem; using namespace Crafter; // Build a tiny module-only static library and confirm libgreet.a lands in -// BinDir(). Exercises ConfigurationType::LibraryStatic, interface module -// parsing via GetInterfacesAndImplementations, and the ar/llvm-lib archive -// step in Crafter.Build-Clang.cpp. +// BinDir(). Exercises ConfigurationType::LibraryStatic, the module a build +// reads in a source GetInterfacesAndImplementations lists, and the +// ar/llvm-lib archive step in Crafter.Build-Clang.cpp. int main() { Configuration cfg; cfg.path = fs::current_path() / "tests" / "StaticLib" / "fixture"; @@ -22,6 +22,14 @@ int main() { std::array impls = {}; cfg.GetInterfacesAndImplementations(ifaces, impls); + std::unordered_map> depResults; + std::mutex depMutex; + BuildResult r = Build(cfg, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "build failed: {}", r.result); + return 1; + } + if (cfg.interfaces.size() != 1) { std::println(std::cerr, "expected 1 interface, got {}", cfg.interfaces.size()); return 1; @@ -31,14 +39,6 @@ int main() { return 1; } - std::unordered_map> depResults; - std::mutex depMutex; - BuildResult r = Build(cfg, depResults, depMutex); - if (!r.result.empty()) { - std::println(std::cerr, "build failed: {}", r.result); - return 1; - } - fs::path archive = cfg.BinDir() / "libgreet.a"; if (!fs::exists(archive)) { std::println(std::cerr, "archive not produced at {}", archive.string()); diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index 108ee5a..60a18bf 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -436,6 +436,10 @@ int main() { prefixed.env.emplace("CRAFTER_BUILD_LLVM_DIR", full.string()); const Toolchain withPrefix = ResolveToolchain(prefixed); Check(withPrefix.llvmReadelf == full / "bin" / "llvm-readelf", "llvm-readelf comes from the prefix"); + // So does clang-scan-deps, which reads what a source declares and + // imports. + Check(ResolveToolchain({}).clangScanDeps == "clang-scan-deps", "the PATH fallback names clang-scan-deps bare"); + Check(withPrefix.clangScanDeps == full / "bin" / "clang-scan-deps", "clang-scan-deps comes from the prefix"); Check(withPrefix.LibcxxSearchFlags() == std::format(" -L{}", (full / "lib").string()), std::format("the search flags are -L alone (got '{}')", withPrefix.LibcxxSearchFlags())); } diff --git a/tests/TransitiveInterfaceChange/main.cpp b/tests/TransitiveInterfaceChange/main.cpp index 4c423a6..e326ed3 100644 --- a/tests/TransitiveInterfaceChange/main.cpp +++ b/tests/TransitiveInterfaceChange/main.cpp @@ -45,10 +45,8 @@ namespace { return staged; } - // Swap in the Base variant carrying the extra member. From a file rather - // than a string literal: the module scanner reads raw source, so a module - // declaration spelled inside this test would make the test itself look like - // an implementation unit of Base. + // Swap in the Base variant carrying the extra member, kept beside the + // original. void GrowBase(const fs::path& staged) { fs::copy_file(staged / "base" / "Base-grown.cppm.in", staged / "base" / "Base.cppm", fs::copy_options::overwrite_existing); // copy_file carries the source's mtime across, which would leave the @@ -115,36 +113,24 @@ namespace { int main() { return 0; { - // The scan records a primary interface unit's imports, and the - // pending/resolve machinery reaches them the same way it reaches a - // partition's. + // The build records a primary interface unit's imports, and places + // them on a dependency's module the same way it places a partition's. fs::path staged = StageFixture(); std::unique_ptr base = MakeBaseLib(staged); std::unique_ptr widget = MakeWidgetLib(staged); + widget->dependencies = { base.get() }; - Module* mod = FindModule(*widget, "Widget"); - Check(mod != nullptr, "the primary interface unit registered a module named Widget"); - if (mod != nullptr) { - Check(mod->partitions.empty(), "Widget has no partitions, so nothing else could carry the edge"); - Check(mod->externalModuleDependencies.empty(), "nothing resolvable before dependencies are assigned"); - Check(std::ranges::find(mod->pendingImports, "Base") != mod->pendingImports.end(), "the unresolved import of Base is remembered as pending"); - Check(std::ranges::find(mod->pendingImports, "std") != mod->pendingImports.end(), "std stays pending — it is supplied from outside the graph"); - - widget->dependencies = { base.get() }; - widget->ResolvePendingImports(); - - Check(mod->externalModuleDependencies.size() == 1, "ResolvePendingImports places the external module edge"); - if (mod->externalModuleDependencies.size() == 1) { - Check(mod->externalModuleDependencies[0].first->name == "Base", "the edge names the Base module"); - Check(mod->externalModuleDependencies[0].second == base->PcmDir() / "Base.pcm", "the edge points at the dependency's BMI"); + if (BuildOk(*widget, "widget on base")) { + Module* mod = FindModule(*widget, "Widget"); + Check(mod != nullptr, "the primary interface unit registered a module named Widget"); + if (mod != nullptr) { + Check(mod->partitions.empty(), "Widget has no partitions, so nothing else could carry the edge"); + Check(mod->externalModuleDependencies.size() == 1, "the import of Base is one external module edge; std, supplied from outside the graph, has none"); + if (mod->externalModuleDependencies.size() == 1) { + Check(mod->externalModuleDependencies[0].first->name == "Base", "the edge names the Base module"); + Check(mod->externalModuleDependencies[0].second == base->PcmDir() / "Base.pcm", "the edge points at the dependency's BMI"); + } } - Check(std::ranges::find(mod->pendingImports, "Base") == mod->pendingImports.end(), "the resolved name is no longer pending"); - Check(std::ranges::find(mod->pendingImports, "std") != mod->pendingImports.end(), "std is still pending after the sweep"); - - // Build() runs a sweep unconditionally on top of whatever callers - // already did, so a repeat must not duplicate the edge. - widget->ResolvePendingImports(); - Check(mod->externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent"); } } @@ -164,6 +150,18 @@ int main() { std::array impls = { "widget/Widget", "base/Base", "main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); + // Widget's import of its sibling is also the compile-ordering + // guarantee: Widget's precompile needs Base.pcm on disk. Repeated from + // scratch because the failure was a thread race, and one lucky pass + // proves nothing. + for (std::int32_t attempt = 0; attempt < 4; ++attempt) { + fs::remove_all(cfg.BuildDir()); + fs::remove_all(cfg.BinDir()); + if (!BuildOk(cfg, std::format("sibling pass {}", attempt))) break; + CheckAgrees(cfg.BinDir() / "sibling", std::format("sibling pass {}", attempt)); + } + + // The edge itself, as the last pass read it. Module* widgetMod = FindModule(cfg, "Widget"); Module* baseMod = FindModule(cfg, "Base"); Check(widgetMod != nullptr && baseMod != nullptr, "both sibling modules registered"); @@ -172,16 +170,6 @@ int main() { Check(widgetMod->externalModuleDependencies.empty(), "a sibling in the same Configuration is not an external edge"); Check(baseMod->moduleDependencies.empty(), "Base imports no sibling"); } - - // That edge is also the compile-ordering guarantee: Widget's precompile - // needs Base.pcm on disk. Repeated from scratch because the failure was - // a thread race, and one lucky pass proves nothing. - for (std::int32_t attempt = 0; attempt < 4; ++attempt) { - fs::remove_all(cfg.BuildDir()); - fs::remove_all(cfg.BinDir()); - if (!BuildOk(cfg, std::format("sibling pass {}", attempt))) break; - CheckAgrees(cfg.BinDir() / "sibling", std::format("sibling pass {}", attempt)); - } } { From 08a506d34bf994d3377b14dc504205848c3ba0cd Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:25:53 +0100 Subject: [PATCH 10/27] test(build): a source's declaration and imports, as its compile reads them SourceScan builds copies of six fixtures and checks what the build read in their sources, by the modules and units it gives each configuration, and runs the program where what it does depends on that: - text, three of the four inputs of #45: `import Base;` and `import Spaced ;` are imports, and an import in a comment that spans lines or under #if 0 is none. A build with nothing changed then rewrites none of the scans, and one that cannot be read is taken again. - quoted, the fourth: an implementation source whose string literal holds "export module std;" is a unit of no module, and the build succeeds. - partition: a .cppm that declares an implementation partition (`module X:Impl;`) is the partition Impl of X, and the implementation unit that imports it has its edge to it. - define: an #ifdef on a define that the test sets after listing the source decides whether the source imports a module. - switch: an #if on a header of the library the app is built on decides it. The header is edited, and the source is scanned again; then the app is built on another library, whose header of that name says the other thing, so that only the command the scan was taken with has changed. - missing: an #include of a header that is not there fails the build with a message naming the header, and nothing is compiled of the source. On the engine of the range's base, with only this test added, every case but missing fails. Each of the three inputs of the text case is read the old way, and its first build fails outright whenever Spaced.cppm, whose import of Base was missed, is compiled before Base's BMI is there; the string literal makes the listing throw "Module std not found not found", and the implementation partition the listing of the partition case, "No module declaration found"; the import under the #ifdef counts without the define, and the one under the #if after the edit and after the swap; and there is no scan to look at. The missing case passes there too, the compile reporting the header as the scan now does. --- project.cpp | 1 + tests/SourceScan/fixture/define/Extra.cppm | 8 + tests/SourceScan/fixture/define/main.cpp | 17 ++ tests/SourceScan/fixture/missing/main.cpp | 8 + .../SourceScan/fixture/partition/X-Impl.cppm | 10 + tests/SourceScan/fixture/partition/X.cpp | 9 + tests/SourceScan/fixture/partition/X.cppm | 6 + tests/SourceScan/fixture/partition/main.cpp | 8 + tests/SourceScan/fixture/quoted/Quoted.cpp | 9 + tests/SourceScan/fixture/quoted/main.cpp | 8 + .../SourceScan/fixture/switch/app/Extra.cppm | 8 + tests/SourceScan/fixture/switch/app/main.cpp | 19 ++ tests/SourceScan/fixture/switch/off/Off.cppm | 8 + tests/SourceScan/fixture/switch/off/switch.h | 5 + tests/SourceScan/fixture/switch/on/On.cppm | 8 + .../fixture/switch/on/switch-off.h.in | 6 + tests/SourceScan/fixture/switch/on/switch.h | 5 + tests/SourceScan/fixture/text/Base.cppm | 8 + tests/SourceScan/fixture/text/Commented.cppm | 11 + tests/SourceScan/fixture/text/Disabled.cppm | 11 + tests/SourceScan/fixture/text/Spaced.cppm | 10 + tests/SourceScan/fixture/text/main.cpp | 12 + tests/SourceScan/main.cpp | 288 ++++++++++++++++++ 23 files changed, 483 insertions(+) create mode 100644 tests/SourceScan/fixture/define/Extra.cppm create mode 100644 tests/SourceScan/fixture/define/main.cpp create mode 100644 tests/SourceScan/fixture/missing/main.cpp create mode 100644 tests/SourceScan/fixture/partition/X-Impl.cppm create mode 100644 tests/SourceScan/fixture/partition/X.cpp create mode 100644 tests/SourceScan/fixture/partition/X.cppm create mode 100644 tests/SourceScan/fixture/partition/main.cpp create mode 100644 tests/SourceScan/fixture/quoted/Quoted.cpp create mode 100644 tests/SourceScan/fixture/quoted/main.cpp create mode 100644 tests/SourceScan/fixture/switch/app/Extra.cppm create mode 100644 tests/SourceScan/fixture/switch/app/main.cpp create mode 100644 tests/SourceScan/fixture/switch/off/Off.cppm create mode 100644 tests/SourceScan/fixture/switch/off/switch.h create mode 100644 tests/SourceScan/fixture/switch/on/On.cppm create mode 100644 tests/SourceScan/fixture/switch/on/switch-off.h.in create mode 100644 tests/SourceScan/fixture/switch/on/switch.h create mode 100644 tests/SourceScan/fixture/text/Base.cppm create mode 100644 tests/SourceScan/fixture/text/Commented.cppm create mode 100644 tests/SourceScan/fixture/text/Disabled.cppm create mode 100644 tests/SourceScan/fixture/text/Spaced.cppm create mode 100644 tests/SourceScan/fixture/text/main.cpp create mode 100644 tests/SourceScan/main.cpp diff --git a/project.cpp b/project.cpp index 3292236..d0cb676 100644 --- a/project.cpp +++ b/project.cpp @@ -349,6 +349,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); } diff --git a/tests/SourceScan/fixture/define/Extra.cppm b/tests/SourceScan/fixture/define/Extra.cppm new file mode 100644 index 0000000..0ec35f0 --- /dev/null +++ b/tests/SourceScan/fixture/define/Extra.cppm @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Extra; + +export int ExtraValue() { + return 40; +} diff --git a/tests/SourceScan/fixture/define/main.cpp b/tests/SourceScan/fixture/define/main.cpp new file mode 100644 index 0000000..991d781 --- /dev/null +++ b/tests/SourceScan/fixture/define/main.cpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Imports Extra when the build defines CRAFTER_TEST_EXTRA, which the test +// does after it lists this source. +#ifdef CRAFTER_TEST_EXTRA +import Extra; +#endif + +// Exits with 40 when CRAFTER_TEST_EXTRA is defined, 2 when it is not. +int main() { +#ifdef CRAFTER_TEST_EXTRA + return ExtraValue(); +#else + return 2; +#endif +} diff --git a/tests/SourceScan/fixture/missing/main.cpp b/tests/SourceScan/fixture/missing/main.cpp new file mode 100644 index 0000000..879c039 --- /dev/null +++ b/tests/SourceScan/fixture/missing/main.cpp @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include "not-there.h" + +int main() { + return 0; +} diff --git a/tests/SourceScan/fixture/partition/X-Impl.cppm b/tests/SourceScan/fixture/partition/X-Impl.cppm new file mode 100644 index 0000000..d64e5b4 --- /dev/null +++ b/tests/SourceScan/fixture/partition/X-Impl.cppm @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// An implementation partition, listed as an interface unit of the +// configuration, as a partition another unit of the module imports has to be. +module X:Impl; + +int G() { + return 7; +} diff --git a/tests/SourceScan/fixture/partition/X.cpp b/tests/SourceScan/fixture/partition/X.cpp new file mode 100644 index 0000000..e2ff029 --- /dev/null +++ b/tests/SourceScan/fixture/partition/X.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +module X; +import :Impl; + +int F() { + return G(); +} diff --git a/tests/SourceScan/fixture/partition/X.cppm b/tests/SourceScan/fixture/partition/X.cppm new file mode 100644 index 0000000..96cf388 --- /dev/null +++ b/tests/SourceScan/fixture/partition/X.cppm @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module X; + +export int F(); diff --git a/tests/SourceScan/fixture/partition/main.cpp b/tests/SourceScan/fixture/partition/main.cpp new file mode 100644 index 0000000..bbd41ed --- /dev/null +++ b/tests/SourceScan/fixture/partition/main.cpp @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import X; + +int main() { + return F() == 7 ? 0 : 1; +} diff --git a/tests/SourceScan/fixture/quoted/Quoted.cpp b/tests/SourceScan/fixture/quoted/Quoted.cpp new file mode 100644 index 0000000..3307f40 --- /dev/null +++ b/tests/SourceScan/fixture/quoted/Quoted.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// No unit of any module: what reads as a module declaration below is the +// text of a string literal. +int QuotedLength() { + constexpr char text[] = "export module std;"; + return static_cast(sizeof(text)) - 1; +} diff --git a/tests/SourceScan/fixture/quoted/main.cpp b/tests/SourceScan/fixture/quoted/main.cpp new file mode 100644 index 0000000..25b8a2e --- /dev/null +++ b/tests/SourceScan/fixture/quoted/main.cpp @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int QuotedLength(); + +int main() { + return QuotedLength() == 18 ? 0 : 1; +} diff --git a/tests/SourceScan/fixture/switch/app/Extra.cppm b/tests/SourceScan/fixture/switch/app/Extra.cppm new file mode 100644 index 0000000..0ec35f0 --- /dev/null +++ b/tests/SourceScan/fixture/switch/app/Extra.cppm @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Extra; + +export int ExtraValue() { + return 40; +} diff --git a/tests/SourceScan/fixture/switch/app/main.cpp b/tests/SourceScan/fixture/switch/app/main.cpp new file mode 100644 index 0000000..9c241cb --- /dev/null +++ b/tests/SourceScan/fixture/switch/app/main.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// WITH_EXTRA comes from the switch.h of the library the app is built on: +// found through its directory, which is on the include path of what is +// built on it. +#include +#if WITH_EXTRA +import Extra; +#endif + +// Exits with 40 when WITH_EXTRA is 1, 2 when it is 0. +int main() { +#if WITH_EXTRA + return ExtraValue(); +#else + return 2; +#endif +} diff --git a/tests/SourceScan/fixture/switch/off/Off.cppm b/tests/SourceScan/fixture/switch/off/Off.cppm new file mode 100644 index 0000000..8a40660 --- /dev/null +++ b/tests/SourceScan/fixture/switch/off/Off.cppm @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Off; + +export int OffValue() { + return 0; +} diff --git a/tests/SourceScan/fixture/switch/off/switch.h b/tests/SourceScan/fixture/switch/off/switch.h new file mode 100644 index 0000000..9b30c96 --- /dev/null +++ b/tests/SourceScan/fixture/switch/off/switch.h @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#pragma once +#define WITH_EXTRA 0 diff --git a/tests/SourceScan/fixture/switch/on/On.cppm b/tests/SourceScan/fixture/switch/on/On.cppm new file mode 100644 index 0000000..07d9648 --- /dev/null +++ b/tests/SourceScan/fixture/switch/on/On.cppm @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module On; + +export int OnValue() { + return 1; +} diff --git a/tests/SourceScan/fixture/switch/on/switch-off.h.in b/tests/SourceScan/fixture/switch/on/switch-off.h.in new file mode 100644 index 0000000..3dd272e --- /dev/null +++ b/tests/SourceScan/fixture/switch/on/switch-off.h.in @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Copied over switch.h by the test, mid-run. +#pragma once +#define WITH_EXTRA 0 diff --git a/tests/SourceScan/fixture/switch/on/switch.h b/tests/SourceScan/fixture/switch/on/switch.h new file mode 100644 index 0000000..c1760ca --- /dev/null +++ b/tests/SourceScan/fixture/switch/on/switch.h @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#pragma once +#define WITH_EXTRA 1 diff --git a/tests/SourceScan/fixture/text/Base.cppm b/tests/SourceScan/fixture/text/Base.cppm new file mode 100644 index 0000000..7204265 --- /dev/null +++ b/tests/SourceScan/fixture/text/Base.cppm @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Base; + +export int BaseValue() { + return 1; +} diff --git a/tests/SourceScan/fixture/text/Commented.cppm b/tests/SourceScan/fixture/text/Commented.cppm new file mode 100644 index 0000000..fd3ca0e --- /dev/null +++ b/tests/SourceScan/fixture/text/Commented.cppm @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Commented; +/* +import Spaced; +*/ + +export int CommentedValue() { + return 3; +} diff --git a/tests/SourceScan/fixture/text/Disabled.cppm b/tests/SourceScan/fixture/text/Disabled.cppm new file mode 100644 index 0000000..42f5f96 --- /dev/null +++ b/tests/SourceScan/fixture/text/Disabled.cppm @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Disabled; +#if 0 +import Spaced; +#endif + +export int DisabledValue() { + return 4; +} diff --git a/tests/SourceScan/fixture/text/Spaced.cppm b/tests/SourceScan/fixture/text/Spaced.cppm new file mode 100644 index 0000000..3879307 --- /dev/null +++ b/tests/SourceScan/fixture/text/Spaced.cppm @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Spaced; +// Two spaces after `import`, as a formatter that lines up columns writes it. +import Base; + +export int SpacedValue() { + return BaseValue() + 1; +} diff --git a/tests/SourceScan/fixture/text/main.cpp b/tests/SourceScan/fixture/text/main.cpp new file mode 100644 index 0000000..4ff9325 --- /dev/null +++ b/tests/SourceScan/fixture/text/main.cpp @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// A space before the semicolon. +import Spaced ; +import Commented; +import Disabled; + +// Exits 0 when each module gives what it should. +int main() { + return SpacedValue() + CommentedValue() + DisabledValue() == 9 ? 0 : 1; +} diff --git a/tests/SourceScan/main.cpp b/tests/SourceScan/main.cpp new file mode 100644 index 0000000..df420b9 --- /dev/null +++ b/tests/SourceScan/main.cpp @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A build reads what a source declares and imports as the compiler reads +// it: clang-scan-deps preprocesses the source with the command it is +// compiled with. The build used to search the text with regular +// expressions after deleting the comments that fit on one line (issue #45), +// so it took a module declaration in a string literal for a real one, +// followed an import in a comment that spans lines or under `#if 0`, missed +// `import X;` and `import X ;`, and read every #if as true. A source that +// held "export module std;" in a string became a unit of a module std and +// stopped the build; an import it missed was an edge missing, so a unit +// could be compiled before the BMI it imports, or kept when that changed. +// +// Each case builds a copy of a fixture and checks what the build read, by +// the modules and units it gave the configuration, and runs the program +// where what it does depends on that: +// text an import in a comment that spans lines, under #if 0, after +// two spaces and before a space, three of the issue's four +// inputs; a build with nothing changed; a kept scan that cannot +// be read +// quoted a module declaration in a string literal, the fourth +// partition +// a .cppm that declares an implementation partition, which +// the build refused as declaring no module +// define an #ifdef on a define set after the source is listed +// switch an #if on a header of a dependency: the header edited, and the +// dependency swapped for another +// missing an #include of a header that is not there + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + const fs::path Scratch = fs::temp_directory_path() / "crafter-build-source-scan"; + + // A copy of the fixture `name`, made anew: the switch case edits it. + fs::path Stage(std::string_view name) { + const fs::path staged = Scratch / name; + fs::remove_all(staged); + fs::create_directories(Scratch); + fs::copy(fs::current_path() / "tests" / "SourceScan" / "fixture" / name, staged, fs::copy_options::recursive); + return staged; + } + + Configuration Make(const fs::path& dir, std::string_view name, ConfigurationType type, std::vector interfaces, std::vector implementations) { + Configuration cfg; + cfg.path = dir; + cfg.name = std::string(name); + cfg.outputName = std::string(name); + cfg.target = HostTarget(); + cfg.type = type; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + return cfg; + } + + // Build()'s error, in a pass of its own. + std::string BuildError(Configuration& cfg) { + std::unordered_map> depResults; + std::mutex depMutex; + return Build(cfg, depResults, depMutex).result; + } + + // The exit code of the program `cfg` built. + std::int32_t Run(const Configuration& cfg) { + const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30)); + return run.crashed || run.timedOut ? -1 : run.exitCode; + } + + const Module* Named(const Configuration& cfg, std::string_view name) { + for (const std::unique_ptr& module : cfg.interfaces) { + if (module->name == name) return module.get(); + } + return nullptr; + } + + // The names of the modules a unit's import edges lead to, local and + // external alike, in order. + template + std::vector Imports(const Unit& unit) { + std::vector names; + for (const Module* imported : unit.moduleDependencies) names.push_back(imported->name); + for (const auto& [imported, bmi] : unit.externalModuleDependencies) names.push_back(imported->name); + return names; + } + + std::string Listed(const std::vector& names) { + return names.empty() ? "nothing" : std::format("{}", names); + } + + // The implementation unit of `cfg` whose source is `source`. + const Implementation* UnitOf(const Configuration& cfg, const fs::path& source) { + fs::path stem = source; + stem.replace_extension(); + for (const Implementation& unit : cfg.implementations) { + if (unit.path == stem) return &unit; + } + return nullptr; + } + + // When the scan the build keeps of `source` was written. + std::optional ScanTime(const Configuration& cfg, const fs::path& source) { + std::error_code ec; + const fs::file_time_type written = fs::last_write_time(cfg.BuildDir() / "scans" / std::format("{}.json", source.string()), ec); + if (ec) return std::nullopt; + return written; + } + + // Copies `from` over `to` and dates it now: copy_file keeps the time of + // `from`, which would leave the edit older than what was built before. + void Replace(const fs::path& from, const fs::path& to) { + fs::copy_file(from, to, fs::copy_options::overwrite_existing); + fs::last_write_time(to, fs::file_time_type::clock::now()); + } + + void TextCase() { + const fs::path dir = Stage("text"); + Configuration cfg = Make(dir, "scan-text", ConfigurationType::Executable, { "Base", "Spaced", "Commented", "Disabled" }, { "main" }); + const std::string error = BuildError(cfg); + Check(error.empty(), std::format("text: the build succeeds: {}", error)); + if (!error.empty()) return; + Check(Run(cfg) == 0, "text: the program gets what each module gives"); + + const Module* spaced = Named(cfg, "Spaced"); + const Module* commented = Named(cfg, "Commented"); + const Module* disabled = Named(cfg, "Disabled"); + Check(spaced != nullptr && commented != nullptr && disabled != nullptr && Named(cfg, "Base") != nullptr, "text: the four interface units are four modules"); + if (spaced == nullptr || commented == nullptr || disabled == nullptr) return; + Check(Imports(*spaced) == std::vector{ "Base" }, std::format("text: `import Base;` is an import of Base, got {}", Listed(Imports(*spaced)))); + Check(Imports(*commented).empty(), std::format("text: an import in a comment that spans lines is none, got {}", Listed(Imports(*commented)))); + Check(Imports(*disabled).empty(), std::format("text: an import under #if 0 is none, got {}", Listed(Imports(*disabled)))); + const Implementation* main = UnitOf(cfg, dir / "main.cpp"); + Check(main != nullptr && Imports(*main) == std::vector{ "Spaced", "Commented", "Disabled" }, std::format("text: `import Spaced ;` is an import of Spaced, beside the two others, got {}", main == nullptr ? "no unit" : Listed(Imports(*main)))); + + // Built again with nothing changed: every scan is read as it was + // kept, and none is taken again. + const std::vector sources = { "Base.cppm", "Spaced.cppm", "Commented.cppm", "Disabled.cppm", "main.cpp" }; + std::vector> before; + for (const fs::path& source : sources) before.push_back(ScanTime(cfg, source)); + Check(std::ranges::none_of(before, [](const std::optional& t) { return !t; }), "text: every source has its scan in the build directory"); + const std::string again = BuildError(cfg); + Check(again.empty(), std::format("text: the build with nothing changed succeeds: {}", again)); + for (std::size_t i = 0; i < sources.size(); ++i) { + Check(ScanTime(cfg, sources[i]) == before[i], std::format("text: {} is not scanned again when nothing changed", sources[i].string())); + } + // The build made the modules anew, from the scans it kept. + const Module* kept = Named(cfg, "Spaced"); + Check(kept != nullptr && Imports(*kept) == std::vector{ "Base" }, "text: the kept scan gives the import of Base again"); + + // A kept scan that cannot be read is taken again. + std::ofstream(cfg.BuildDir() / "scans" / "Spaced.cppm.json", std::ios::binary | std::ios::trunc) << "not what a build writes"; + const std::string unreadable = BuildError(cfg); + Check(unreadable.empty(), std::format("text: a scan that cannot be read is taken again, and the build succeeds: {}", unreadable)); + if (const Module* rescanned = Named(cfg, "Spaced")) Check(Imports(*rescanned) == std::vector{ "Base" }, "text: the scan taken again gives the import of Base"); + } + + void QuotedCase() { + const fs::path dir = Stage("quoted"); + Configuration cfg = Make(dir, "scan-quoted", ConfigurationType::Executable, {}, { "Quoted", "main" }); + const std::string error = BuildError(cfg); + Check(error.empty(), std::format("quoted: a module declaration in a string literal is none, and the build succeeds: {}", error)); + if (!error.empty()) return; + Check(cfg.interfaces.empty(), "quoted: the configuration has no module"); + const Implementation* quoted = UnitOf(cfg, dir / "Quoted.cpp"); + Check(quoted != nullptr && Imports(*quoted).empty(), "quoted: Quoted.cpp imports nothing, a module std least of all"); + Check(Run(cfg) == 0, "quoted: the program holds the string"); + } + + void PartitionCase() { + const fs::path dir = Stage("partition"); + Configuration cfg = Make(dir, "scan-partition", ConfigurationType::Executable, { "X", "X-Impl" }, { "X", "main" }); + const std::string error = BuildError(cfg); + Check(error.empty(), std::format("partition: an implementation partition listed as an interface unit builds: {}", error)); + if (!error.empty()) return; + const Module* x = Named(cfg, "X"); + Check(x != nullptr && x->partitions.size() == 1 && x->partitions[0]->name == "Impl", "partition: it is the partition Impl of module X"); + const Implementation* unit = UnitOf(cfg, dir / "X.cpp"); + Check(unit != nullptr && unit->partitionDependencies.size() == 1 && unit->partitionDependencies[0]->name == "Impl", "partition: X.cpp, which imports :Impl, has its edge to it"); + Check(Run(cfg) == 0, "partition: the program gets G() through F()"); + } + + void DefineCase() { + const fs::path dir = Stage("define"); + for (const bool defined : { false, true }) { + Configuration cfg = Make(dir, "scan-define", ConfigurationType::Executable, { "Extra" }, { "main" }); + // After the source is listed: the build reads it with the + // command the configuration has by then. + if (defined) cfg.defines.push_back({ "CRAFTER_TEST_EXTRA", "" }); + const std::string label = defined ? "with CRAFTER_TEST_EXTRA" : "without CRAFTER_TEST_EXTRA"; + const std::string error = BuildError(cfg); + Check(error.empty(), std::format("define, {}: the build succeeds: {}", label, error)); + if (!error.empty()) continue; + const Implementation* main = UnitOf(cfg, dir / "main.cpp"); + const std::vector expected = defined ? std::vector{ "Extra" } : std::vector{}; + Check(main != nullptr && Imports(*main) == expected, std::format("define, {}: main.cpp imports {}, got {}", label, Listed(expected), main == nullptr ? "no unit" : Listed(Imports(*main)))); + Check(Run(cfg) == (defined ? 40 : 2), std::format("define, {}: the program is built as the define says", label)); + } + } + + void SwitchCase() { + const fs::path dir = Stage("switch"); + Configuration on = Make(dir / "on", "scan-on", ConfigurationType::LibraryStatic, { "On" }, {}); + Configuration off = Make(dir / "off", "scan-off", ConfigurationType::LibraryStatic, { "Off" }, {}); + Configuration app = Make(dir / "app", "scan-switch", ConfigurationType::Executable, { "Extra" }, { "main" }); + app.dependencies = { &on }; + const fs::path source = dir / "app" / "main.cpp"; + const auto imports = [&] { + const Implementation* main = UnitOf(app, source); + return main == nullptr ? std::vector{ "no unit" } : Imports(*main); + }; + + std::string error = BuildError(app); + Check(error.empty(), std::format("switch, on: the build succeeds: {}", error)); + if (!error.empty()) return; + Check(imports() == std::vector{ "Extra" }, std::format("switch, on: WITH_EXTRA 1 imports Extra, got {}", Listed(imports()))); + Check(Run(app) == 40, "switch, on: the program imports Extra"); + + // The header is edited: the scan that read it is taken again. + Replace(dir / "on" / "switch-off.h.in", dir / "on" / "switch.h"); + const std::optional scannedOn = ScanTime(app, "main.cpp"); + error = BuildError(app); + Check(error.empty(), std::format("switch, header edited: the build succeeds: {}", error)); + if (!error.empty()) return; + Check(ScanTime(app, "main.cpp") != scannedOn, "switch, header edited: main.cpp is scanned again"); + Check(imports().empty(), std::format("switch, header edited: WITH_EXTRA 0 imports nothing, got {}", Listed(imports()))); + Check(Run(app) == 2, "switch, header edited: the program is compiled again without Extra"); + + // Back to 1, then built on the other library, whose switch.h has 0. + // Nothing the scan read has changed, but the command it read them + // with has: its include path names the other library. Checked by + // what the build read alone: this is about the scan. + Replace(fs::current_path() / "tests" / "SourceScan" / "fixture" / "switch" / "on" / "switch.h", dir / "on" / "switch.h"); + error = BuildError(app); + Check(error.empty() && imports() == std::vector{ "Extra" }, std::format("switch, header back to 1: main.cpp imports Extra again, got {} ({})", Listed(imports()), error)); + app.dependencies = { &off }; + const std::optional scannedWithOn = ScanTime(app, "main.cpp"); + error = BuildError(app); + Check(error.empty(), std::format("switch, off: the build succeeds: {}", error)); + if (!error.empty()) return; + Check(ScanTime(app, "main.cpp") != scannedWithOn, "switch, off: main.cpp is scanned again for the command that changed"); + Check(imports().empty(), std::format("switch, off: the other library's WITH_EXTRA 0 imports nothing, got {}", Listed(imports()))); + } + + void MissingCase() { + const fs::path dir = Stage("missing"); + Configuration cfg = Make(dir, "scan-missing", ConfigurationType::Executable, {}, { "main" }); + const std::string error = BuildError(cfg); + Check(error.contains("not-there.h"), std::format("missing: the build fails naming the header it cannot find, got: {}", error)); + Check(!fs::exists(ObjectPath(cfg, dir / "main.cpp")), "missing: nothing is compiled of a source that cannot be read"); + } + + // Runs one case: an exception it lets out fails that case, and the + // others still run. + void RunCase(std::string_view name, const std::function& run) { + try { + run(); + } catch (const std::exception& e) { + Check(false, std::format("{}: threw {}", name, e.what())); + } + } +} + +int main() { + RunCase("text", TextCase); + RunCase("quoted", QuotedCase); + RunCase("partition", PartitionCase); + RunCase("define", DefineCase); + RunCase("switch", SwitchCase); + RunCase("missing", MissingCase); + std::error_code ec; + fs::remove_all(Scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From 15e98312030ed95494ecda8445114f68fe826395 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:25:53 +0100 Subject: [PATCH 11/27] test(build): one project loaded with its flags in two orders is built once DuplicateModule builds its project once more with --wide --reorder, with which P gives M the list that A passes on, in the other order. The loader takes the two orders for two lists and makes two configurations of M, which VariantId, taking the project's own flags sorted, builds into one directory, and a pass builds that directory once. The case checks that the two are two configurations with one directory, and then, in two passes, that the graph builds and that P's main.cpp and A's interface have their edges to the module of the configuration of M that the pass built. The first pass builds whichever asks first, and the other has no modules. The second builds the other one first and records it for the directory, as BuildAll records a configuration it builds, before it builds the graph, so that both configurations of M then have modules, the first still those it read in the first pass. On the engine of the range's base the graph is refused as "module M is built twice for P": every configuration had its modules from the listing, and the refusal told the builds apart by their configurations. On an engine that reads a dependency's modules off the configuration it is listed as, the range's fix without BuildResult::built, the first pass builds and A's interface has no edge to M, P's M being the one built and A's having no modules, and the second pass is refused as a graph with two builds of M. --- tests/DuplicateModule/fixture/p/project.cpp | 5 +- tests/DuplicateModule/main.cpp | 66 +++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/tests/DuplicateModule/fixture/p/project.cpp b/tests/DuplicateModule/fixture/p/project.cpp index 3f4a06b..c0eb440 100644 --- a/tests/DuplicateModule/fixture/p/project.cpp +++ b/tests/DuplicateModule/fixture/p/project.cpp @@ -8,13 +8,16 @@ using namespace Crafter; // Loads M itself and through A, which passes on all of its args. With // --split, the list P gives M leaves --wide out, as a filter meant for one -// sibling would, and the two paths load M with two different lists. +// sibling would, and the two paths load M with two different lists. With +// --reorder, P gives M its args in the other order: the same list, which +// the loader still takes for another. extern "C" Configuration CrafterBuildProject(std::span args) { const bool split = std::ranges::contains(args, std::string_view("--split")); std::vector mArgs; for (std::string_view arg : args) { if (!split || arg != "--wide") mArgs.emplace_back(arg); } + if (std::ranges::contains(args, std::string_view("--reorder"))) std::ranges::reverse(mArgs); Configuration* m = LocalProject({ .projectFile = "../m/project.cpp", .args = mArgs }); Configuration* a = LocalProject({ .projectFile = "../a/project.cpp" }); diff --git a/tests/DuplicateModule/main.cpp b/tests/DuplicateModule/main.cpp index 6a05d73..b755bee 100644 --- a/tests/DuplicateModule/main.cpp +++ b/tests/DuplicateModule/main.cpp @@ -67,6 +67,72 @@ int main() { Check(!fs::exists(ObjectPath(cfg, scratch / "p" / "main.cpp")) && !fs::exists(ExpectedOutput(cfg)), "P compiled and linked nothing"); } + // The same list for M along both paths, in two orders. The loader + // makes a configuration of M for each order, and VariantId, which + // takes the args sorted, gives both one directory, which a pass + // builds once, on whichever of the two asks first. That build's + // modules stand for both: P's import of M and A's have their edge to + // the module it read, and the graph is not taken for one with two + // builds of M. A second pass builds the other configuration on + // purpose, while the first still holds the modules it read: then + // both have modules, and they are still one build. + { + std::array args = { "--wide", "--reorder" }; + Configuration cfg = LoadProject("project.cpp", args); + const bool twoM = cfg.dependencies.size() == 2 && cfg.dependencies[1]->dependencies.size() == 1 && cfg.dependencies[0] != cfg.dependencies[1]->dependencies[0]; + Check(twoM, "the two orders load two configurations of M"); + if (twoM) { + Configuration& a = *cfg.dependencies[1]; + Configuration& mOfP = *cfg.dependencies[0]; + Configuration& mOfA = *a.dependencies[0]; + Check(mOfP.PcmDir() == mOfA.PcmDir(), "which are built into one directory"); + // The module M as a build of `m` read it; nullptr where no + // build of `m` has. + const auto moduleOf = [](const Configuration& m) -> const Module* { + return m.interfaces.size() == 1 ? m.interfaces[0].get() : nullptr; + }; + // The module a unit's edge to M leads to; nullptr without one. + const auto edgeToM = [](const auto& unit) -> const Module* { + for (const auto& [imported, bmi] : unit.externalModuleDependencies) { + if (imported->name == "M") return imported; + } + return nullptr; + }; + // P's main.cpp and A's interface lead to the module of `built`. + const auto checkEdges = [&](const Configuration& built, std::string_view pass) { + const Module* m = moduleOf(built); + Check(m != nullptr, std::format("{}: the configuration of M built has its module", pass)); + Check(cfg.implementations.size() == 1 && edgeToM(cfg.implementations[0]) == m, std::format("{}: P's main.cpp has its edge to that module", pass)); + Check(a.interfaces.size() == 1 && edgeToM(*a.interfaces[0]) == m, std::format("{}: A's interface has its edge to that module", pass)); + }; + + // Pass 1, with a record of its own. + BuildResult built = BuildPass(cfg); + Check(built.result.empty(), std::format("pass 1: the graph with one M in two configurations builds (got: {})", built.result)); + if (built.result.empty()) { + Configuration& first = moduleOf(mOfP) != nullptr ? mOfP : mOfA; + Configuration& other = &first == &mOfP ? mOfA : mOfP; + Check(moduleOf(other) == nullptr, "pass 1: one of the two is built, and the other has no modules"); + checkEdges(first, "pass 1"); + + // Pass 2: the other one is built first and recorded for + // the directory, as BuildAll records a configuration it + // builds, and the graph after it, which finds that build. + std::unordered_map> depResults; + std::mutex depMutex; + std::promise otherBuilt; + otherBuilt.set_value(Build(other, depResults, depMutex)); + depResults.insert_or_assign(other.PcmDir(), otherBuilt.get_future().share()); + built = Build(cfg, depResults, depMutex); + Check(built.result.empty(), std::format("pass 2: the graph builds with the other configuration of M built, and the first one holding the module it read in pass 1 (got: {})", built.result)); + if (built.result.empty()) { + Check(moduleOf(first) != nullptr, "pass 2: the first one still holds the module it read in pass 1"); + checkEdges(other, "pass 2"); + } + } + } + } + // One list along both paths: one M, and the build goes through. { std::array args = { "--wide" }; From efb8fcc8b27f0e07b21ed3ff98d7c1d70f9a55e9 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:25:53 +0100 Subject: [PATCH 12/27] docs: what a source imports is read as its compile reads it The README said that crafter-build reads the imports of a configuration's sources from their text without compiling them, so that one in a string literal, in a comment that spans lines or under #if 0 counted, and that a configuration whose interface units import each other is refused before anything of it is built. It now says that clang-scan-deps reads what a .cppm or .cpp declares and imports, with the command the source is compiled with, as the compiler reads it, once the configuration's dependencies are built; where the build keeps what it read, as it keeps objects; that such a configuration is refused once its sources are read, before any of its .cppm and .cpp is compiled; and that the scans are among the steps a build runs at most as many of at once as the machine has hardware threads. The README's sentence on a project that two paths load with different lists now names the projects the build stops for, those that export modules, since DuplicateModuleError refuses a module built twice and nothing else, and says that such a project is built once where both lists give it one build directory, as two orders of the same flags of its own can. The README and the contributor guide also stop naming nlohmann/json among the vendored headers in lib/, which it left in 4af9280. --- AGENTS.template.md | 2 +- README.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 5f92432..364a336 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -16,7 +16,7 @@ crafter-build is a C++26 modules build system. A project is described by a `proj | `examples/` | Standalone user-facing projects, MIT licensed. | | `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. | | `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. | -| `lib/` | Vendored third-party headers (nlohmann/json, glslang's DirStackFileIncluder). Do not edit. | +| `lib/` | Vendored third-party headers (glslang's DirStackFileIncluder). Do not edit. | | `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. | | `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. | | `.review-gates/` | The pre-push review's `config.json` and this repository's lens sections (`lenses/`), read by Crafter.Review. Its `push/` and `trees/` are generated and gitignored. | diff --git a/README.md b/README.md index 762e84c..0c68e1a 100644 --- a/README.md +++ b/README.md @@ -45,9 +45,9 @@ Run `crafter-build` in that directory, outputs land at `bin/myapp--.objects`, so the command is no longer for many sources than for one. -crafter-build orders a configuration's units by the `import` lines of its sources: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused before anything of it is built, with an error that names the units in the order they wait. The imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under `#if 0` counts too, and such text can make a round in a project the compiler accepts. +crafter-build orders a configuration's units by what their sources import: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. What a `.cppm` or `.cpp` declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, so it reads them as the compiler does: an import in a comment, in a string literal or in a branch that `#if` leaves out is none, and a define or a header decides one as it does for the compile. It reads them once the configuration's dependencies are built, since the command takes their include paths, and keeps what it found in the `build/` directory, as it keeps objects: in `scans/` at the source's path from `cfg.path`, and in `scans-outside/` at its whole path for a source outside `cfg.path`, until the source, a file it includes or the command changes. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused once its sources are read, before any of its `.cppm` and `.cpp` is compiled, with an error that names the units in the order they wait. -A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. +A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the scans and the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. ### Several configurations @@ -182,7 +182,7 @@ Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project. cfg.dependencies = { math }; ``` -The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths. Releases up to 2.2.0 forward nothing when `.args` is left out. +The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that exports modules and that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths, unless both lists give the project one build directory, as two orders of the same flags of its own can: it is then built once. Releases up to 2.2.0 forward nothing when `.args` is left out. The default is read when the spec is made, so make it inside the entry point, `CrafterBuildProject` or `CrafterBuildConfigurations`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing. @@ -542,7 +542,7 @@ This project is licensed under the GNU Lesser General Public License, version 3 The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects. -The [lib/](lib/) directory contains vendored third-party code (nlohmann/json, glslang's DirStackFileIncluder) that remains under its own permissive licenses, see the headers of those files. +The [lib/](lib/) directory contains vendored third-party code (glslang's DirStackFileIncluder) that remains under its own permissive license, see the header of that file. ## Copyright From 578a1da60097f7e444b226802bebeb6b9c4464e7 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:25:54 +0100 Subject: [PATCH 13/27] docs(packaging): add the 6.4.2 release entry 6.4.2 reads what each .cppm and .cpp declares and imports with clang-scan-deps, which preprocesses the source with its compile command, where it searched the source's text with regular expressions (#45), and so refuses a module built twice for one program, and interface units that import each other, once the dependencies are built. A patch, by the version rule: the notes have Fixes and nothing New or Breaking. The range takes ResolvePendingImports off Configuration, and the pendingImports members off Module, ModulePartition and Implementation, all of which interfaces/ exports, and leaves a configuration's interfaces and implementations empty until a build has read its sources. All of it is the build's own bookkeeping of a configuration's units, as Compile() and `compiled` were, which 6.3.0 took off the same unit classes as "internal and not user facing" (12e8b90), and no project.cpp of this checkout or of the Catcrafts checkouts beside it names any of it (callers.txt in the review's evidence). --- .../flatpak/net.catcrafts.CrafterBuild.metainfo.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml index af1f4fa..6f56beb 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml @@ -26,6 +26,15 @@ + + +

Fixes

+
    +
  • What a .cppm or .cpp declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, where crafter-build searched its text (#45). An import in a comment that spans lines, in a string literal or in a branch that #if leaves out no longer counts; one written with two spaces after import, or with a space before its semicolon, is no longer missed, which let a unit be compiled before the module it imports; and a define or a header decides an import as it does for the compile. A string literal that holds export module std; no longer stops the build. What was read is kept in the build directory, and read again when the source, a file it includes or its compile command changes. The refusal of interface units that import each other, and of a module built twice for one program, comes once the configuration's dependencies are built, before any of its own .cppm and .cpp is compiled, where it came before the configuration built anything.
  • +
  • A project that exports modules and that two paths load with the same flags of its own in two orders is built once where the two orders give it one build directory. The build stopped, taking it for two builds of the project's modules.
  • +
+
+

Fixes

From 8019f9d44f45046609f3915f03f54da421632610 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 16:16:38 +0100 Subject: [PATCH 14/27] fix(lint): look for libc++ where the compiler does In crafter-build's Flatpak, whose compiler keeps libc++ in /app and whose /usr has none, a file that includes a header of the C++ standard library could not be parsed for the lint rules that read its AST in a build like that of #46: the file built, and `crafter-build lint` then ran none of those rules on it, printed "'algorithm' file not found" and exited 1. libclang parses through a clang driver of its own. In a build for the host whose compile command names no libc++ directory, as #46's names none, where a sysroot or CRAFTER_BUILD_LIBCXX_DIR would name one, that driver looks for libc++'s headers under ../include from the directory of its argv[0], then under /usr/local/include and /usr/include. ParseAst gave libclang the compile command without its compiler, and clang_parseTranslationUnit names argv[0] plain "clang", in no directory. So the parse of such a build, natively as in the Flatpak, took the first libc++ it found under ../include from the working directory, /usr/local/include and /usr/include, whichever compiler the build used. The -resource-dir ParseAst passes is for clang's own headers and changes nothing for libc++. The compile command's argv[0] would not do on its own: a clang++ from PATH is the bare name clang++, in no directory either, and a clang++ reached through a link into another directory takes itself to be where the link leads, as clang finds its installation from the file it runs as. The compiler says where that is, on the InstalledDir line of `clang++ --version`, which GetToolchain() already runs for clangVersion. Toolchain::installedDir keeps it, InstalledClangxx(command) names the compiler in it, and ParseAst passes that as argv[0], through clang_parseTranslationUnit2FullArgv, which takes argv[0] from its caller. With argv[0] there, the parse finds libc++ where the compile does, whatever the working directory. A compile command can have the compiler look from elsewhere: with -no-canonical-prefixes, where the last of it and -canonical-prefixes is that one, clang takes itself to be at clangxx as written, or, where no file is there, as is usual for a bare name, at the one PATH gives, a link not followed, and `clang++ -no-canonical-prefixes --version` names that directory. GetToolchain() runs that too, Toolchain::installedDirAsWritten keeps what it names, and InstalledClangxx(command) names the compiler there for a command whose last prefix flag is -no-canonical-prefixes, as clang's own driver reads them. argv[0] also gives libclang's driver its mode, by its file name, and the configuration files it reads by default, from its directory. The parse now runs in the g++ mode the compile runs in, where it ran in clang's gcc mode, and reads the default configuration files beside the compiler that the compile reads, clang++.cfg among them; before, it read none from there, as the driver skips the directory of an argv[0] that has none. -resource-dir stays, for a libclang of another release than the compiler, whose driver would derive the directory from argv[0] for its own release. The comment on it said libclang found clang's own headers relative to its own install path; its driver derived them from argv[0], as it does libc++'s. Fixes #46 --- implementations/Crafter.Build-Lint.cpp | 38 ++++++++++++++++----- implementations/Crafter.Build-Toolchain.cpp | 29 ++++++++++++++++ interfaces/Crafter.Build-Toolchain.cppm | 28 +++++++++++++++ 3 files changed, 87 insertions(+), 8 deletions(-) diff --git a/implementations/Crafter.Build-Lint.cpp b/implementations/Crafter.Build-Lint.cpp index 948b9e4..f546ea9 100644 --- a/implementations/Crafter.Build-Lint.cpp +++ b/implementations/Crafter.Build-Lint.cpp @@ -43,6 +43,7 @@ namespace { decltype(&clang_createIndex) createIndex = nullptr; decltype(&clang_disposeIndex) disposeIndex = nullptr; decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr; + decltype(&clang_parseTranslationUnit2FullArgv) parseTranslationUnit2FullArgv = nullptr; decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr; decltype(&clang_getFile) getFile = nullptr; decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr; @@ -133,6 +134,7 @@ namespace { bind(lib.createIndex, "clang_createIndex"); bind(lib.disposeIndex, "clang_disposeIndex"); bind(lib.parseTranslationUnit, "clang_parseTranslationUnit"); + bind(lib.parseTranslationUnit2FullArgv, "clang_parseTranslationUnit2FullArgv"); bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit"); bind(lib.getFile, "clang_getFile"); bind(lib.getLocationForOffset, "clang_getLocationForOffset"); @@ -705,11 +707,12 @@ namespace { return decls; } - // libclang locates its builtin headers relative to its own install path, - // which need not agree with the clang++ on PATH that produced the PCMs. - // When it disagrees the failure is total and unhelpful — every parse dies - // on "'stddef.h' file not found" — so ask the driver and pass it - // explicitly. Cached like HostTarget, and for the same reason. + // The resource directory, which holds clang's own headers such as + // stddef.h, as the compiler names it. libclang's driver would otherwise + // derive one from argv[0] for libclang's own release, so with a libclang + // of another release than the compiler, a file that includes a header of + // the C++ standard library would fail on "'stddef.h' file not found". + // Cached like HostTarget, and for the same reason. const std::string& ClangResourceDir() { static const std::string Cached = []() -> std::string { CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string())); @@ -752,7 +755,26 @@ namespace { // Byte-length preserving, so cursor line/column land on the original. std::string buffer = BlankExportKeywords(content, tokens); std::string path = file.string(); - std::vector args = CommandToArgs(compileCommand); + // In a build for the host whose compile command names no libc++ + // directory (a sysroot or CRAFTER_BUILD_LIBCXX_DIR names one), the + // driver inside libclang looks for libc++'s headers in ../include from + // the directory of argv[0], as the compiler's driver does from its + // own, and then in /usr/local/include and in /usr/include. Left to + // name argv[0] itself, libclang names it plain "clang", in no + // directory, so the first of those was ../include from the working + // directory, and where none of them had a libc++, as in the Flatpak, + // whose compiler keeps its own in /app, no file of such a build that + // includes a header of the C++ standard library could be parsed + // (issue #46). The compile command's own argv[0] would not do either: + // a clang++ from PATH is a bare name, and one reached through a link + // into another directory takes itself to be where the link leads, + // unless the command's last prefix flag is -no-canonical-prefixes. So + // argv[0] is the compiler where clang started with this command takes + // itself to be, in the directory it says it is installed in when run + // with the command's last prefix flag, or, where it names none, + // clangxx as the command has it (Toolchain::InstalledClangxx). + std::vector args = { GetToolchain().InstalledClangxx(compileCommand).string() }; + std::ranges::move(CommandToArgs(compileCommand), std::back_inserter(args)); // Required: libclang will not infer a module interface unit from the // .cppm extension, and silently treats every flag as a linker input if // left to guess. @@ -772,8 +794,8 @@ namespace { result.error = "clang_createIndex failed"; return result; } - CXTranslationUnit tu = lc.parseTranslationUnit(index, path.c_str(), argv.data(), static_cast(argv.size()), &unsaved, 1, CXTranslationUnit_None); - if (!tu) { + CXTranslationUnit tu = nullptr; + if (lc.parseTranslationUnit2FullArgv(index, path.c_str(), argv.data(), static_cast(argv.size()), &unsaved, 1, CXTranslationUnit_None, &tu) != CXError_Success || !tu) { lc.disposeIndex(index); result.error = "clang could not create a translation unit"; return result; diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index 0edbd84..abb8525 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -151,6 +151,24 @@ namespace { std::atomic ViewMade = false; } +fs::path Toolchain::InstalledClangxx(std::string_view command) const { + // Every word of the command, as clang's driver.cpp reads its arguments + // before it names its own path; the build quotes neither flag. + bool canonical = true; + for (std::size_t at = 0; at < command.size();) { + const std::size_t end = std::min(command.find(' ', at), command.size()); + const std::string_view word = command.substr(at, end - at); + if (word == "-canonical-prefixes") { + canonical = true; + } else if (word == "-no-canonical-prefixes") { + canonical = false; + } + at = end + 1; + } + const fs::path& dir = canonical ? installedDir : installedDirAsWritten; + return dir.empty() ? clangxx : dir / clangxx.filename(); +} + std::string Toolchain::LibcxxCompileFlags() const { if (libcxxDir.empty()) return {}; return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string()); @@ -398,11 +416,22 @@ const Toolchain& Crafter::GetToolchain() { return tc; } tc.hostTriple = Trimmed(std::move(triple.output)); + // The InstalledDir line of a `--version` run; empty where the run + // failed or printed none. + const auto installedDirOf = [](const CommandResult& run) { + constexpr std::string_view InstalledDirLine = "\nInstalledDir: "; + const std::size_t at = run.output.find(InstalledDirLine); + if (run.exitCode != 0 || at == std::string::npos) return fs::path(); + const std::size_t begin = at + InstalledDirLine.size(); + return fs::path(Trimmed(run.output.substr(begin, run.output.find('\n', begin) - begin))); + }; 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)); } + tc.installedDir = installedDirOf(version); + tc.installedDirAsWritten = installedDirOf(RunCommandChecked(std::format("{} -no-canonical-prefixes --version", tc.clangxx.string()))); return tc; }(); return Resolved; diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 24cb930..aa52d6d 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -100,9 +100,37 @@ export namespace Crafter { // `clang++ --version`; both empty when clang++ could not be run. std::string hostTriple; std::string clangVersion; + // The directory clang++ is installed in, from the InstalledDir line + // of that `clang++ --version`. clang names the directory of the file + // it runs from, so for a clang++ found on PATH, or reached through a + // link into another directory, it is where the compiler really is, + // the directory its driver looks for headers and configuration files + // from (InstalledClangxx). Empty when clang++ could not be run or + // named no directory. + fs::path installedDir; + // The same line of `clang++ -no-canonical-prefixes --version`. With + // that flag clang names the directory of clang++ as written, or, where + // no file is there, as is usual for a bare name, of the one PATH + // gives, a link not followed, and a compile whose last prefix flag is + // that one looks from there. Empty as installedDir is. + fs::path installedDirAsWritten; // Why clang++ could not be resolved or run; empty when it could. std::string error; + // clangxx as a program that runs a clang driver of its own over + // `command`, a compile command that starts with clangxx, has to be + // given it: the same file name in the directory clang started with + // that command takes itself to be in, installedDirAsWritten where the + // last of -canonical-prefixes and -no-canonical-prefixes in the + // command is -no-canonical-prefixes, as clang's own driver decides it, + // and installedDir otherwise. That driver takes the directory of the + // compiler it is given as written, without following a link to where + // the compiler is, and looks from there for what the compiler's own + // driver looks for from its directory: clang's own headers where it is + // not told where they are, libc++'s in a build for the host whose + // command names no libc++ directory, and its default configuration + // files. clangxx itself where that directory is empty. + fs::path InstalledClangxx(std::string_view command) const; // Flags for compiling against libcxxDir; empty without one. std::string LibcxxCompileFlags() const; // Where libc++.so.1 is when clang would not find it itself: an From 090d8f6363813a30df1edfb3c3d08cc761906bc4 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 16:16:38 +0100 Subject: [PATCH 15/27] fix(build): scan sources with the compiler where it is installed clang-scan-deps, which reads what a .cppm or .cpp declares and imports since 6.4.2, builds a clang driver of its own from the compile command it is given, and that driver looks for clang's own headers, and in a build for the host whose command names no libc++ directory for libc++'s too, from the directory of the command's first word: the toolchain's clangxx, looked up on PATH where it is a bare name, and taken as it stands where it is a link, whatever the command says of canonical prefixes. Where clangxx is a link from another directory, as a CRAFTER_BUILD_LLVM_DIR whose bin/clang++ links into another installation makes it, and the command's last prefix flag is not -no-canonical-prefixes, that directory need not lead to either, and the scan of a source that includes a header of the C++ standard library then failed, and the build with it, on "'stddef.h' file not found" or on the header it included, though the compile, which takes itself to be where the link leads, found them. It is the parse of issue #46 over again, in the scan. The scan is now given the compile command with Toolchain::InstalledClangxx(command) as its first word, the compiler where clang started with that command takes itself to be, as lint's parse is given it: in the directory its --version names, or, for a command whose last prefix flag is -no-canonical-prefixes, in the directory of clangxx as written, from which such a compile looks and from which the scan of it looked before. That directory is also where the driver looks for its default configuration files, clang++.cfg among them, so for any other command the scan now reads the ones beside the compiler, which the compile reads, where it read any beside a link. What is kept of a scan still records the compile command itself, which decides when a source is scanned again: what the source is compiled with has not changed. AGENTS.template.md now says which of the two commands is which. --- AGENTS.template.md | 2 +- implementations/Crafter.Build-Clang.cpp | 37 +++++++++++++++++++++---- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 364a336..5e1c58a 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -206,7 +206,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. - The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel ` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. - An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. -- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. 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 holding the command it was taken with and what clang-scan-deps wrote, with a dependency file beside it, and taken again when the command differs, when the source or a file the dependency file lists is newer, and when it cannot be read. A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build. +- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. 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 holding the compile command it was taken for and what clang-scan-deps wrote, with a dependency file beside it, and taken again when that command differs, when the source or a file the dependency file lists is newer, and when it cannot be read; clang-scan-deps is given that command with its first word made the compiler where clang started with that command takes itself to be: the directory it is installed in, or, for a command whose last of `-canonical-prefixes` and `-no-canonical-prefixes` is `-no-canonical-prefixes`, that of the compiler as written (`ScannedAs`, `Toolchain::InstalledClangxx`). A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build. - Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - A CMake external whose recorded configure inputs (`/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. - The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps. diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 3b367e3..aa6c813 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -299,9 +299,10 @@ namespace { } // The scan of a source that Build() keeps at `scan`, when it holds for - // `command`: it was taken with that command, after the source and every - // file the source included were last written (NewestPrerequisite of - // its dependency file). nullopt when it does not, and when it cannot be + // `command`: it was taken for that command, which clang-scan-deps was + // given as ScannedAs makes it, after the source and every file the + // source included were last written (NewestPrerequisite of its + // dependency file). nullopt when it does not, and when it cannot be // read; the source is then scanned again. std::optional CurrentScan(const fs::path& scan, std::string_view command) { std::error_code ec; @@ -1137,6 +1138,29 @@ namespace { return quoted; } + // `command`, a compile command of GetCompileCommand's, with its first + // word, the toolchain's clangxx, made + // Toolchain::InstalledClangxx(command), the compiler where clang started + // with that command takes itself to be. clang-scan-deps runs a clang + // driver of its own over the command after its --, and that driver looks + // for clang's own headers, and in a build for the host whose command names + // no libc++ directory for libc++'s too, from the directory of the + // command's first word, found on PATH where it is a bare name, without + // following a link to where the compiler is, whatever the command says of + // canonical prefixes: with a clangxx reached through a link from another + // directory, as CRAFTER_BUILD_LLVM_DIR may name one, a source that + // includes a header of the C++ standard library failed its scan where + // those headers were not to be found from the link's directory, though its + // compile, which takes itself to be where the link leads unless the + // command's last prefix flag is -no-canonical-prefixes, found the header. + // A command that does not start with clangxx is left as it is. + std::string ScannedAs(std::string_view command) { + const Toolchain& tc = GetToolchain(); + const std::string compiler = tc.clangxx.string(); + if (!command.starts_with(compiler)) return std::string(command); + return std::format("{}{}", ShellQuote(tc.InstalledClangxx(command).string()), command.substr(compiler.size())); + } + // Has `scanner`, clang-scan-deps, read `source` as `command` compiles it, // and keeps what it found at `scan` for CurrentScan: a JSON object of the // command and of the P1689 description the scanner wrote, with the @@ -1152,7 +1176,7 @@ namespace { // -w: what the preprocessor warns of, the compile of the source // reports. The command's own output is named `scan`, so that the // dependency file is the rule for the scan. - const std::string failed = RunBuildCommand(std::format("{} -format=p1689 -o {} -- {} -w {} -c -MD -MF {} -o {}", ShellQuote(scanner.string()), ShellQuote(description.string()), command, ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string()))); + const std::string failed = RunBuildCommand(std::format("{} -format=p1689 -o {} -- {} -w {} -c -MD -MF {} -o {}", ShellQuote(scanner.string()), ShellQuote(description.string()), ScannedAs(command), ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string()))); const std::optional written = ReadWholeFile(description); fs::remove(description, ec); if (!failed.empty()) { @@ -1190,8 +1214,9 @@ namespace { } // Reads what each interface and implementation source of `config` - // declares and imports, with `command`, the command they are compiled - // with, and gives the configuration the modules and units that makes. A + // declares and imports, as `command`, the command they are compiled + // with, compiles them (ScanSource), and gives the configuration the + // modules and units that makes. A // source whose scan is current (CurrentScan) is not read again; the // others are scanned at once, each a job on the workers of the process. // Returns why it could not, empty when it could; the configuration then From 043b1a3015f87909fd71544db294e5eb4ffe16df Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 16:16:38 +0100 Subject: [PATCH 16/27] test(lint): a compiler installed in a directory of its own LintCompilerHeaders stages an installation of its own: the toolchain's compiler copied into install/bin, beside links to the rest of the real installation, and one header more in its c++/v1, crafter_issue46.h. The toolchain it points the build at with CRAFTER_BUILD_LLVM_DIR has a bin/clang++ that links to that copy, and no include directory. The compiler runs from install/bin, so the compile of a file that includes and crafter_issue46.h finds both, and the build's scan of the file and lint's parse of it have to as well. Without the lint fix the parse fails on crafter_issue46.h on a host whose /usr has a libc++, and on in crafter-build's Flatpak, whose /usr has none. It fails in the same two ways with argv[0] taken from the compile command, llvm/bin/clang++. Without the scan fix the scan, given llvm/bin/clang++ as well, fails the same two ways, and the build with it, which the test's first check reports. The compiler is copied because a link would lead clang back to the real installation, and the copy is of the clang++ in the directory `clang++ --version` names, so that a wrapper on PATH that runs the compiler is not copied in its place. The test takes CRAFTER_BUILD_LIBCXX_DIR out of its environment, which would have every compile take that libc++ in place of the staged one, and the std module the staged toolchain builds goes to a cache of its own. It skips where it cannot stage the compiler: where no clang++ is found, the compiler's installation has no libc++ headers of its own, no llvm-ar or clang-scan-deps is beside the compiler, or the copy names no resource directory it has. A second configuration on the same toolchain passes -no-canonical-prefixes, with which the compiler takes itself to be in llvm/bin, as written, and reads the clang++.cfg the test writes there, which adds a directory only it names; its file includes the one header that directory holds, and none of the C++ standard library, which llvm/ has no include directory for. Given install/bin/clang++ whatever the command's prefix flags, the scan fails on that header, and the build with it, and so does the parse. The test takes CLANG_NO_DEFAULT_CONFIG out of its environment as well, which would have clang read no configuration file, and where the compile with the flag still does not read the file beside the link, as where a user or system configuration directory holds a clang++.cfg, or a -clang++.cfg, that clang finds first, it leaves the second configuration out and skips, unless the first configuration failed. --- project.cpp | 1 + tests/LintCompilerHeaders/main.cpp | 235 +++++++++++++++++++++++++++++ 2 files changed, 236 insertions(+) create mode 100644 tests/LintCompilerHeaders/main.cpp diff --git a/project.cpp b/project.cpp index d0cb676..30cedf0 100644 --- a/project.cpp +++ b/project.cpp @@ -352,6 +352,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("LintCompilerHeaders").Dependencies({ CrafterBuildLib.get() }); } // Dogfood: the lite house rules, imported from their own repo through diff --git a/tests/LintCompilerHeaders/main.cpp b/tests/LintCompilerHeaders/main.cpp new file mode 100644 index 0000000..ce1deb3 --- /dev/null +++ b/tests/LintCompilerHeaders/main.cpp @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +extern "C" int setenv(const char* name, const char* value, int overwrite); +extern "C" int unsetenv(const char* name); + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + void Write(const fs::path& path, std::string_view content) { + std::ofstream file(path, std::ios::binary | std::ios::trunc); + file.write(content.data(), static_cast(content.size())); + } + + // The file the toolchain's clang++ runs as when no other toolchain is + // staged: CRAFTER_BUILD_LLVM_DIR's, else the one on PATH, found in the + // directory the compiler itself names, so that a wrapper on PATH that + // runs the compiler is not taken for it. Empty when there is none. + fs::path RealCompiler() { + const char* llvm = std::getenv("CRAFTER_BUILD_LLVM_DIR"); + const std::string compiler = llvm != nullptr && *llvm != '\0' ? (fs::path(llvm) / "bin" / "clang++").string() : std::string("clang++"); + const auto version = RunCommandWithTimeout(std::format("{} --version", ShellQuote(compiler)), std::chrono::seconds(30)); + constexpr std::string_view InstalledDirLine = "\nInstalledDir: "; + const std::size_t at = version.output.find(InstalledDirLine); + if (version.exitCode != 0 || at == std::string::npos) return {}; + const std::size_t begin = at + InstalledDirLine.size(); + std::string dir = version.output.substr(begin, version.output.find('\n', begin) - begin); + while (!dir.empty() && (dir.back() == '\r' || dir.back() == ' ')) dir.pop_back(); + std::error_code ec; + const fs::path real = fs::canonical(fs::path(dir) / "clang++", ec); + return ec ? fs::path() : real; + } + + // A link in `to` to every entry of `from` but the ones `except` names. + void LinkEntries(const fs::path& from, const fs::path& to, std::initializer_list except) { + for (const fs::directory_entry& entry : fs::directory_iterator(from)) { + const std::string name = entry.path().filename().string(); + if (!std::ranges::contains(except, name)) fs::create_symlink(entry.path(), to / name); + } + } +} + +// lint parses a file with the headers of the compiler that builds it, +// wherever that compiler is installed. libclang was given the compile +// command without its compiler and named the driver it runs plain "clang", +// and in a build for the host whose compile command names no libc++ +// directory, such as this test's, that driver, in no directory, looked for +// libc++ only in ../include from the working directory, in +// /usr/local/include and in /usr/include. Where none of them had one, as in +// the Flatpak, whose compiler keeps its libc++ in /app, a file of such a +// build that includes built, and every rule that reads its AST +// then failed on "'algorithm' file not found" (issue #46). +// +// Staged so that it fails without the fix on any host it can be staged on: +// an installation of the test's own, the toolchain's compiler copied into +// install/bin beside links to the rest of the real installation, with one +// header more in its c++/v1, crafter_issue46.h; and the toolchain the build +// is pointed at, whose bin/clang++ is a link to that copy and which has no +// include directory. The compiler runs from install/bin, so its compile finds +// both headers. A parse that looks for libc++ under /usr finds no +// crafter_issue46.h, and one that takes the compile command's own argv[0], +// llvm/bin/clang++, finds none either. The build's scan of the file, which +// clang-scan-deps makes with a driver of its own, is in the same place: given +// llvm/bin/clang++, it failed the build on crafter_issue46.h. A host whose +// compiler the copy cannot stand in for skips. +// +// A compile command whose last prefix flag is -no-canonical-prefixes has the +// compiler take itself to be where clangxx is as written, in llvm/bin, and +// read the clang++.cfg there, which adds a directory only it names. The second +// configuration's file includes a header from that directory, and the scan and +// the parse have to look from llvm/bin as the compile does: given +// install/bin/clang++, both failed on that header. Where the compile itself +// does not read that file, as where a user or system configuration directory +// hides it, the second configuration is left out, and the test skips unless +// the first failed. +int main() { + const fs::path root = fs::temp_directory_path() / "crafter-build-lint-compiler-headers"; + std::error_code ec; + fs::remove_all(root, ec); + + const fs::path compiler = RealCompiler(); + if (compiler.empty()) { + std::println(std::cerr, "SKIP: no clang++ found to stage an installation from"); + return 77; + } + const fs::path real = compiler.parent_path().parent_path(); + if (!fs::is_directory(real / "include" / "c++" / "v1")) { + std::println(std::cerr, "SKIP: {} has no libc++ headers of its own in {}", compiler.string(), (real / "include" / "c++" / "v1").string()); + return 77; + } + for (const std::string_view tool : { "llvm-ar", "clang-scan-deps" }) { + if (!fs::exists(compiler.parent_path() / tool)) { + std::println(std::cerr, "SKIP: no {} beside {} for the staged toolchain", tool, compiler.string()); + return 77; + } + } + const fs::path install = root / "install"; + const fs::path llvm = root / "llvm"; + fs::create_directories(install / "bin"); + fs::create_directories(install / "include" / "c++" / "v1"); + fs::create_directories(llvm / "bin"); + fs::create_directories(root / "project"); + fs::create_directories(root / "cache"); + + // A copy, not a link: clang finds its installation from the file it runs + // as, and a link would lead it back to the real one. The rest is the real + // installation's, linked: the programs and configuration files beside the + // compiler, its shared libraries and its own headers wherever its build + // put them, lib/ or lib64/, and every header, with one more in c++/v1. + fs::copy_file(compiler, install / "bin" / "clang++"); + fs::permissions(install / "bin" / "clang++", fs::perms::owner_all, fs::perm_options::add); + LinkEntries(compiler.parent_path(), install / "bin", {"clang++"}); + LinkEntries(real, install, {"bin", "include"}); + LinkEntries(real / "include", install / "include", {"c++"}); + LinkEntries(real / "include" / "c++", install / "include" / "c++", {"v1"}); + LinkEntries(real / "include" / "c++" / "v1", install / "include" / "c++" / "v1", {}); + Write(install / "include" / "c++" / "v1" / "crafter_issue46.h", "#pragma once\ninline constexpr int CrafterIssue46 = 46;\n"); + // The resource directory the copy works out from where it runs holds + // clang's own headers, stddef.h among them. A clang built to look for it + // somewhere those links do not reach, or a copy that does not start here, + // cannot stand in for the compiler. + const auto resource = RunCommandWithTimeout(std::format("{} -print-resource-dir", ShellQuote((install / "bin" / "clang++").string())), std::chrono::seconds(30)); + std::string resourceDir = resource.output; + while (!resourceDir.empty() && (resourceDir.back() == '\n' || resourceDir.back() == '\r')) resourceDir.pop_back(); + if (resource.exitCode != 0 || !fs::is_directory(fs::path(resourceDir) / "include")) { + std::println(std::cerr, "SKIP: the copy of {} in {} has no resource directory it can use: {}", compiler.string(), (install / "bin").string(), resourceDir); + return 77; + } + + fs::create_symlink(install / "bin" / "clang++", llvm / "bin" / "clang++"); + fs::create_symlink(compiler.parent_path() / "llvm-ar", llvm / "bin" / "llvm-ar"); + fs::create_symlink(compiler.parent_path() / "clang-scan-deps", llvm / "bin" / "clang-scan-deps"); + LinkEntries(real, llvm, {"bin", "include"}); + // The toolchain is resolved once per process, so before anything asks + // for it; and the std module it builds goes to a cache of this run's own. + // A CRAFTER_BUILD_LIBCXX_DIR the suite runs with would have every compile + // take that libc++ in place of the staged one, and a + // CLANG_NO_DEFAULT_CONFIG would have clang read no configuration file, + // the one the second configuration rests on among them. + setenv("CRAFTER_BUILD_LLVM_DIR", llvm.c_str(), 1); + unsetenv("CRAFTER_BUILD_LIBCXX_DIR"); + unsetenv("CLANG_NO_DEFAULT_CONFIG"); + setenv("XDG_CACHE_HOME", (root / "cache").c_str(), 1); + + Write(root / "project" / "unit.cpp", "#include \n#include \n\nint Largest(int a, int b) {\n return std::max(a, b) + CrafterIssue46;\n}\n"); + Configuration cfg; + cfg.path = root / "project"; + cfg.name = "compiler-headers"; + cfg.outputName = "compiler-headers"; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::LibraryStatic; + std::array interfaces = {}; + std::array implementations = { "unit" }; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + + { + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult result = Build(cfg, depResults, depMutex); + Check(result.result.empty(), std::format("the staged toolchain builds the file: {}", result.result)); + } + + std::vector declared; + cfg.AddAstLintRule("reads-ast", [&declared](LintContext& ctx) { + for (const LintDecl& decl : ctx.Decls()) declared.push_back(decl.name); + }); + const LintSummary summary = RunLint(cfg, {}); + Check(summary.errors == 0, "lint parses the file the build compiled (why not is on stderr)"); + Check(std::ranges::contains(declared, std::string("Largest")), "the rule that reads the AST sees the file's function"); + + // The same toolchain, with -no-canonical-prefixes in the command. The + // configuration file beside the link is written only now, once the first + // configuration is done with. The file includes no header of the C++ + // standard library, as llvm/ has no include directory, only the one that + // configuration file's directory holds. + fs::create_directories(root / "cfg-include"); + Write(root / "cfg-include" / "crafter_issue46_cfg.h", "#pragma once\ninline constexpr int CrafterIssue46Cfg = 46;\n"); + Write(llvm / "bin" / "clang++.cfg", std::format("-isystem {}\n", (root / "cfg-include").string())); + Write(root / "project" / "written.cpp", "#include \n\nint Written() {\n return CrafterIssue46Cfg;\n}\n"); + // clang reads the first clang++.cfg it finds, looking in its user and + // system configuration directories before its own, and none where it + // finds a -clang++.cfg first, so the file beside the link can be + // hidden. The compile the case rests on, tried first, says whether it is. + const auto reads = RunCommandWithTimeout(std::format("{} -no-canonical-prefixes -fsyntax-only -x c++ {}", ShellQuote((llvm / "bin" / "clang++").string()), ShellQuote((root / "project" / "written.cpp").string())), std::chrono::seconds(30)); + if (reads.exitCode != 0) { + std::println(std::cerr, "SKIP: the staged clang++ started with -no-canonical-prefixes does not read {}, which a user or system configuration directory can hide: {}", (llvm / "bin" / "clang++.cfg").string(), reads.output.substr(0, reads.output.find('\n'))); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 77; + } + Configuration written; + written.path = root / "project"; + written.name = "compiler-headers-as-written"; + written.outputName = "compiler-headers-as-written"; + written.target = HostTarget(); + written.type = ConfigurationType::LibraryStatic; + written.compileFlags.push_back("-no-canonical-prefixes"); + std::array writtenImplementations = { "written" }; + written.GetInterfacesAndImplementations(interfaces, writtenImplementations); + + { + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult result = Build(written, depResults, depMutex); + Check(result.result.empty(), std::format("with -no-canonical-prefixes, the staged toolchain builds the file: {}", result.result)); + } + + std::vector writtenDeclared; + written.AddAstLintRule("reads-ast", [&writtenDeclared](LintContext& ctx) { + for (const LintDecl& decl : ctx.Decls()) writtenDeclared.push_back(decl.name); + }); + const LintSummary writtenSummary = RunLint(written, {}); + Check(writtenSummary.errors == 0, "with -no-canonical-prefixes, lint parses the file the build compiled (why not is on stderr)"); + Check(std::ranges::contains(writtenDeclared, std::string("Written")), "with -no-canonical-prefixes, the rule that reads the AST sees the file's function"); + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From fe25d7aeff55bb3db0dde0c1385f0393e282fee8 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 16:16:38 +0100 Subject: [PATCH 17/27] test(lint): the ast and ast-module cases pass only when their rule ran RunLint calls a rule that reads the AST only on a file it could parse, so when the parse failed, the checks inside the "ast" and "ast-module" rules went untried, and the test, which read nothing of the run but those checks, passed. That is how the "ast" case, whose file includes , passed in crafter-build's Flatpak with #46 open: lint printed "'string' file not found" for that file, and the test exited 0. Both cases now also check that their rule ran and that the run had no error. --- tests/Lint/main.cpp | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/Lint/main.cpp b/tests/Lint/main.cpp index 8db7f3b..556b540 100644 --- a/tests/Lint/main.cpp +++ b/tests/Lint/main.cpp @@ -629,7 +629,9 @@ int main() { Scratch s("ast"); s.Write("f", Source); Configuration cfg = s.Config({"f"}); - cfg.AddAstLintRule("ast", [](LintContext& ctx) { + bool ran = false; + cfg.AddAstLintRule("ast", [&ran](LintContext& ctx) { + ran = true; Check(ctx.AstAvailable(), std::format("ast: parse succeeded ({})", ctx.AstUnavailableReason())); std::span decls = ctx.Decls(); Check(!decls.empty(), "ast: declarations found"); @@ -688,7 +690,13 @@ int main() { Check(std::string_view(ctx.content).substr(count->begin, count->end - count->begin) == "int count", "ast: extent brackets exactly the declaration"); } }); - RunLint(cfg, Mode(LintMode::Report)); + const LintSummary summary = RunLint(cfg, Mode(LintMode::Report)); + // The driver runs a rule that reads the AST only on a file it could + // parse, so when the parse fails every check above goes untried and + // the run's error is all that is left to see. In crafter-build's + // Flatpak this file's was not found, and the case passed + // (issue #46). + Check(ran && summary.errors == 0, "ast: the rule ran on the parsed file (why not is on stderr)"); } // A module interface unit. libclang reports `export namespace X { … }` as a @@ -710,7 +718,9 @@ int main() { std::array ifaces = { "Demo" }; std::array impls = {}; cfg.GetInterfacesAndImplementations(ifaces, impls); - cfg.AddAstLintRule("ast-module", [](LintContext& ctx) { + bool ran = false; + cfg.AddAstLintRule("ast-module", [&ran](LintContext& ctx) { + ran = true; Check(ctx.AstAvailable(), std::format("ast-module: parse succeeded ({})", ctx.AstUnavailableReason())); std::span decls = ctx.Decls(); auto find = [&](LintDeclKind kind, std::string_view name) -> const LintDecl* { @@ -732,7 +742,9 @@ int main() { Check(count != nullptr && count->line == 18, "ast-module: field line matches"); Check(exported != nullptr && exported->line == 20, "ast-module: exported variable line matches"); }); - RunLint(cfg, Mode(LintMode::Report)); + const LintSummary summary = RunLint(cfg, Mode(LintMode::Report)); + // As in the case above: the checks only count if the rule ran. + Check(ran && summary.errors == 0, "ast-module: the rule ran on the parsed file (why not is on stderr)"); } // An unavailable AST must fail the run, never look like a clean file. A From cb8914d387fbf4e8933c3dbe4481d3615f15efa9 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 16:16:38 +0100 Subject: [PATCH 18/27] docs(packaging): add the 6.4.3 release entry 6.4.3 has lint parse a file for the rules that read its AST with the libc++ of the compiler that builds it, so that in the Flatpak those rules run on a file that includes a header of the C++ standard library (#46), and gives the scan of a build's sources the compiler where it is installed, so that a build whose compiler is reached through a link from another directory scans them. A patch, by the version rule: the notes have Fixes and nothing New or Breaking. The range adds Toolchain::installedDir, Toolchain::installedDirAsWritten and Toolchain::InstalledClangxx(command), which interfaces/ exports, for the linter and the scan to read. They are not under New, as ObjectPath, which 6.4.1 exported for the tests, was not. --- .../flatpak/net.catcrafts.CrafterBuild.metainfo.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml index 6f56beb..afaf84a 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml @@ -26,6 +26,15 @@ + + +

Fixes

+
    +
  • In crafter-build's Flatpak, crafter-build lint runs the rules that read a file's AST on a source that includes a header of the C++ standard library, such as <algorithm>, in a build for the host that names no libc++ directory of its own through a sysroot, CRAFTER_BUILD_LIBCXX_DIR or its flags (#46). There such a source built, and lint then ran none of those rules on it, printed 'algorithm' file not found and exited 1. The parse of such a build took the first libc++ it found under ../include from the working directory, /usr/local/include and /usr/include, wherever the build's compiler keeps its own (/app in the Flatpak, whose /usr has none). It now looks for libc++ where the compiler does, and reads the default configuration files beside the compiler that the compile reads, such as clang++.cfg.
  • +
  • A build no longer fails to scan its sources where its compiler is reached through a link from another directory, as a bin/clang++ under CRAFTER_BUILD_LLVM_DIR may be. clang-scan-deps, which reads what a source declares and imports since 6.4.2, looked for clang's own headers from the directory of the link, and for libc++'s too in a build for the host that names no libc++ directory of its own, and where they were not to be found from there, the scan of a source that includes a header of the C++ standard library failed, and the build with it, though its compile found the header. It is now given the compiler in the directory the compiler says it is installed in, as lint's parse is, and reads the default configuration files beside the compiler that the compile reads.
  • +
+
+

Fixes

From dc8e9e6f9e1c41a1ad8eb654d23e6c1145907d08 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 26 Nov 2026 10:37:09 +0100 Subject: [PATCH 19/27] feat(test): give a test that sets Test::wayland a compositor of its own A test that opens a window opened it on the display of whoever ran the suite: every `crafter-build test` of Crafter.Graphics put the windows of its window tests on the desktop, and its other GPU tests connect to the session's compositor too, since Device::Initialize calls wl_display_connect whether a window follows or not. A test that sets the new Test::wayland (TestBuilder::Wayland) now runs with a headless compositor started for it alone. RunSingleTest starts the compositor through sh, with XDG_RUNTIME_DIR naming a directory made for it and without WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, waits up to 30 s for a wayland- socket in that directory, runs the test with WAYLAND_DISPLAY set to the socket's path and with DISPLAY and WAYLAND_SOCKET unset, then stops the compositor's process group and removes the directory. The test's command is env with those changes, and env's command is sh, which execs the test's words: env takes every word with an '=' in it ahead of its command for an assignment, a binary's path among them. The compositor runs under timeout(1) as long as the test may, the wait and 30 s more, and with no limit for a test that has none, a timeout of 0. It is weston on its headless backend with its GL renderer, unless CRAFTER_BUILD_COMPOSITOR or the new --compositor= names another command; `host` gives the tests the session's own display instead, to watch them. A compositor that ends before it listens, sh not finding it included, or does not listen in time fails the test with what it printed. A test that may run where its compositor is missing declares it in requires_ (tool:weston for the default), the check RunTests makes before the build, so no skip of its own is added, and no probe of the command: the command is any sh command, whose first word need not be the compositor. A test that fails, crashes or times out keeps what its compositor printed (TestResult::compositorLog), which RunTests writes to build/test-logs/.compositor.log, and says when the compositor ended while it ran. One compositor per test rather than one per run: no two tests share one, so tests that run at once cannot cover each other's windows or take each other's focus, for weston's start-up on every test. weston's GL renderer, because it imports the dmabufs that a GPU's Vulkan driver presents, as Mesa's and NVIDIA's do, and the headless backend's default renderer and pixman import none: against pixman, the NVIDIA driver reports no format for a window's surface, and Crafter.Graphics's FrameLoopSync stops at its formatCount > 0 assertion. weston cannot run the test itself, as `weston -- ` exits 0 whatever the test returned, so crafter-build runs the compositor beside it. :Platform gains BackgroundCommand, the compositor's process, and PrivateDirectory, its directory. The process is forked with PR_SET_PDEATHSIG and runs under `timeout`, which passes the SIGTERM it gets when crafter-build dies on to the compositor's group, so a crafter-build killed by Ctrl-C leaves no compositor running. The directory is made in $XDG_RUNTIME_DIR, or in /tmp where that is not a directory, rather than in the temp directory, since a socket's path holds 107 bytes, and is flocked while in use; one that a killed crafter-build left is removed when the next is made beside it, once it has not changed for a minute. New members and a parameter with a default, nothing removed: a minor release. --- AGENTS.template.md | 3 +- implementations/Crafter.Build-Clang.cpp | 12 ++ implementations/Crafter.Build-Platform.cpp | 152 +++++++++++++++++++ implementations/Crafter.Build-Test.cpp | 164 +++++++++++++++++++-- interfaces/Crafter.Build-Clang.cppm | 18 +++ interfaces/Crafter.Build-Platform.cppm | 53 +++++++ interfaces/Crafter.Build-Test.cppm | 29 +++- 7 files changed, 418 insertions(+), 13 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 5e1c58a..27f77bd 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -29,7 +29,7 @@ Partitions and what they own: - `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`. - `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`). - `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. -- `:Test` holds `AddTest`, `RunTests` and `TestRunner`. +- `:Test` holds `AddTest`, `RunTests` and `TestRunner`, and starts the headless compositor of a test that sets `Test::wayland` (`RunSingleTest`), through `:Platform`'s `BackgroundCommand` and `PrivateDirectory`. - `:Lint` is the lint/format driver plus the libclang token and AST layer. - `:Script` is the driver behind `crafter-build run`: it looks a name up in the `scripts` of the configurations it is given, calls the callback and turns what it returns into the exit code. - `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configurations returned by a project file that `GitProject` or `LocalProject` loaded have their `path` rebased. @@ -162,6 +162,7 @@ These were decided deliberately. Do not undo them without the maintainer's say-s - `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters. - Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built. - `--runner=cmd:` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests. +- `--compositor=` and `CRAFTER_BUILD_COMPOSITOR` name the command that crafter-build runs through `sh` beside every test that sets `Test::wayland`, unless they name `host`; the default is the weston on `PATH`. - `crafter-build run ` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's: `run` leaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (`KeptBy`); keep it that way. - The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. - crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index aa6c813..6dbbc0d 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -2949,6 +2949,13 @@ Test options (after the `test` subcommand): --runner= Override the test runner for this run. Specs: local cmd: (e.g. cmd:wine) + --compositor= The headless Wayland compositor each test that sets + Test::wayland runs with, a command run through sh + that listens on a wayland- socket in the + XDG_RUNTIME_DIR it is given. Default: weston + --backend=headless --renderer=gl --no-config + --idle-time=0. `host` runs those tests on this + session's own display. --target= Filter to tests whose cfg.target matches. Default: sweep across every distinct target declared by the project's tests plus the host triple. @@ -3052,6 +3059,9 @@ Environment: CRAFTER_BUILD_RUNNER_ Default test runner for a target triple. Replace '-' and '.' with '_' in the triple. CLI --runner= overrides this. + CRAFTER_BUILD_COMPOSITOR Default headless Wayland compositor for + tests that set Test::wayland, as for + --compositor=, which overrides it. CRAFTER_BUILD_LLVM_DIR LLVM prefix to use instead of a toolchain installed beside crafter-build or PATH. CRAFTER_BUILD_LIBCXX_DIR libc++ install to compile and link against @@ -3175,6 +3185,8 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { testOpts.listOnly = true; } else if (verb == Verb::Test && arg.starts_with("--runner=")) { testOpts.runnerOverride = std::string(arg.substr(std::string_view("--runner=").size())); + } else if (verb == Verb::Test && arg.starts_with("--compositor=")) { + testOpts.compositorOverride = std::string(arg.substr(std::string_view("--compositor=").size())); } else if (verb == Verb::Test && !arg.starts_with("-")) { testOpts.globs.emplace_back(arg); } else if ((verb == Verb::Lint || verb == Verb::Format) && arg == "--list") { diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index 45aabae..c62cbd3 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -9,6 +9,8 @@ module; #include #include #include +#include +#include #include #include module Crafter.Build:Platform_impl; @@ -874,6 +876,156 @@ CommandResult Crafter::RunCommandWithTimeout(std::string_view cmd, std::chrono:: return result; } +namespace { + // How a child that waitid saw end ended, read as DecodeWaitStatus reads + // a pclose: the exit code, or 128+signal when a signal ended it. + std::int32_t ChildExitCode(const siginfo_t& info) { + return info.si_code == CLD_EXITED ? info.si_status : 128 + info.si_status; + } +} + +Crafter::BackgroundCommand::BackgroundCommand(std::string_view command, std::span environment, const fs::path& log, std::chrono::seconds lifetime) { + // The death signal goes to the process this forks, so that has to be + // the timeout process: `exec` makes the sh it starts as become it. + // timeout passes a SIGTERM on to its whole group and ends what is still + // running 2 s later. + std::string script = std::format("exec timeout -k 2 {} sh -c {}", lifetime.count(), ShellQuote(command)); + std::string shell = "sh"; + std::string flag = "-c"; + std::array argv = { shell.data(), flag.data(), script.data(), nullptr }; + + std::vector variables; + for (char** entry = environ; *entry != nullptr; ++entry) { + const std::string_view variable(*entry); + const std::string_view name = variable.substr(0, variable.find('=')); + if (std::ranges::none_of(environment, [&](const EnvironmentChange& change) { return change.name == name; })) { + variables.emplace_back(variable); + } + } + for (const EnvironmentChange& change : environment) { + if (change.value) variables.push_back(std::format("{}={}", change.name, *change.value)); + } + std::vector envp; + for (std::string& variable : variables) envp.push_back(variable.data()); + envp.push_back(nullptr); + + // Both close-on-exec: the child keeps them only as its 0, 1 and 2. + const std::int32_t output = ::open(log.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (output < 0) throw std::runtime_error(std::format("cannot write {}: {}", log.string(), std::strerror(errno))); + const std::int32_t input = ::open("/dev/null", O_RDONLY | O_CLOEXEC); + if (input < 0) { + const std::int32_t openError = errno; + ::close(output); + throw std::runtime_error(std::format("cannot open /dev/null: {}", std::strerror(openError))); + } + + const pid_t parent = ::getpid(); + // Everything the child uses was made above: between fork and exec it + // makes async-signal-safe calls only, since another thread of this + // process may hold the allocator's lock at the moment of the fork. + pid = ::fork(); + if (pid == 0) { + // The signal is sent when the thread that forked ends, not the + // process; the parent may also have ended before this line. + if (::prctl(PR_SET_PDEATHSIG, SIGTERM) != 0 || ::getppid() != parent) ::_exit(126); + // A signal mask outlives exec, and a SIGTERM blocked in it would + // keep both the death signal and Stop() from reaching timeout. + sigset_t none; + ::sigemptyset(&none); + ::sigprocmask(SIG_SETMASK, &none, nullptr); + ::setpgid(0, 0); + ::dup2(input, STDIN_FILENO); + ::dup2(output, STDOUT_FILENO); + ::dup2(output, STDERR_FILENO); + ::execve("/bin/sh", argv.data(), envp.data()); + ::_exit(127); + } + const std::int32_t forkError = errno; + ::close(input); + ::close(output); + if (pid < 0) throw std::runtime_error(std::format("cannot start {}: {}", command, std::strerror(forkError))); + // From this side as well, so that the group exists before Stop() can + // signal it, whichever of the two runs first. Once the child has + // exec'd this fails, after the child's own call has made the group. + ::setpgid(pid, pid); +} + +Crafter::BackgroundCommand::~BackgroundCommand() { + Stop(std::chrono::seconds(5)); +} + +std::optional Crafter::BackgroundCommand::Exited() { + if (exitCode || pid < 0) return exitCode; + siginfo_t info{}; + // WNOWAIT leaves an ended command unreaped: its pid, and with it the + // number of its process group, which Stop() signals, cannot be handed + // to another process before Stop() reaps it. + if (::waitid(P_PID, static_cast(pid), &info, WEXITED | WNOHANG | WNOWAIT) == 0 && info.si_pid == pid) { + exitCode = ChildExitCode(info); + } + return exitCode; +} + +void Crafter::BackgroundCommand::Stop(std::chrono::milliseconds grace) { + if (pid < 0 || reaped) return; + ::kill(-pid, SIGTERM); + const auto deadline = std::chrono::steady_clock::now() + grace; + while (!Exited() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + // What is left of the group: anything the command started that outlived + // it, and the command itself when it did not end within `grace`. + ::kill(-pid, SIGKILL); + std::int32_t status = 0; + while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + reaped = true; +} + +namespace { + // Removes what PrivateDirectory's destructor would have, for the + // processes that never ran it. + void RemoveAbandonedDirectories(const fs::path& parent, std::string_view prefix) { + std::error_code ec; + const auto now = fs::file_time_type::clock::now(); + for (const fs::directory_entry& entry : fs::directory_iterator(parent, ec)) { + std::error_code entryError; + if (!entry.path().filename().string().starts_with(prefix) || !entry.is_directory(entryError) || entry.is_symlink(entryError)) continue; + const auto changed = fs::last_write_time(entry.path(), entryError); + if (entryError || now - changed < std::chrono::minutes(1)) continue; + // Another user's directory does not open: mkdtemp made it 0700. + const std::int32_t held = ::open(entry.path().c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (held < 0) continue; + if (::flock(held, LOCK_EX | LOCK_NB) == 0) fs::remove_all(entry.path(), entryError); + ::close(held); + } + } + + fs::path MakeDirectory(const fs::path& parent, std::string_view prefix) { + RemoveAbandonedDirectories(parent, prefix); + std::string pattern = (parent / std::format("{}XXXXXX", prefix)).string(); + if (::mkdtemp(pattern.data()) == nullptr) { + throw std::runtime_error(std::format("cannot make a directory in {}: {}", parent.string(), std::strerror(errno))); + } + return fs::path(pattern); + } +} + +Crafter::PrivateDirectory::PrivateDirectory(const fs::path& parent, std::string_view prefix) : path(MakeDirectory(parent, prefix)) { + // Close-on-exec, so that the lock is this process's alone: a command it + // starts that outlives it does not keep the directory from being + // removed. + fd = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (fd >= 0) { + while (::flock(fd, LOCK_EX) != 0 && errno == EINTR) {} + } +} + +Crafter::PrivateDirectory::~PrivateDirectory() { + std::error_code ec; + fs::remove_all(path, ec); + if (fd >= 0) ::close(fd); +} + std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { CacheLock lock(stdPcm.parent_path()); if(config.target == "x86_64-w64-mingw32") { diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index ab75ead..2ef3bad 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -64,12 +64,77 @@ namespace { } } - void WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) { + // Writes build/test-logs/.log and returns its path, or nothing + // when the directory cannot be made. + std::optional WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) { fs::path logDir = projectPath / "build" / "test-logs"; std::error_code ec; fs::create_directories(logDir, ec); - if (ec) return; - std::ofstream(logDir / (std::format("{}.log", name))) << output; + if (ec) return std::nullopt; + const fs::path log = logDir / std::format("{}.log", name); + std::ofstream(log) << output; + return log; + } + + // weston on its headless backend: the compositor a test that sets + // Test::wayland runs with unless --compositor= or CRAFTER_BUILD_COMPOSITOR + // names another. Its GL renderer takes the dmabufs that hardware Vulkan + // and EGL drivers present, which the headless backend's default, a + // renderer that draws nothing, and pixman do not. --no-config keeps the + // user's weston.ini out of the test, and --idle-time=0 keeps the output + // from going idle after the default 300 s, which would stop frame + // callbacks. + constexpr std::string_view DefaultCompositor = "weston --backend=headless --renderer=gl --no-config --idle-time=0"; + // The compositor named for none of the test's own: the test gets the + // environment crafter-build has, display included, to watch its windows. + constexpr std::string_view HostDisplay = "host"; + // How long a compositor may take to listen. weston needs a fraction of a + // second; this is for a machine running a test on every hardware thread. + constexpr std::chrono::seconds CompositorStartup{30}; + + std::string CompositorCommand(const std::optional& compositorOverride) { + if (compositorOverride && !compositorOverride->empty()) return *compositorOverride; + const char* named = std::getenv("CRAFTER_BUILD_COMPOSITOR"); + if (named != nullptr && *named != '\0') return named; + return std::string(DefaultCompositor); + } + + // The wayland- socket a compositor made in `directory`. Any number: + // libwayland's wl_display_add_socket_auto starts at 0 and weston at 1. + std::optional WaylandSocket(const fs::path& directory) { + constexpr std::string_view prefix = "wayland-"; + std::error_code ec; + for (const fs::directory_entry& entry : fs::directory_iterator(directory, ec)) { + const std::string name = entry.path().filename().string(); + if (!name.starts_with(prefix) || name.size() == prefix.size()) continue; + if (!std::ranges::all_of(name.substr(prefix.size()), [](char c) { return c >= '0' && c <= '9'; })) continue; + std::error_code statError; + if (fs::is_socket(entry.symlink_status(statError))) return entry.path(); + } + return std::nullopt; + } + + // Where the directory one test's compositor gets as its XDG_RUNTIME_DIR + // is made: in $XDG_RUNTIME_DIR, where a session's sockets live, when + // that is a directory, else in /tmp. A socket's path holds at most 107 + // bytes, so the directory needs a short path, which a project's, a + // scratch directory's or the temp directory TMPDIR names need not be. + fs::path CompositorParent() { + const char* runtime = std::getenv("XDG_RUNTIME_DIR"); + std::error_code ec; + if (runtime != nullptr && *runtime != '\0' && fs::is_directory(runtime, ec)) return runtime; + return "/tmp"; + } + + // That directory, which also holds the compositor's log. + struct CompositorDirectory : PrivateDirectory { + CompositorDirectory() : PrivateDirectory(CompositorParent(), "crafter-build-wayland-") {} + fs::path Log() const { return path / "compositor.log"; } + }; + + std::string ReadWhole(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); } void PrintResult(const TestResult& r, std::string_view runnerName) { @@ -259,27 +324,82 @@ TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) { return fallback; } -TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout) { +TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride) { TestResult result; result.name = test.config.name; std::map ph; ph["{args}"] = JoinAndQuoteArgs(test.args); - auto start = std::chrono::steady_clock::now(); - CommandResult r; - + std::string cmd; if (test.runner.exec.empty()) { // Local runner: spawn the binary directly through the host shell. - std::string cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]); - r = RunCommandWithTimeout(cmd, timeout); + cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]); } else { // Prefix runner (qemu-user, wasmtime, wine, ...): templated exec // wraps the local binary. ph["{bin}"] = binary.string(); - r = RunCommandWithTimeout(Substitute(test.runner.exec, ph), timeout); + cmd = Substitute(test.runner.exec, ph); } + // The test's own compositor, which no other test shares, so that no + // two tests cover each other's windows or take each other's focus. Its + // directory goes after it: declared first, it is destroyed last. + const std::string compositor = test.wayland ? CompositorCommand(compositorOverride) : std::string(); + std::optional directory; + std::optional process; + if (test.wayland && compositor != HostDisplay) { + directory.emplace(); + // Without a WAYLAND_DISPLAY, which the compositor would take for a + // session to open a window in (wlroots does), or a DISPLAY. + const std::array environment = {{ + {"XDG_RUNTIME_DIR", directory->path.string()}, + {"WAYLAND_DISPLAY", std::nullopt}, + {"WAYLAND_SOCKET", std::nullopt}, + {"DISPLAY", std::nullopt}, + }}; + // As long as the test may run, the wait for its socket and 30 s + // more; none for a test with none, a timeout of 0, which timeout(1) + // takes for no limit, the test's as the compositor's. + const std::chrono::seconds lifetime = timeout.count() > 0 ? timeout + CompositorStartup + std::chrono::seconds(30) : std::chrono::seconds(0); + process.emplace(compositor, environment, directory->Log(), lifetime); + + // weston makes its socket once its backend and renderer are up, so a + // socket means a compositor that takes clients. + const auto deadline = std::chrono::steady_clock::now() + CompositorStartup; + std::optional socket = WaylandSocket(directory->path); + std::optional ended; + while (!socket && !(ended = process->Exited()) && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + socket = WaylandSocket(directory->path); + } + if (!socket) { + process->Stop(std::chrono::seconds(5)); + std::string printed = ReadWhole(directory->Log()); + if (!printed.empty() && !printed.ends_with('\n')) printed.push_back('\n'); + // A compositor that is missing fails the test as any other that + // does not start does. The one skip is the test's own requires_, + // tool:weston for the default, which RunTests checks before the + // build; a probe of the command here would not do, since it is any + // sh command, whose first word need not be the compositor. + result.outcome = TestOutcome::Fail; + result.exitCode = -1; + result.output = ended + ? std::format("the headless compositor ({}) ended with status {} before it listened for clients; it printed:\n{}", compositor, *ended, printed) + : std::format("the headless compositor ({}) made no wayland- socket in {} within {} s; it printed:\n{}", compositor, directory->path.string(), CompositorStartup.count(), printed); + // sh's status for a command it cannot find. + if (ended == 127) result.output += "install weston, name another compositor with CRAFTER_BUILD_COMPOSITOR or --compositor=, or skip a test that may run without it with requires_, tool:weston for weston\n"; + return result; + } + // env's command is sh, which execs the test's words as they are: env + // takes every word with an '=' in it ahead of its command for an + // assignment, the binary's path among them where it has one (a test + // named a=b), and that test never ran. + cmd = std::format("env -u DISPLAY -u WAYLAND_SOCKET WAYLAND_DISPLAY={} sh -c 'exec \"$@\"' sh {}", ShellQuote(socket->string()), cmd); + } + + auto start = std::chrono::steady_clock::now(); + CommandResult r = RunCommandWithTimeout(cmd, timeout); auto end = std::chrono::steady_clock::now(); result.duration = std::chrono::duration_cast(end - start); result.output = std::move(r.output); @@ -292,6 +412,19 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std: else if (r.exitCode != 0) result.outcome = TestOutcome::Fail; else result.outcome = TestOutcome::Pass; + if (process) { + // Asked before Stop() ends it, which would make every compositor one + // that ended. + const std::optional ended = process->Exited(); + process->Stop(std::chrono::seconds(5)); + if (result.outcome != TestOutcome::Pass && result.outcome != TestOutcome::Skipped) { + if (ended) { + if (!result.output.empty() && !result.output.ends_with('\n')) result.output.push_back('\n'); + result.output += std::format("the headless compositor ({}) ended with status {} while the test ran\n", compositor, *ended); + } + result.compositorLog = ReadWhole(directory->Log()); + } + } return result; } @@ -447,6 +580,7 @@ TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.pu TestBuilder& TestBuilder::Dependencies(std::vector d) { Ref().config.dependencies = std::move(d); return *this; } TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; } +TestBuilder& TestBuilder::Wayland(bool w) { Ref().wayland = w; return *this; } void Crafter::UnpackageTests(Configuration& cfg) { for (Test& test : cfg.tests) test.config.packaging = Packaging::None; @@ -692,13 +826,21 @@ TestSummary Crafter::RunTests(std::span configurations, co // wasmtime without the .wasm it was linked as. fs::path binary = ExpectedOutput(t.config); try { - r = RunSingleTest(t, binary, timeout); + r = RunSingleTest(t, binary, timeout, opts.compositorOverride); } catch (const std::exception& e) { r.outcome = TestOutcome::Fail; r.output = std::format("runner threw: {}", e.what()); r.exitCode = -1; } + // Beside the test's own log rather than in it: weston prints some + // 70 lines starting up, which would bury what the test said. + if (!r.compositorLog.empty()) { + if (const std::optional log = WriteLog(owners[i]->path, std::format("{}.compositor", r.name), r.compositorLog)) { + if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n'); + r.output += std::format("the headless compositor's output is in {}\n", log->string()); + } + } if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) { WriteLog(owners[i]->path, r.name, r.output); } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index f73973b..3693d6a 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -176,6 +176,11 @@ export namespace Crafter { std::int32_t signal = 0; std::chrono::milliseconds duration{0}; std::string output; + // What the headless compositor of a test that sets Test::wayland + // printed, kept when the test ran and failed, crashed or timed out, + // for RunTests to write beside the test's own log. A compositor that + // did not start has what it printed in `output`. + std::string compositorLog; }; // One lint diagnostic. Produced by LintContext::Report — or derived by @@ -817,6 +822,19 @@ export namespace Crafter { // unavailable runner becomes a Fail instead of a silent Skip — the // dependency has to be declared to be allowed to be missing. std::vector requires_; + // The test talks to a Wayland compositor, so every run of it gets one + // of its own: a headless compositor started for it alone and stopped + // when it ends. The test finds it through WAYLAND_DISPLAY, the full + // path of its socket, and runs with DISPLAY unset, so the windows it + // opens through WAYLAND_DISPLAY do not reach the session's display. + // The compositor is weston on + // its headless backend unless --compositor= or CRAFTER_BUILD_COMPOSITOR + // names another, or names `host` to give the test the session's own + // display. A test whose compositor cannot be started fails, unless it + // declares the compositor in requires_ (tool:weston for the default), + // which skips it where that is missing. README, "Tests that open + // windows". + bool wayland = false; }; // Directory holding the std module PCM for this Configuration, diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index 1573d9a..e41412e 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -58,6 +58,59 @@ namespace Crafter { // and not to crafter-build, which then sees it as exit code 130. // Project scripts reach this through ScriptContext::Run. std::int32_t RunCommandAttached(std::string_view command); + // One change to the environment a command inherits from this process: + // the variable set to `value`, or taken out when there is none. + struct EnvironmentChange { + std::string name; + std::optional value; + }; + // A command that runs beside its caller, through sh, until Stop() or the + // destructor ends it: the compositor of a test that sets Test::wayland. + // Its stdin is /dev/null and its stdout and stderr go to `log`. It is + // the leader of a process group of its own, so that Stop() reaches what + // it starts in turn, as long as that stays in the group, and runs under `timeout`, which ends that group + // after `lifetime` if nothing else has, a `lifetime` of 0 being none, + // as for timeout(1). The timeout process is also sent + // SIGTERM, which it passes on to the group, when the thread that + // constructed this ends, so a crafter-build that is killed, by Ctrl-C + // or otherwise, leaves no command of this kind running. That is why the + // object has to stay on the thread that made it. Throws when the command + // cannot be started. + class BackgroundCommand { + std::int32_t pid = -1; + std::optional exitCode; + bool reaped = false; + public: + BackgroundCommand(std::string_view command, std::span environment, const fs::path& log, std::chrono::seconds lifetime); + ~BackgroundCommand(); + BackgroundCommand(const BackgroundCommand&) = delete; + BackgroundCommand& operator=(const BackgroundCommand&) = delete; + // The command's exit code once it has ended on its own, 128+signal + // when a signal ended it; nullopt while it runs. Does not wait. + std::optional Exited(); + // Sends the group SIGTERM, then SIGKILL to whatever of it is left + // once the command has ended or `grace` has passed, and waits for the + // command. Further calls do nothing. + void Stop(std::chrono::milliseconds grace); + }; + // A new directory in `parent`, named `prefix` and six random characters, + // that only this user may enter (mkdtemp), removed with everything in it + // when this ends. A process that is killed runs no destructor, so this + // also holds an flock on the directory, which the OS drops with the + // process, and making one removes the directories of `prefix` in + // `parent` that nobody holds and that have not changed for a minute: + // left behind by a process that is gone. The minute covers one that is + // being made at that moment, between mkdtemp and its lock. Throws when + // the directory cannot be made. + class PrivateDirectory { + std::int32_t fd = -1; + public: + const fs::path path; + PrivateDirectory(const fs::path& parent, std::string_view prefix); + ~PrivateDirectory(); + PrivateDirectory(const PrivateDirectory&) = delete; + PrivateDirectory& operator=(const PrivateDirectory&) = delete; + }; // The link flags that record `dir` as a run path, with -Xlinker rather // than -Wl,: clang splits a -Wl, value at every comma, and `dir` may be a // project's own directory, named whatever its owner chose. Quoted for diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index 2988b6a..7c51b2e 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -53,6 +53,9 @@ export namespace Crafter { TestBuilder& LinkFlag(std::string f); // Append a single compile flag. TestBuilder& CompileFlag(std::string f); + // Sets Test::wayland: the test runs with a headless Wayland + // compositor of its own. + TestBuilder& Wayland(bool w = true); }; struct RunTestsOptions { @@ -75,6 +78,10 @@ export namespace Crafter { // Target scoping is unnecessary because targetFilter ensures the run // contains only one target's tests. std::optional runnerOverride; + // From --compositor=: the compositor every test of the run that sets + // Test::wayland runs with, in place of CRAFTER_BUILD_COMPOSITOR and + // the default. See RunSingleTest. + std::optional compositorOverride; }; struct TestSummary { @@ -98,7 +105,27 @@ export namespace Crafter { // compiled alike are, both fail without being built and name the // configurations. A configuration the list names twice counts once. TestSummary RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs = {}); - TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout); + // Runs `binary` as `test` with its runner, its arguments and `timeout`, + // and reads the outcome from how it ended (exit 0 passes, 77 skips). + // + // When the test sets Test::wayland, a compositor is started for it + // first: `compositorOverride` when it holds a command, else the one + // CRAFTER_BUILD_COMPOSITOR names, else weston on its headless backend. + // The command runs through sh in a process group of its own, with + // XDG_RUNTIME_DIR naming a directory made for it alone and without + // WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, and is waited for until + // a wayland- socket appears in that directory, with a limit of the + // test's, the wait and 30 s more, or none when `timeout` is 0, which is + // no limit for the test either (timeout(1)). The test then runs + // with WAYLAND_DISPLAY set to the socket's path and DISPLAY and + // WAYLAND_SOCKET unset; afterwards the compositor's group is stopped and + // the directory removed. A compositor that ends before it listens, sh + // not finding it included, or does not listen within 30 s fails the + // test, with what it printed; a test that may run where its compositor + // is missing declares it in requires_ (tool:weston), which RunTests + // checks before the build. `host` starts nothing and runs the test with + // this process's environment as it is. + TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride = std::nullopt); // The configurations of the project crafter-build was pointed at, by // name. Run() hands SetParentProject what the project file returned, From 67e97d0a2a92d732aba2d2ab3e23a73b161930d8 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 26 Nov 2026 10:37:44 +0100 Subject: [PATCH 20/27] test: a test's headless compositor, from its start to its cleanup HeadlessCompositor drives RunSingleTest with itself in every part. The harness starts it again as the compositor, which listens on a wayland-7 socket in the XDG_RUNTIME_DIR it is given and records its environment, and as the test, which records its own and connects. A test that sets wayland passes against its compositor and runs with WAYLAND_DISPLAY naming the compositor's socket, without DISPLAY and WAYLAND_SOCKET, and with the XDG_RUNTIME_DIR of the process that runs it. The compositor gets a directory of its own in that one, or in /tmp where that process has none, and none of the WAYLAND_DISPLAY, WAYLAND_SOCKET and DISPLAY that process has, each given a value of the session's in the driver, and afterwards it has been sent SIGTERM, is gone and so is its directory. The compositor's timeout(1) is the test's, the wait for its socket and 30 s more, and none for a test with no time limit; and a test whose binary's path has an '=' in it runs as any other. A test that does not set wayland, and one run under `host`, keep that display. Without an override CRAFTER_BUILD_COMPOSITOR names the compositor, and an override wins over it. A compositor sh cannot find fails the test with status 127, named, and a line on how a test that may run without it is skipped; one that ends before it listens fails it with its status and what it printed, checked on a word the command does not hold, without running the test; a failing test keeps what its compositor printed; a compositor killed while the test runs is reported as ended. A stand-in crafter-build killed in the middle of a test has its compositor sent SIGTERM and gone, and the directory it leaves is removed when the next is made, once dated past the minute, while one changed a moment ago and one that is held stay. Without PR_SET_PDEATHSIG the two checks on the killed crafter-build fail, and without the removal of abandoned directories the one on its directory does; with the test's own words as env's command, the check on the binary whose path has an '=' fails, with a limit of its own for the compositor of a test with none the one on that limit does, without what the compositor printed in the failure the one on that, with WAYLAND_SOCKET left to the compositor and the test the ones on it, and without the command in the failure of a compositor sh cannot find the one on that, which looks for the harness's words, not sh's. No weston is needed, so the suite runs it in the native loop and in the Flatpak's build sandbox alike. The driver makes its compositors' directories in a directory of its own in $XDG_RUNTIME_DIR, or in /tmp where that is not a directory, rather than in the temp directory, since a socket's path holds 107 bytes and a temp directory's path can use them up; its check without an XDG_RUNTIME_DIR has the harness make that compositor's directory in /tmp itself, as crafter-build does where there is none. The driver's directory is a PrivateDirectory, now exported for it, so that one a killed driver left goes when a later one is made, once it has not changed for a minute, and AGENTS.template.md's line on where tests write now says that what a test runs writes caches of its own, crafter-build's builds and wasmtime the modules the wasm tests run, and names this test as the one that writes anywhere else. --- AGENTS.template.md | 2 +- interfaces/Crafter.Build-Platform.cppm | 4 +- project.cpp | 1 + tests/HeadlessCompositor/main.cpp | 491 +++++++++++++++++++++++++ 4 files changed, 496 insertions(+), 2 deletions(-) create mode 100644 tests/HeadlessCompositor/main.cpp diff --git a/AGENTS.template.md b/AGENTS.template.md index 27f77bd..85a92b7 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -167,7 +167,7 @@ These were decided deliberately. Do not undo them without the maintainer's say-s - The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. - crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. - CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. -- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`. Keep it that way. +- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. One test writes elsewhere, `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up. It removes what it makes, and a later run removes what a killed one left once that has not changed for a minute (`PrivateDirectory`). ## CI and publishing diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index e41412e..c7abe00 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -102,7 +102,9 @@ namespace Crafter { // left behind by a process that is gone. The minute covers one that is // being made at that moment, between mkdtemp and its lock. Throws when // the directory cannot be made. - class PrivateDirectory { + // Exported for the tests that make a directory of their own outside the + // temp directory. + export class PrivateDirectory { std::int32_t fd = -1; public: const fs::path path; diff --git a/project.cpp b/project.cpp index 30cedf0..be6f693 100644 --- a/project.cpp +++ b/project.cpp @@ -314,6 +314,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() }); // Loading a project file dlopens the project.so compiled from it, // which references Crafter:: symbols (HostTarget, Configuration // ctors) that have to be visible from the test exe — same wiring diff --git a/tests/HeadlessCompositor/main.cpp b/tests/HeadlessCompositor/main.cpp new file mode 100644 index 0000000..807df30 --- /dev/null +++ b/tests/HeadlessCompositor/main.cpp @@ -0,0 +1,491 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +#include +#include +#include +#include +#include +#include +#include +#include +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; +using namespace std::chrono_literals; + +// A test that sets Test::wayland runs with a headless compositor of its own, +// so that `test` opens no window on the desktop of whoever runs it, as +// Crafter.Graphics's window tests did. RunSingleTest starts the compositor +// with XDG_RUNTIME_DIR naming a directory made for it, in the session's +// XDG_RUNTIME_DIR or in /tmp where there is none, and without the session's +// WAYLAND_DISPLAY and DISPLAY, waits for a wayland- socket there, runs +// the test with WAYLAND_DISPLAY naming that socket and no DISPLAY, and stops +// the compositor and removes the directory afterwards; also when +// crafter-build is killed while the test runs, which would otherwise leave a +// compositor running for good, and the directory that such a crafter-build +// leaves goes the next time one is made. A test that does not set it, or a +// run that names `host`, keeps the session's display. A test with no time +// limit gives its compositor none, and one whose binary's path holds an '=' +// runs as any other. +// +// This binary plays every part. Without arguments it is the driver; the +// harness starts it again as the compositor, which listens on a wayland-7 +// socket and records what it was given, and as the test, which records its +// environment and connects. No real compositor is needed. +// +// The compositors' directories are made in an XDG_RUNTIME_DIR the driver +// makes in the session's own, or in /tmp where there is none, not in the +// temp directory: a socket's path holds 107 bytes, which a temp directory's +// path can use up by itself. The driver removes it, and its state under +// the temp directory, at the end, and it is a PrivateDirectory, so that one +// a killed driver left goes when a later one is made, once it has not +// changed for a minute. The check without an XDG_RUNTIME_DIR has the +// harness make its compositor's directory in /tmp itself, as crafter-build +// does where there is none. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + constexpr std::string_view Unset = ""; + + std::string Variable(std::string_view name) { + const char* value = std::getenv(std::string(name).c_str()); + return value != nullptr ? std::string(value) : std::string(Unset); + } + + // The variables of a Wayland session. + constexpr std::array SessionVariables = { "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY", "XDG_RUNTIME_DIR" }; + + void WriteFile(const fs::path& file, std::string_view content) { + std::ofstream(file, std::ios::binary) << content; + } + + std::string ReadFile(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + } + + // SessionVariables as this process has them, one NAME=value line each. + void RecordEnvironment(const fs::path& file) { + std::string lines; + for (const std::string_view name : SessionVariables) { + lines += std::format("{}={}\n", name, Variable(name)); + } + WriteFile(file, lines); + } + + std::map ReadEnvironment(const fs::path& file) { + std::map variables; + std::istringstream in(ReadFile(file)); + for (std::string line; std::getline(in, line);) { + const std::size_t equals = line.find('='); + if (equals != std::string::npos) variables[line.substr(0, equals)] = line.substr(equals + 1); + } + return variables; + } + + bool SocketAddress(std::string_view path, sockaddr_un& address) { + address = {}; + address.sun_family = AF_UNIX; + if (path.size() >= sizeof(address.sun_path)) return false; + std::ranges::copy(path, address.sun_path); + return true; + } + + // A descriptor connected to the socket at `path`, or -1. + std::int32_t Connect(std::string_view path) { + sockaddr_un address; + if (!SocketAddress(path, address)) return -1; + const std::int32_t fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) return -1; + if (::connect(fd, reinterpret_cast(&address), sizeof(address)) != 0) { + ::close(fd); + return -1; + } + return fd; + } + + bool Gone(pid_t pid) { + return ::kill(pid, 0) != 0 && errno == ESRCH; + } + + pid_t ReadPid(const fs::path& file) { + pid_t pid = 0; + std::istringstream(ReadFile(file)) >> pid; + return pid; + } + + bool WaitFor(const std::function& done, std::chrono::milliseconds limit) { + const auto deadline = std::chrono::steady_clock::now() + limit; + while (!done()) { + if (std::chrono::steady_clock::now() > deadline) return false; + std::this_thread::sleep_for(10ms); + } + return true; + } + + // The parent of `pid`, from /proc//stat, " () + // ...", whose comm may hold spaces and parentheses. + pid_t ParentOf(pid_t pid) { + const std::string stat = ReadFile(std::format("/proc/{}/stat", pid)); + const std::size_t close = stat.rfind(')'); + if (close == std::string::npos) return 0; + std::istringstream rest(stat.substr(close + 1)); + std::string state; + pid_t parent = 0; + rest >> state >> parent; + return parent; + } + + // The command line of the timeout(1) this process runs under, the + // nearest of its ancestors that is one, its words joined by spaces. + std::string TimeoutAbove() { + for (pid_t pid = ::getppid(); pid > 1; pid = ParentOf(pid)) { + std::string words = ReadFile(std::format("/proc/{}/cmdline", pid)); + std::ranges::replace(words, '\0', ' '); + if (words.starts_with("timeout ")) return words; + } + return std::string(); + } + + // The compositor: listens until SIGTERM, which it records, and records + // the timeout(1) it runs under. + std::int32_t FakeCompositor(const fs::path& state) { + RecordEnvironment(state / "compositor.env"); + WriteFile(state / "compositor.timeout", TimeoutAbove()); + WriteFile(state / "compositor.pid", std::format("{}", ::getpid())); + // Blocked before the socket appears, so that sigwait takes the + // SIGTERM of a Stop() that comes the moment the harness sees it. + sigset_t term; + ::sigemptyset(&term); + ::sigaddset(&term, SIGTERM); + ::sigprocmask(SIG_BLOCK, &term, nullptr); + const fs::path socketPath = fs::path(Variable("XDG_RUNTIME_DIR")) / "wayland-7"; + sockaddr_un address; + const std::int32_t fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0 || !SocketAddress(socketPath.string(), address) + || ::bind(fd, reinterpret_cast(&address), sizeof(address)) != 0 || ::listen(fd, 8) != 0) { + std::println(std::cerr, "fake compositor: cannot listen on {}: {}", socketPath.string(), std::strerror(errno)); + return 2; + } + std::println(std::cerr, "fake compositor listening on {}", socketPath.string()); + WriteFile(state / "compositor.listening", socketPath.string()); + std::int32_t signal = 0; + ::sigwait(&term, &signal); + WriteFile(state / "compositor.terminated", ""); + return 0; + } + + // The test: records its environment and connects to WAYLAND_DISPLAY. + // With `hold` it stays connected until the compositor goes away. + std::int32_t Client(const fs::path& state, bool hold) { + RecordEnvironment(state / "client.env"); + const std::string display = Variable("WAYLAND_DISPLAY"); + const std::int32_t fd = Connect(display); + if (fd < 0) { + std::println(std::cerr, "cannot connect to {}: {}", display, std::strerror(errno)); + return 1; + } + WriteFile(state / "client.connected", ""); + if (hold) { + // Never written to: read returns once the listening socket is + // gone, with 0 or ECONNRESET. + char byte = 0; + while (::read(fd, &byte, 1) > 0) {} + } + ::close(fd); + return 0; + } + + // The test, failing after it has ended its compositor: the harness has + // to say that the compositor ended while the test ran. + std::int32_t KillCompositor(const fs::path& state) { + const pid_t compositor = ReadPid(state / "compositor.pid"); + if (compositor <= 0 || ::kill(compositor, SIGKILL) != 0) return 2; + WaitFor([&] { return Gone(compositor); }, 5s); + // Time for timeout, which ends when its child has, to have ended. + std::this_thread::sleep_for(300ms); + return 1; + } + + std::string FakeCompositorCommand(const fs::path& self, const fs::path& state) { + return std::format("{} --compositor {}", ShellQuote(self.string()), ShellQuote(state.string())); + } + + Test MakeTest(bool wayland, std::string_view mode, const fs::path& state) { + Test test; + test.runner = TestRunner::Local(); + test.config.name = std::format("HeadlessCompositor{}", mode); + test.wayland = wayland; + test.args = { std::string(mode), state.string() }; + return test; + } + + // crafter-build in the middle of a test, for the driver to kill. + std::int32_t Orphan(const fs::path& self, const fs::path& state) { + RunSingleTest(MakeTest(true, "--hold", state), self, 30s, FakeCompositorCommand(self, state)); + return 0; + } +} + +int main(int argc, char* argv[]) { + const fs::path self = fs::read_symlink("/proc/self/exe"); + if (argc == 3) { + const std::string_view mode = argv[1]; + const fs::path state = argv[2]; + if (mode == "--compositor") return FakeCompositor(state); + if (mode == "--client") return Client(state, false); + if (mode == "--hold") return Client(state, true); + if (mode == "--env") { + RecordEnvironment(state / "client.env"); + return 0; + } + if (mode == "--fail") { + RecordEnvironment(state / "client.env"); + std::println(std::cerr, "the test failed"); + return 1; + } + if (mode == "--kill-compositor") return KillCompositor(state); + if (mode == "--orphan") return Orphan(self, state); + return 2; + } + + const fs::path root = fs::temp_directory_path() / "crafter-build-headless-compositor"; + std::error_code ec; + fs::remove_all(root, ec); + const auto stateDir = [&](std::string_view name) { + const fs::path dir = root / name; + fs::create_directories(dir); + return dir; + }; + + // The directory the harness makes the compositors' in, as it would in + // the session's XDG_RUNTIME_DIR: one of the driver's own, so that + // nothing here removes or keeps the directories of a real run. Where + // the session has none, it is made in /tmp, by name, whose path leaves + // a socket's room, as a temp directory's need not (above). + const std::string sessionRuntime = Variable("XDG_RUNTIME_DIR"); + const fs::path base = sessionRuntime != Unset && fs::is_directory(sessionRuntime, ec) ? fs::path(sessionRuntime) : fs::path("/tmp"); + std::optional own; + try { + own.emplace(base, "crafter-build-headless-compositor-"); + } catch (const std::exception& e) { + std::println(std::cerr, "FAIL: {}", e.what()); + return 1; + } + const fs::path parent = own->path; + const std::string runtime = parent.string(); + ::setenv("XDG_RUNTIME_DIR", runtime.c_str(), 1); + + // The session's display, which a test that sets Test::wayland must not + // see and one that does not must. + ::setenv("WAYLAND_DISPLAY", "crafter-build-session-display", 1); + ::setenv("DISPLAY", ":4242", 1); + // An fd number nothing has open: nothing here connects through + // libwayland, which would take it for its connection to a compositor. + ::setenv("WAYLAND_SOCKET", "4243", 1); + ::unsetenv("CRAFTER_BUILD_COMPOSITOR"); + + { + const fs::path state = stateDir("wayland"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state)); + Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland passes against its compositor: {}", r.output)); + std::map server = ReadEnvironment(state / "compositor.env"); + std::map client = ReadEnvironment(state / "client.env"); + const fs::path directory = server["XDG_RUNTIME_DIR"]; + Check(directory.parent_path() == parent && directory.filename().string().starts_with("crafter-build-wayland-"), + std::format("the compositor's XDG_RUNTIME_DIR is a directory of its own in {}: {}", parent.string(), directory.string())); + Check(server["WAYLAND_DISPLAY"] == Unset && server["WAYLAND_SOCKET"] == Unset && server["DISPLAY"] == Unset, + "the compositor gets none of the session's WAYLAND_DISPLAY, WAYLAND_SOCKET and DISPLAY"); + Check(client["WAYLAND_DISPLAY"] == ReadFile(state / "compositor.listening"), + std::format("the test's WAYLAND_DISPLAY is the path of the compositor's socket: {}", client["WAYLAND_DISPLAY"])); + Check(client["DISPLAY"] == Unset && client["WAYLAND_SOCKET"] == Unset, "the test runs without DISPLAY and WAYLAND_SOCKET"); + Check(client["XDG_RUNTIME_DIR"] == runtime, "the test keeps the session's XDG_RUNTIME_DIR"); + Check(fs::exists(state / "client.connected"), "the test connected to the compositor"); + Check(fs::exists(state / "compositor.terminated"), "the compositor is sent SIGTERM once the test has ended"); + Check(!directory.empty() && !fs::exists(directory), "the compositor's directory is removed afterwards"); + const pid_t compositor = ReadPid(state / "compositor.pid"); + Check(compositor > 0 && Gone(compositor), "the compositor is not running after the test"); + Check(r.compositorLog.empty(), "a test that passes keeps no compositor log"); + const std::string limit = ReadFile(state / "compositor.timeout"); + Check(limit.starts_with("timeout -k 2 70 "), std::format("the compositor's limit is the test's, the wait for its socket and 30 s more: {}", limit)); + } + + // A test with no time limit, a timeout of 0, which timeout(1) takes for + // none, gives its compositor none either: a limit of its own would end + // the compositor under a test that runs on. + { + const fs::path state = stateDir("unlimited"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 0s, FakeCompositorCommand(self, state)); + Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland and has no time limit passes: {}", r.output)); + const std::string limit = ReadFile(state / "compositor.timeout"); + Check(limit.starts_with("timeout -k 2 0 "), std::format("and its compositor has no limit either: {}", limit)); + } + + // A test whose binary's path has an '=' in it: env, which unsets and + // sets the display's variables, would take that path for an + // assignment of its own. + { + const fs::path state = stateDir("equals"); + const fs::path linked = stateDir("a=b") / "HeadlessCompositor"; + fs::create_symlink(self, linked, ec); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), linked, 10s, FakeCompositorCommand(self, state)); + Check(r.outcome == TestOutcome::Pass && fs::exists(state / "client.connected"), + std::format("a test whose binary's path has an '=' in it runs against its compositor: {}", r.output)); + } + + // Where the session has no XDG_RUNTIME_DIR, the compositor's directory + // is made in /tmp, by name: the temp directory's path may leave a + // socket's path no room. + { + const fs::path state = stateDir("no-runtime"); + ::unsetenv("XDG_RUNTIME_DIR"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state)); + ::setenv("XDG_RUNTIME_DIR", runtime.c_str(), 1); + Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland passes where the session has no XDG_RUNTIME_DIR: {}", r.output)); + std::map server = ReadEnvironment(state / "compositor.env"); + const fs::path directory = server["XDG_RUNTIME_DIR"]; + Check(directory.parent_path() == "/tmp" && directory.filename().string().starts_with("crafter-build-wayland-"), + std::format("and its compositor's XDG_RUNTIME_DIR is then a directory of its own in /tmp: {}", directory.string())); + Check(!directory.empty() && !fs::exists(directory), "which is removed afterwards"); + } + + { + const fs::path state = stateDir("without"); + const TestResult r = RunSingleTest(MakeTest(false, "--env", state), self, 10s, FakeCompositorCommand(self, state)); + std::map client = ReadEnvironment(state / "client.env"); + Check(r.outcome == TestOutcome::Pass, std::format("a test that does not set wayland passes: {}", r.output)); + Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243", + "a test that does not set wayland keeps the session's display"); + Check(!fs::exists(state / "compositor.pid"), "no compositor is started for a test that does not set wayland"); + } + + { + const fs::path state = stateDir("host"); + const TestResult r = RunSingleTest(MakeTest(true, "--env", state), self, 10s, "host"); + std::map client = ReadEnvironment(state / "client.env"); + Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland passes under `host`: {}", r.output)); + Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243", + "under `host` the test keeps the session's display"); + } + + { + const fs::path state = stateDir("variable"); + ::setenv("CRAFTER_BUILD_COMPOSITOR", FakeCompositorCommand(self, state).c_str(), 1); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s); + Check(r.outcome == TestOutcome::Pass && fs::exists(state / "client.connected"), + std::format("without an override the compositor CRAFTER_BUILD_COMPOSITOR names is started: {}", r.output)); + } + + { + const fs::path state = stateDir("override"); + ::setenv("CRAFTER_BUILD_COMPOSITOR", "crafter-build-no-such-compositor", 1); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state)); + Check(r.outcome == TestOutcome::Pass && fs::exists(state / "client.connected"), + std::format("--compositor= wins over CRAFTER_BUILD_COMPOSITOR: {}", r.output)); + ::unsetenv("CRAFTER_BUILD_COMPOSITOR"); + } + + { + const fs::path state = stateDir("missing"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, "crafter-build-no-such-compositor --headless"); + Check(r.outcome == TestOutcome::Fail, std::format("a compositor sh cannot find fails the test: {}", r.output)); + // The command in the harness's words: sh's own error names its first + // word and never the rest. + Check(r.output.contains("(crafter-build-no-such-compositor --headless)") && r.output.contains("status 127") && r.output.contains("tool:weston"), + std::format("the failure names the compositor and says how a test is skipped without it: {}", r.output)); + Check(!fs::exists(state / "client.env"), "the test does not run without its compositor"); + } + + { + const fs::path state = stateDir("broken"); + // Printed in two halves, so that what the failure quotes of the + // command does not hold what the compositor printed. + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, "printf '%s-%s\\n' compositor start-failure >&2; exit 3"); + Check(r.outcome == TestOutcome::Fail, std::format("a compositor that ends before it listens fails the test: {}", r.output)); + Check(r.output.contains("status 3") && r.output.contains("it printed:\ncompositor-start-failure"), + std::format("the failure gives the compositor's status and what it printed: {}", r.output)); + Check(!fs::exists(state / "client.env"), "the test does not run when its compositor did not start"); + } + + { + const fs::path state = stateDir("failing"); + const TestResult r = RunSingleTest(MakeTest(true, "--fail", state), self, 10s, FakeCompositorCommand(self, state)); + Check(r.outcome == TestOutcome::Fail, std::format("a failing test fails: {}", r.output)); + Check(r.compositorLog.contains("fake compositor listening"), std::format("a failing test keeps what its compositor printed: {}", r.compositorLog)); + Check(!r.output.contains("while the test ran"), std::format("a compositor that ran until the end is not reported as ended: {}", r.output)); + } + + { + const fs::path state = stateDir("ended"); + const TestResult r = RunSingleTest(MakeTest(true, "--kill-compositor", state), self, 10s, FakeCompositorCommand(self, state)); + Check(r.outcome == TestOutcome::Fail && r.output.contains("ended with status 137 while the test ran"), + std::format("a compositor killed while the test ran is reported: {}", r.output)); + } + + { + // crafter-build killed in the middle of a test, as Ctrl-C would. + const fs::path state = stateDir("orphan"); + std::fflush(nullptr); + const pid_t orphan = ::fork(); + if (orphan == 0) { + const std::string path = self.string(); + const std::string mode = "--orphan"; + const std::string dir = state.string(); + ::execl(path.c_str(), path.c_str(), mode.c_str(), dir.c_str(), nullptr); + ::_exit(127); + } + const bool connected = orphan > 0 && WaitFor([&] { return fs::exists(state / "client.connected"); }, 10s); + Check(connected, "the test of the crafter-build to be killed connected to its compositor"); + if (orphan > 0) { + ::kill(orphan, SIGKILL); + std::int32_t status = 0; + ::waitpid(orphan, &status, 0); + } + if (connected) { + const pid_t compositor = ReadPid(state / "compositor.pid"); + Check(WaitFor([&] { return fs::exists(state / "compositor.terminated"); }, 5s), + "the compositor of a crafter-build that is killed is sent SIGTERM"); + Check(compositor > 0 && WaitFor([&] { return Gone(compositor); }, 5s), "and is not left running"); + } + + // Its directory is left, unlocked, and goes when the next is made + // once it has not changed for a minute; one made a moment ago, or one + // that is held (here by the driver), stays. + const fs::path abandoned = ReadEnvironment(state / "compositor.env")["XDG_RUNTIME_DIR"]; + Check(connected && fs::is_directory(abandoned, ec), std::format("a crafter-build that is killed leaves its directory: {}", abandoned.string())); + const auto old = fs::file_time_type::clock::now() - std::chrono::minutes(2); + fs::last_write_time(abandoned, old, ec); + const fs::path young = parent / "crafter-build-wayland-young"; + const fs::path held = parent / "crafter-build-wayland-held"; + fs::create_directories(young, ec); + fs::create_directories(held, ec); + fs::last_write_time(held, old, ec); + const std::int32_t lock = ::open(held.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + Check(lock >= 0 && ::flock(lock, LOCK_EX) == 0, "the driver holds a directory"); + const fs::path next = stateDir("after-orphan"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", next), self, 10s, FakeCompositorCommand(self, next)); + Check(r.outcome == TestOutcome::Pass, std::format("the next test that sets wayland passes: {}", r.output)); + Check(!fs::exists(abandoned), "an abandoned directory that has not changed for a minute is removed"); + Check(fs::is_directory(young, ec), "one that changed a moment ago is kept"); + Check(fs::is_directory(held, ec), "and so is one that is held"); + if (lock >= 0) ::close(lock); + } + + fs::remove_all(root, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From 0a91b128cfe8917cd6a25c530746da776a7c9eb2 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 26 Nov 2026 10:37:59 +0100 Subject: [PATCH 21/27] feat(packaging): ship a headless weston for tests that set wayland A test that sets Test::wayland runs with the weston on PATH unless another compositor is named, and the Sdk has none, so the Flatpak builds one: weston 16.0.2 with its headless backend, its GL renderer and its desktop shell, and with none of its other backends or shells and no Vulkan renderer. Its frontend links libinput, libevdev and libdisplay-info whatever the backend, and the Sdk has none of those either, so three modules come before it: libevdev 1.14.0; libinput 1.32.0 without mtdev, libwacom or Lua plugins, of which only the library and its licence ship, since the headless backend opens no input device; and libdisplay-info 0.4.0, which weston would otherwise fetch as a subproject. libinput is a git source pinned by commit, since its 1.32.0 release has no tarball of its own. The four sit just before the crafter-build module, so bumping them rebuilds only them and crafter-build. weston's post-install runs `weston --version` and checks that the backend and the renderer the default command names are installed. --- AGENTS.template.md | 1 + .../flatpak/net.catcrafts.CrafterBuild.yaml | 108 ++++++++++++++++++ 2 files changed, 109 insertions(+) diff --git a/AGENTS.template.md b/AGENTS.template.md index 85a92b7..a78394f 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -215,6 +215,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - `RunCommandWithTimeout` runs its command under `timeout`, which can only start programs, so a shell builtin such as `command -v` fails there wherever no program of that name is on PATH, as on Arch and in the Sdk: a probe built on it reports the tool missing, and whatever it guards is skipped without a word. Probe through `RunCommandChecked`, which goes through `sh`, or `std::system` in a test. - A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules//`, one `libcxx--modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot. - The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`. +- The Flatpak carries weston for the tests that set `Test::wayland`: the `libevdev`, `libinput`, `libdisplay-info` and `weston` modules, just before `crafter-build`, so that bumping them rebuilds only them and crafter-build. weston's frontend links the first three whatever the backend, so they ship. weston is configured with its headless backend, its GL renderer and its desktop shell, and with none of its other backends or shells and no Vulkan renderer. libinput is a `git` source pinned by commit, since its 1.32.0 release has no tarball attached. `tests/HeadlessCompositor` stands in a fake compositor, so the suite needs no weston: only a project's own tests that set `Test::wayland` run the real one. - The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib//eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`. - `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`. - `CudaCompile` builds with a real CUDA toolkit whose `lib64` beside `bin/nvcc` holds `libcudart_static.a`, and skips everywhere else, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, or how the CUDA runtime is linked and handed on through `BuildResult::runtimeLibs`, run it in the native loop on a machine with such a toolkit, as Arch's `/opt/cuda` is. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere, and so is whether the `lib64` beside it holds the static runtime. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either. diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.yaml b/packaging/flatpak/net.catcrafts.CrafterBuild.yaml index 6915b89..d3086ad 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.yaml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.yaml @@ -378,6 +378,114 @@ modules: url: https://github.com/KhronosGroup/Vulkan-ValidationLayers/archive/refs/tags/vulkan-sdk-1.4.357.0.tar.gz sha256: 73180b11992a3554e97ebc18e6bf2b45ff9790ded9d87fc526c7bab865d1303f + # weston on its headless backend, the compositor `crafter-build test` starts + # for each test that sets Test::wayland (README, "Tests that open windows"): + # built with the headless backend, the GL renderer, which imports the + # dmabufs a GPU's Vulkan driver presents, and the desktop shell, and with + # none of its other backends or shells and no Vulkan renderer. weston's frontend + # links libinput, libevdev and libdisplay-info whatever the backend, and the + # Sdk has none of them, so they come first; the headless backend never opens + # an input device, so libinput ships without its quirks, udev helpers and + # tools. + - name: libevdev + buildsystem: meson + config-opts: + - -Dtests=disabled + - -Dtools=disabled + - -Ddocumentation=disabled + cleanup: + - /include + - /lib/pkgconfig + sources: + - type: archive + url: https://www.freedesktop.org/software/libevdev/libevdev-1.14.0.tar.xz + sha256: 5a0966c7110648665983848bad696c7acba614a2160d2865d535397101007332 + + - name: libinput + buildsystem: meson + config-opts: + - -Dlibwacom=false + - -Dmtdev=false + - -Ddebug-gui=false + - -Dtests=false + - -Ddocumentation=false + - -Dlua-plugins=disabled + - -Dudev-dir=/app/lib/udev + - -Dzshcompletiondir=no + cleanup: + - /bin + - /include + - /lib/pkgconfig + - /lib/udev + - /libexec + - /share/libinput + sources: + # libinput publishes no release tarball, only the tag. + - type: git + url: https://gitlab.freedesktop.org/libinput/libinput.git + tag: 1.32.0 + commit: 5cf833b572f5a33663888da321dce0ba1abd82a2 + + - name: libdisplay-info + buildsystem: meson + cleanup: + - /bin + - /include + - /lib/pkgconfig + sources: + - type: archive + url: https://gitlab.freedesktop.org/emersion/libdisplay-info/-/releases/0.4.0/downloads/libdisplay-info-0.4.0.tar.xz + sha256: 43b180baa143e2035654759d84e2b2f5ee77d5fe817c423838c7fe59c0d68459 + + - name: weston + buildsystem: meson + config-opts: + # The modules above, never a subproject meson would download. + - --wrap-mode=nodownload + - -Dbackend-drm=false + - -Dbackend-headless=true + - -Dbackend-pipewire=false + - -Dbackend-rdp=false + - -Dbackend-vnc=false + - -Dbackend-wayland=false + - -Dbackend-x11=false + - -Dbackend-default=headless + - -Drenderer-gl=true + - -Drenderer-vulkan=false + - -Dxwayland=false + - -Dsystemd=false + - -Ddeprecated-remoting=false + - -Ddeprecated-pipewire=false + - -Dshell-desktop=true + - -Dshell-ivi=false + - -Dshell-kiosk=false + - -Dshell-lua=false + - -Dcolor-management-lcms=false + - -Dimage-jpeg=false + - -Dimage-webp=false + - -Dtools=[] + - -Ddemo-clients=false + - -Dsimple-clients=[] + - -Dtests=false + - -Ddoc=false + - -Dperfetto=false + cleanup: + - /bin/weston-screenshooter + - /include + - /lib/pkgconfig + - /share/libweston-16 + - /share/man + - /share/pkgconfig + - /share/wayland-sessions + post-install: + - weston --version + - test -f /app/lib/libweston-16/headless-backend.so + - test -f /app/lib/libweston-16/gl-renderer.so + sources: + - type: archive + url: https://gitlab.freedesktop.org/wayland/weston/-/releases/16.0.2/downloads/weston-16.0.2.tar.xz + sha256: 49dd87d18cb229384264d2f69cb5a51f14f61a111e9227bfedb91b3ca8c39643 + - name: crafter-build buildsystem: simple build-options: From fcfac0d9cf563d43a569a49b9471ba5b56cc1f57 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 26 Nov 2026 10:37:59 +0100 Subject: [PATCH 22/27] docs: tests that open windows, and the compositor each one gets The README's Tests section gains "Tests that open windows": a test that sets Test::wayland, or .Wayland() on what AddTest returns, runs with a headless compositor of its own instead of the session's display. It says what crafter-build gives the compositor and the test and what it does afterwards; the default weston command, weston 12 as the first release that takes its --renderer=, and what its renderer and two options are for; how CRAFTER_BUILD_COMPOSITOR, --compositor= and `host` choose another; when the compositor fails the test, how a test that may run without weston is skipped, and where the compositor's output goes; and what a crafter-build that is killed leaves. The CLI examples gain --compositor=host, and examples/tests/README.md's list of the builder's methods gains .Wayland(). --- README.md | 19 +++++++++++++++++++ examples/tests/README.md | 1 + 2 files changed, 20 insertions(+) diff --git a/README.md b/README.md index 0c68e1a..6e8c085 100644 --- a/README.md +++ b/README.md @@ -313,6 +313,7 @@ crafter-build test --target=x86_64-w64-mingw32 # only tests for crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine crafter-build test --jobs=1 # one test at a time crafter-build test --timeout=5 # override per-test timeout +crafter-build test --compositor=host # Wayland tests on this session's display ``` Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed. @@ -375,6 +376,24 @@ cmd: # cmd:wine, cmd:qemu-aarch64, cmd:valgrind, ... Each runner carries a `probe` command (e.g. `which wine`), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (`AllPassed()` returns true on skip-only runs). +### Tests that open windows + +A test that talks to a Wayland compositor sets `Test::wayland`, and every run of it gets a headless compositor of its own instead of your session's display, so the windows it opens through `WAYLAND_DISPLAY` show up there and not on your desktop: + +```cpp +cfg.AddTest("Swapchain").Wayland(); // or, on a Test you build yourself: test.wayland = true; +``` + +Before the test, crafter-build starts the compositor with `XDG_RUNTIME_DIR` set to a directory made for it (in your `XDG_RUNTIME_DIR`, else in `/tmp`) and without `WAYLAND_DISPLAY`, `WAYLAND_SOCKET` or `DISPLAY`, and waits up to 30 s for a `wayland-` socket to appear there. The test then runs with `WAYLAND_DISPLAY` set to that socket's full path and with `DISPLAY` and `WAYLAND_SOCKET` unset; its `XDG_RUNTIME_DIR` stays yours. Afterwards the compositor's process group is sent SIGTERM, what is left of the group SIGKILL once the compositor has ended or 5 s have passed, and the directory is removed. No two tests share a compositor, so tests that run at once cannot cover each other's windows or take each other's focus. + +The compositor is `weston --backend=headless --renderer=gl --no-config --idle-time=0` unless `CRAFTER_BUILD_COMPOSITOR` names another, and `--compositor=` wins over both. The Flatpak ships weston 16.0.2; outside it, install weston 12 or newer, the first release to take `--renderer=`. Its GL renderer takes the GPU buffers (dmabufs) that a GPU's Vulkan driver presents, as Mesa's and NVIDIA's do, and which the headless backend's default, a renderer that draws nothing, and pixman take none of; `--no-config` keeps your `weston.ini` out, and `--idle-time=0` keeps the output from going idle after 5 minutes, which would stop frame callbacks. Another compositor is any command, run through `sh`, that listens on a `wayland-` socket in the `XDG_RUNTIME_DIR` it is given. `host` starts none and gives these tests your own display, to watch what they draw: + +```bash +crafter-build test --compositor=host 'Swapchain*' +``` + +A compositor that ends before it listens, `sh` not finding it included, or does not listen within 30 s fails the test with what it printed. A test that may run where weston is missing declares it with `.Requires("tool:weston")`, and is then skipped there before it is built, as for any tool it declares. When a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to `build/test-logs/.compositor.log`, and the test's output says so, and also when the compositor ended before the test did; what a compositor that did not start printed is in the test's own failure, in `build/test-logs/.log`. A crafter-build that is killed takes its compositors with it; the directories it leaves behind are removed by a test that starts a compositor after they have gone a minute unchanged. + ### Linking the parent project's library A test fixture can depend on the project's own library so it can `import` and exercise its API: diff --git a/examples/tests/README.md b/examples/tests/README.md index 6dcbf5c..8f46338 100644 --- a/examples/tests/README.md +++ b/examples/tests/README.md @@ -37,6 +37,7 @@ builder methods overlay overrides: - `.Dependencies({ &otherCfg, ... })` - `.Path(p)` — rebase the test's source-resolution path - `.LinkFlag(s)` / `.CompileFlag(s)` +- `.Wayland()` — a headless Wayland compositor of the test's own, so that the windows it opens stay off your desktop ([Tests that open windows](../../README.md#tests-that-open-windows)) ## Test conventions From 93f1c8d9b943790aa610a0cafa94ab350a3f3ab1 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:17:28 +0100 Subject: [PATCH 23/27] fix(test): run each test's command with a TMPDIR of its own Tests stage their fixtures under fixed names in the temp directory, fs::temp_directory_path() / "crafter-build-", and two runs at once staged into the same ones: natively every process shares the machine's /tmp, and every sandbox of crafter-build's Flatpak shares the one the app has, whatever checkout it runs in. A test of one run could find what it had staged removed or written over by the same test of the other run, which removes the directory as it starts and stages its copy anew. RunTests now makes a directory for the run in the temp directory, a PrivateDirectory, and runs each test with TMPDIR naming /, so that fs::temp_directory_path() in the test names it and the fixed names are the run's alone. The second test of one name in a run, as two configurations or two targets may each have one, gets -2, so that removing one's directory does not take the other's. RunSingleTest takes the directory as a new last parameter and puts TMPDIR into the env prefix of the test's command, beside a Wayland test's WAYLAND_DISPLAY. env's command is sh, which execs the test's words, as for a Wayland test's: env takes a word with an '=' in it ahead of its command for an assignment, a binary's path among them, and with no command left it printed its environment and exited 0, a pass for a test that never ran. What a test that passes or skips leaves is removed when it ends. What one that fails, crashes or times out leaves is kept for a look, its log says where, as does what is printed of a test that fails or crashes, and the run's directory then outlives the run, unlocked, for a later run to remove a minute after, or, where the run was killed, a minute after its last change to it; PrivateDirectory gains Keep() for that. A test's logs, build/test-logs/.log and .compositor.log, are named as its TMPDIR is, -2 for a later test of one name, so that two failing tests of one name each keep their own, and with it where what each left is kept: with one log for both, the second's was written over the first's. The README's line on the logs says so. The directory is dated as it is let go of, since the removal of abandoned directories goes by its date, which is that of what was last made or removed in it: for the run of a test that fails after a minute, as one that times out at the default 60 s does, a minute old already, and the next run would remove it at once. The removal now reads a directory's date only once it holds the directory's lock: a date read before could be one the holder replaced as it let go. The directory is the run's, not a pass's: every pass of a sweep over targets shares it, so it is made and its surroundings swept once, and let go of once the last pass is done. A pass that made one of its own would have made it once the passes before had let go of theirs, and making it would have removed any of those that had not changed for a minute: a kept one, after a pass of that long, while its test's output said where it was. RunTests becomes the wrapper that holds the run's directory around RunTestsWith, the passes it recurses into, and the directory is kept the moment a test keeps something in it, by the worker that ran the test, so that a later pass that throws, as one does for a target whose runner CRAFTER_BUILD_RUNNER_ gives wrong, or a worker that cannot be started does not take it with it; Keep() may be called from several workers at once. TMPDIR reaches the test where its runner hands it on, as running it directly and qemu-user do. Under wine a Windows test does not get TMPDIR, and takes the Wine prefix's TMP, TEMP and temp directory, and wasmtime gives a test no environment at all; RunSingleTest's comment says so. A test under `host` gets its TMPDIR as any test does, so that comment and HostDisplay's now say that `host` leaves the test the display, not the whole environment, as it is. In the runner rather than in each of the 74 tests whose main.cpp uses the temp directory at this commit: a project's own tests are covered the same way, where their runner hands them TMPDIR. Of the 74 only SysrootStdModule has to change. It builds against a sysroot it stages there, and the std module's cache directory is keyed on the sysroot's path, which is a new one every run now, so every run left one more directory, with its lock, in the real cache; it keeps its cache in its scratch directory now, as the tests that have crafter-build fetch a repository they stage do. AGENTS.template.md says what changes for the tests: HostFlatpak, whose /tmp is no longer the temp directory a test is given, is a second test that writes elsewhere, and under `crafter-build test` a staged copy goes with the test's TMPDIR rather than at the test's next run. --- AGENTS.template.md | 4 +- README.md | 4 +- implementations/Crafter.Build-Platform.cpp | 20 +++- implementations/Crafter.Build-Test.cpp | 102 ++++++++++++++++++--- interfaces/Crafter.Build-Platform.cppm | 20 ++-- interfaces/Crafter.Build-Test.cppm | 13 ++- tests/SysrootStdModule/main.cpp | 10 +- 7 files changed, 140 insertions(+), 33 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index a78394f..0865356 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -90,7 +90,7 @@ Conventions the existing tests follow: - Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape. - Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it. - Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout. -- Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"` and removes it on the next run. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. +- Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"`, after removing what an earlier run left there, which matters where the test runs by hand: under `crafter-build test` the copy is in the test's own `TMPDIR`, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. - Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. - Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. - `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first. @@ -167,7 +167,7 @@ These were decided deliberately. Do not undo them without the maintainer's say-s - The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. - crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. - CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. -- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. One test writes elsewhere, `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up. It removes what it makes, and a later run removes what a killed one left once that has not changed for a minute (`PrivateDirectory`). +- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make: `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up, and a later run removes what a killed run of it left once that has not changed for a minute (`PrivateDirectory`); and `tests/HostFlatpak`, which in the Flatpak makes its two projects in the sandbox's `/tmp`, the place it asks the host about, under fixed names, so that its next run that makes them removes what a killed one left. ## CI and publishing diff --git a/README.md b/README.md index 6e8c085..ec26f89 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,7 @@ Test conventions: - **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH"). - Each test runs in its own subprocess — a segfault doesn't take the runner down. - Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()` tests (`--jobs=`). The steps of their builds share one limit, a build's: as many at once as there are hardware threads. -- Stdout+stderr is captured and printed atomically on completion. Failed/crashed/timed-out tests also write to `build/test-logs/.log`. +- Stdout+stderr is captured and printed atomically on completion. A test that fails, crashes or times out once it is built also writes what it printed, and what crafter-build said of it, to `build/test-logs/.log`, when that is anything, and, where it sets `Test::wayland` and ran, what its compositor printed, if anything, to `.compositor.log` beside it (what a compositor that did not start printed is in `.log`); one that failed to build, or did not get that far, writes neither. `` is the test's name with `-2`, `-3` and on after it where the run has given that name out already, as two configurations or two targets may each declare a test of one name. - A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run. CLI: @@ -392,7 +392,7 @@ The compositor is `weston --backend=headless --renderer=gl --no-config --idle-ti crafter-build test --compositor=host 'Swapchain*' ``` -A compositor that ends before it listens, `sh` not finding it included, or does not listen within 30 s fails the test with what it printed. A test that may run where weston is missing declares it with `.Requires("tool:weston")`, and is then skipped there before it is built, as for any tool it declares. When a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to `build/test-logs/.compositor.log`, and the test's output says so, and also when the compositor ended before the test did; what a compositor that did not start printed is in the test's own failure, in `build/test-logs/.log`. A crafter-build that is killed takes its compositors with it; the directories it leaves behind are removed by a test that starts a compositor after they have gone a minute unchanged. +A compositor that ends before it listens, `sh` not finding it included, or does not listen within 30 s fails the test with what it printed. A test that may run where weston is missing declares it with `.Requires("tool:weston")`, and is then skipped there before it is built, as for any tool it declares. When a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to `build/test-logs/.compositor.log`, named as the test's own log is, and the test's output says so, and also when the compositor ended before the test did; what a compositor that did not start printed is in the test's own failure, in `build/test-logs/.log`. A crafter-build that is killed takes its compositors with it; the directories it leaves behind are removed by a test that starts a compositor after they have gone a minute unchanged. ### Linking the parent project's library diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index c62cbd3..58ddefe 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -990,12 +990,16 @@ namespace { for (const fs::directory_entry& entry : fs::directory_iterator(parent, ec)) { std::error_code entryError; if (!entry.path().filename().string().starts_with(prefix) || !entry.is_directory(entryError) || entry.is_symlink(entryError)) continue; - const auto changed = fs::last_write_time(entry.path(), entryError); - if (entryError || now - changed < std::chrono::minutes(1)) continue; // Another user's directory does not open: mkdtemp made it 0700. const std::int32_t held = ::open(entry.path().c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (held < 0) continue; - if (::flock(held, LOCK_EX | LOCK_NB) == 0) fs::remove_all(entry.path(), entryError); + // Dated only once it is held: a directory that is kept is dated + // by its holder just before it lets go of it, so a date read + // before the lock can be one the holder has replaced since. + if (::flock(held, LOCK_EX | LOCK_NB) == 0) { + const auto changed = fs::last_write_time(entry.path(), entryError); + if (!entryError && now - changed >= std::chrono::minutes(1)) fs::remove_all(entry.path(), entryError); + } ::close(held); } } @@ -1022,7 +1026,15 @@ Crafter::PrivateDirectory::PrivateDirectory(const fs::path& parent, std::string_ Crafter::PrivateDirectory::~PrivateDirectory() { std::error_code ec; - fs::remove_all(path, ec); + if (kept) { + // Dated now, while it is still held: its date is that of what was + // last made or removed in it, which may be long before, as for the + // run of a test that failed after minutes, and a directory nobody + // holds is removed a minute after its date. + fs::last_write_time(path, fs::file_time_type::clock::now(), ec); + } else { + fs::remove_all(path, ec); + } if (fd >= 0) ::close(fd); } diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index 2ef3bad..3160dd9 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -86,7 +86,8 @@ namespace { // callbacks. constexpr std::string_view DefaultCompositor = "weston --backend=headless --renderer=gl --no-config --idle-time=0"; // The compositor named for none of the test's own: the test gets the - // environment crafter-build has, display included, to watch its windows. + // display crafter-build has, to watch its windows, and the TMPDIR it is + // given, as any test does. constexpr std::string_view HostDisplay = "host"; // How long a compositor may take to listen. weston needs a fraction of a // second; this is for a machine running a test on every hardware thread. @@ -324,7 +325,7 @@ TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) { return fallback; } -TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride) { +TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride, const fs::path& temporaryDirectory) { TestResult result; result.name = test.config.name; @@ -342,6 +343,12 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std: cmd = Substitute(test.runner.exec, ph); } + // What `env` changes for the test, its -u options and its assignments, + // which it takes in that order. + std::string unset; + std::string set; + if (!temporaryDirectory.empty()) set += std::format(" TMPDIR={}", ShellQuote(temporaryDirectory.string())); + // The test's own compositor, which no other test shares, so that no // two tests cover each other's windows or take each other's focus. Its // directory goes after it: declared first, it is destroyed last. @@ -391,12 +398,15 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std: if (ended == 127) result.output += "install weston, name another compositor with CRAFTER_BUILD_COMPOSITOR or --compositor=, or skip a test that may run without it with requires_, tool:weston for weston\n"; return result; } - // env's command is sh, which execs the test's words as they are: env - // takes every word with an '=' in it ahead of its command for an - // assignment, the binary's path among them where it has one (a test - // named a=b), and that test never ran. - cmd = std::format("env -u DISPLAY -u WAYLAND_SOCKET WAYLAND_DISPLAY={} sh -c 'exec \"$@\"' sh {}", ShellQuote(socket->string()), cmd); + unset += " -u DISPLAY -u WAYLAND_SOCKET"; + set += std::format(" WAYLAND_DISPLAY={}", ShellQuote(socket->string())); } + // env's command is sh, which execs the test's words as they are: env + // takes every word with an '=' in it ahead of its command for an + // assignment, the binary's path among them where it has one (a test + // named a=b), and with no command left it printed its environment and + // exited 0, a pass for a test that never ran. + if (!unset.empty() || !set.empty()) cmd = std::format("env{}{} sh -c 'exec \"$@\"' sh {}", unset, set, cmd); auto start = std::chrono::steady_clock::now(); CommandResult r = RunCommandWithTimeout(cmd, timeout); @@ -591,14 +601,30 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& return RunTests(std::span(one), opts, projectArgs); } -TestSummary Crafter::RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs) { +namespace { + // The directory of one run of `crafter-build test`, in the temp + // directory, which each test's TMPDIR is made in, and the names given + // out in it. Every pass of a sweep over targets shares it: the first + // that runs a test makes it, and RunTests lets go of it once the last + // pass is done. A pass that made one of its own made it once the + // passes before had let go of theirs, and making it removed any of + // those that had not changed for a minute: a kept one after a pass + // that long, while its test's output said where it was kept. + struct RunTemporaries { + std::optional directory; + std::set used; + }; +} + +// RunTests, with the run's temporaries. +static TestSummary RunTestsWith(std::span configurations, const RunTestsOptions& opts, std::span projectArgs, RunTemporaries& run) { // Each of them once, however often the list names it: named twice, a // configuration would have each of its tests built twice at once. std::vector distinct; for (Configuration* cfg : configurations) { if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg); } - if (distinct.size() != configurations.size()) return RunTests(distinct, opts, projectArgs); + if (distinct.size() != configurations.size()) return RunTestsWith(distinct, opts, projectArgs, run); for (Configuration* cfg : configurations) UnpackageTests(*cfg); // Multi-target sweep: when no --target= was given, the run covers every @@ -625,7 +651,7 @@ TestSummary Crafter::RunTests(std::span configurations, co Progress::Clear(); std::println("\n=== target: {} ===", target); } - TestSummary s = RunTests(configurations, perTarget, projectArgs); + TestSummary s = RunTestsWith(configurations, perTarget, projectArgs, run); aggregate.passed += s.passed; aggregate.failed += s.failed; aggregate.crashed += s.crashed; @@ -705,6 +731,28 @@ TestSummary Crafter::RunTests(std::span configurations, co } } + // Each test runs with TMPDIR naming a directory of its own, /, + // in the run's directory in the temp directory (RunTemporaries), so that + // fs::temp_directory_path() in the test names it, where its runner hands + // it TMPDIR (RunSingleTest). Tests stage their fixtures under + // fixed names in it (crafter-build-), and two runs at once staged + // into the same ones: natively every process shares the machine's + // /tmp, and every sandbox of crafter-build's Flatpak shares the one the + // app has. A second test of one name in the run, as two configurations + // or two targets may each have one, gets -2. What a test that + // passes or skips leaves there is removed when it ends; what one that + // fails, crashes or times out leaves is kept, its output says where, and + // so is the run's directory, for a later run to remove a minute after + // this one ends, or after its last change to it where this one is + // killed (PrivateDirectory::Keep). + if (!run.directory) run.directory.emplace(fs::temp_directory_path(), "crafter-build-tests-"); + std::vector temporary(filtered.size()); + for (std::size_t i = 0; i < filtered.size(); ++i) { + std::string name = filtered[i]->config.name; + for (std::int32_t n = 2; !run.used.insert(name).second; ++n) name = std::format("{}-{}", filtered[i]->config.name, n); + temporary[i] = run.directory->path / name; + } + std::int32_t jobs = opts.jobs > 0 ? opts.jobs : std::max(1u, std::thread::hardware_concurrency()); @@ -825,24 +873,47 @@ TestSummary Crafter::RunTests(std::span configurations, co // triple and nothing for wasm, so every wasm test was handed to // wasmtime without the .wasm it was linked as. fs::path binary = ExpectedOutput(t.config); + std::error_code temporaryError; + fs::create_directories(temporary[i], temporaryError); try { - r = RunSingleTest(t, binary, timeout, opts.compositorOverride); + if (temporaryError) throw std::runtime_error(std::format("cannot make the test's TMPDIR {}: {}", temporary[i].string(), temporaryError.message())); + r = RunSingleTest(t, binary, timeout, opts.compositorOverride, temporary[i]); } catch (const std::exception& e) { r.outcome = TestOutcome::Fail; r.output = std::format("runner threw: {}", e.what()); r.exitCode = -1; } + // The logs are named as the test's TMPDIR is, -2 for a later + // test of one name in the run, so that each has its own: with one + // for both, the second's was written over the first's, and with it + // where what the first left is kept. + const std::string logName = temporary[i].filename().string(); // Beside the test's own log rather than in it: weston prints some // 70 lines starting up, which would bury what the test said. if (!r.compositorLog.empty()) { - if (const std::optional log = WriteLog(owners[i]->path, std::format("{}.compositor", r.name), r.compositorLog)) { + if (const std::optional log = WriteLog(owners[i]->path, std::format("{}.compositor", logName), r.compositorLog)) { if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n'); r.output += std::format("the headless compositor's output is in {}\n", log->string()); } } + if (!temporaryError) { + std::error_code ec; + const bool failed = r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped; + if (failed && !fs::is_empty(temporary[i], ec) && !ec) { + // Kept at once, so that it stays whatever ends the run: + // a later pass that throws, as one does for a target whose + // runner CRAFTER_BUILD_RUNNER_ gives wrong, or a worker + // that cannot be started unwinds past the end of RunTests. + run.directory->Keep(); + if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n'); + r.output += std::format("what it left in its TMPDIR is kept in {}\n", temporary[i].string()); + } else { + fs::remove_all(temporary[i], ec); + } + } if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) { - WriteLog(owners[i]->path, r.name, r.output); + WriteLog(owners[i]->path, logName, r.output); } { @@ -888,3 +959,8 @@ TestSummary Crafter::RunTests(std::span configurations, co return summary; } + +TestSummary Crafter::RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs) { + RunTemporaries run; + return RunTestsWith(configurations, opts, projectArgs, run); +} diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index c7abe00..98f97a5 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -95,23 +95,29 @@ namespace Crafter { }; // A new directory in `parent`, named `prefix` and six random characters, // that only this user may enter (mkdtemp), removed with everything in it - // when this ends. A process that is killed runs no destructor, so this - // also holds an flock on the directory, which the OS drops with the - // process, and making one removes the directories of `prefix` in - // `parent` that nobody holds and that have not changed for a minute: - // left behind by a process that is gone. The minute covers one that is - // being made at that moment, between mkdtemp and its lock. Throws when - // the directory cannot be made. + // when this ends, unless it is kept. A process that is killed runs no + // destructor, so this also holds an flock on the directory, which the OS + // drops with the process, and making one removes the directories of + // `prefix` in `parent` that nobody holds and that have not changed for a + // minute: left behind by a process that is gone, or kept. The minute + // covers one that is being made at that moment, between mkdtemp and its + // lock. Throws when the directory cannot be made. // Exported for the tests that make a directory of their own outside the // temp directory. export class PrivateDirectory { std::int32_t fd = -1; + std::atomic kept{false}; public: const fs::path path; PrivateDirectory(const fs::path& parent, std::string_view prefix); ~PrivateDirectory(); PrivateDirectory(const PrivateDirectory&) = delete; PrivateDirectory& operator=(const PrivateDirectory&) = delete; + // The destructor leaves the directory where it is, unlocked and + // dated as it lets go of it, so that what is in it can be looked at + // for a minute at least, until it is removed as one that nobody + // holds. Several threads may call it at once. + void Keep() { kept = true; } }; // The link flags that record `dir` as a run path, with -Xlinker rather // than -Wl,: clang splits a -Wl, value at every comma, and `dir` may be a diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index 7c51b2e..32acd87 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -107,6 +107,12 @@ export namespace Crafter { TestSummary RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs = {}); // Runs `binary` as `test` with its runner, its arguments and `timeout`, // and reads the outcome from how it ended (exit 0 passes, 77 skips). + // With a `temporaryDirectory` the test's command runs with TMPDIR naming + // it; RunTests gives each test a directory of its own, made for the run. + // fs::temp_directory_path() in the test names it where the runner hands + // the test TMPDIR, as running it directly and qemu-user do. Under wine a + // Windows test does not get TMPDIR, and takes the Wine prefix's TMP, TEMP + // and temp directory; wasmtime gives a test no environment at all. // // When the test sets Test::wayland, a compositor is started for it // first: `compositorOverride` when it holds a command, else the one @@ -123,9 +129,10 @@ export namespace Crafter { // not finding it included, or does not listen within 30 s fails the // test, with what it printed; a test that may run where its compositor // is missing declares it in requires_ (tool:weston), which RunTests - // checks before the build. `host` starts nothing and runs the test with - // this process's environment as it is. - TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride = std::nullopt); + // checks before the build. `host` starts nothing and leaves the test the + // display this process has, its WAYLAND_DISPLAY, WAYLAND_SOCKET, DISPLAY + // and XDG_RUNTIME_DIR; a `temporaryDirectory` is its TMPDIR all the same. + TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride = std::nullopt, const std::filesystem::path& temporaryDirectory = {}); // The configurations of the project crafter-build was pointed at, by // name. Run() hands SetParentProject what the project file returned, diff --git a/tests/SysrootStdModule/main.cpp b/tests/SysrootStdModule/main.cpp index e5e984f..9a2d5e5 100644 --- a/tests/SysrootStdModule/main.cpp +++ b/tests/SysrootStdModule/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; namespace fs = std::filesystem; @@ -52,6 +53,11 @@ int main() { std::error_code ec; fs::remove_all(scratch, ec); fs::create_directories(scratch); + // The cache the build below makes its std module's directory in, which + // is keyed on the sysroot's path: one under the temp directory, which + // is a new one every run of the suite, so the real cache would keep one + // more directory each run. Set while this is the only thread. + setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1); { StageHeaders(scratch / "headers", 230102); @@ -126,8 +132,8 @@ int main() { { // End to end with the real toolchain: a sysroot on a libc++ release // that does not exist fails the build with the one-line explanation - // before clang is run. The target is the host's so the std PCM cache - // directory is the one every other test already uses. + // before clang is run, for the host's target. The std module's cache + // directory is made in the scratch cache (above). const Toolchain& real = GetToolchain(); Check(real.libcxxVersion != 0, "the running toolchain's libc++ release is read from its headers"); From ab8935826d297c732cf022e745a9aee6bf0a86ad Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:17:35 +0100 Subject: [PATCH 24/27] test: what a test leaves in its TMPDIR, kept when it fails, else gone TestTemporaryDirectory runs a probe through RunTests that records the TMPDIR it was given and the directory fs::temp_directory_path() names, leaves a file there and exits as it is told. Two configurations each declare a passing test named probe, built differently so that the run does not refuse them, and the second also a failing one and one for another target, the host's own triple without its vendor and with x32 after it, which is never the host's and makes a second pass after the host's, and is skipped before it is built. The run takes one test at a time, so the failing one comes last in the host's pass, and it dates the run's directory, and a directory beside it that looks like one a run let go of, two minutes back before it fails, as a test that ran that long leaves them. Each test's fs::temp_directory_path() is the TMPDIR it was given: /, in a directory made for the run in the temp directory, and probe-2 for the second probe. What the passing tests left is removed; what the failing one left is kept, named in its output and its log, and so is the run's directory. A second run gets a directory of its own, removes it since every test passed, and leaves the first run's alone; a third, once that one is dated past the minute, removes it. The other target's pass makes no directory of its own: the one dated back beside the run's is still there when the run ends. A fourth run, whose pass for the other target throws, as one does where CRAFTER_BUILD_RUNNER_ names that target's runner wrong, keeps what its first pass kept. The runs make their directories in a temp directory the test makes for them and names with TMPDIR. The test removes only its own scratch directory, which holds that one, and the fixture's bin/ and build/, and dates a directory a probe reports only when it is a run's directory in that temp directory. HeadlessCompositor checks that a test that sets wayland and is given a TMPDIR runs with both: the TMPDIR it is given and its compositor's display alone, and that one under `host` and given a TMPDIR has it beside the session's display. Two failing tests of one name each have a log of their own, twin.log and twin-2.log, that says where what each left is kept. RunSingleTestExit runs a script whose path has an '=' in it, given a TMPDIR, which has to run and whose exit decides the outcome. Without TMPDIR on the test's command, 13 of TestTemporaryDirectory's checks fail; with a test's log named after the test alone, the two on the logs of the tests of one name do; without the date a kept directory gets as it is let go of, the one on the second run leaving the first run's alone does; with a directory of its own for a later pass, beside the run's, the one on the other target's pass does; and with the directory kept only once RunTests returns, the one on the fourth run does. With the test's own words as env's command, the two of RunSingleTestExit on the script whose path has an '=' fail. --- project.cpp | 1 + tests/HeadlessCompositor/main.cpp | 32 ++- tests/RunSingleTestExit/main.cpp | 19 ++ .../fixture/tests/probe/main.cpp | 30 +++ tests/TestTemporaryDirectory/main.cpp | 247 ++++++++++++++++++ 5 files changed, 326 insertions(+), 3 deletions(-) create mode 100644 tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp create mode 100644 tests/TestTemporaryDirectory/main.cpp diff --git a/project.cpp b/project.cpp index be6f693..eb8f9ab 100644 --- a/project.cpp +++ b/project.cpp @@ -315,6 +315,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("TestTemporaryDirectory").Dependencies({ CrafterBuildLib.get() }); // Loading a project file dlopens the project.so compiled from it, // which references Crafter:: symbols (HostTarget, Configuration // ctors) that have to be visible from the test exe — same wiring diff --git a/tests/HeadlessCompositor/main.cpp b/tests/HeadlessCompositor/main.cpp index 807df30..e14ae12 100644 --- a/tests/HeadlessCompositor/main.cpp +++ b/tests/HeadlessCompositor/main.cpp @@ -29,7 +29,8 @@ using namespace std::chrono_literals; // leaves goes the next time one is made. A test that does not set it, or a // run that names `host`, keeps the session's display. A test with no time // limit gives its compositor none, and one whose binary's path holds an '=' -// runs as any other. +// runs as any other. One that is given a TMPDIR as well, as RunTests gives +// every test one, runs with both. // // This binary plays every part. Without arguments it is the driver; the // harness starts it again as the compositor, which listens on a wayland-7 @@ -63,8 +64,8 @@ namespace { return value != nullptr ? std::string(value) : std::string(Unset); } - // The variables of a Wayland session. - constexpr std::array SessionVariables = { "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY", "XDG_RUNTIME_DIR" }; + // The variables of a Wayland session, and the TMPDIR a test is given. + constexpr std::array SessionVariables = { "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY", "XDG_RUNTIME_DIR", "TMPDIR" }; void WriteFile(const fs::path& file, std::string_view content) { std::ofstream(file, std::ios::binary) << content; @@ -360,6 +361,31 @@ int main(int argc, char* argv[]) { Check(!directory.empty() && !fs::exists(directory), "which is removed afterwards"); } + // A test that sets wayland and is given a TMPDIR: the env prefix takes + // the TMPDIR beside what it unsets and sets for the display. + { + const fs::path state = stateDir("tmpdir"); + const fs::path given = stateDir("tmpdir-given"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state), given); + Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland and is given a TMPDIR passes: {}", r.output)); + std::map client = ReadEnvironment(state / "client.env"); + Check(client["TMPDIR"] == given.string(), std::format("and runs with that TMPDIR: {}", client["TMPDIR"])); + Check(client["WAYLAND_DISPLAY"] == ReadFile(state / "compositor.listening") && client["DISPLAY"] == Unset && client["WAYLAND_SOCKET"] == Unset, + std::format("and with its compositor's display alone: {}", client["WAYLAND_DISPLAY"])); + } + + // Under `host`, a test given a TMPDIR runs with it, beside the + // session's display. + { + const fs::path state = stateDir("host-tmpdir"); + const fs::path given = stateDir("host-tmpdir-given"); + const TestResult r = RunSingleTest(MakeTest(true, "--env", state), self, 10s, "host", given); + std::map client = ReadEnvironment(state / "client.env"); + Check(r.outcome == TestOutcome::Pass && client["TMPDIR"] == given.string(), std::format("under `host` a test given a TMPDIR runs with it: {}", client["TMPDIR"])); + Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243", + "and with the session's display"); + } + { const fs::path state = stateDir("without"); const TestResult r = RunSingleTest(MakeTest(false, "--env", state), self, 10s, FakeCompositorCommand(self, state)); diff --git a/tests/RunSingleTestExit/main.cpp b/tests/RunSingleTestExit/main.cpp index 34f429f..970fde8 100644 --- a/tests/RunSingleTestExit/main.cpp +++ b/tests/RunSingleTestExit/main.cpp @@ -34,6 +34,8 @@ namespace { // 0 -> Pass // 77 -> Skipped (autoconf convention) // anything else -> Fail +// and that a binary whose path has an '=' in it runs, with a TMPDIR as +// RunTests gives it. int main() { fs::path dir = fs::temp_directory_path() / "crafter-build-run-single-test"; std::error_code ec; @@ -76,6 +78,23 @@ int main() { Check(r.outcome == TestOutcome::Pass, "Cmd-prefixed exit 0 -> Pass"); } + // A test whose binary's path has an '=' in it, given a TMPDIR, as + // RunTests gives every test one: env, which sets the TMPDIR, took that + // path for an assignment and, with no command left, exited 0, a pass + // for a test that never ran. + { + const fs::path equals = dir / "a=b"; + fs::create_directories(equals); + fs::create_directories(dir / "tmpdir"); + const fs::path marker = dir / "a=b-ran"; + const fs::path script = equals / "marker.sh"; + std::ofstream(script) << std::format("#!/bin/sh\necho ran > '{}'\nexit 3\n", marker.string()); + fs::permissions(script, fs::perms::owner_all, fs::perm_options::replace); + TestResult r = RunSingleTest(t, script, std::chrono::seconds(5), std::nullopt, dir / "tmpdir"); + Check(fs::exists(marker), "a test whose binary's path has an '=' in it runs"); + Check(r.outcome == TestOutcome::Fail && r.exitCode == 3, std::format("and its exit decides the outcome, got {}", r.exitCode)); + } + fs::remove_all(dir, ec); if (Failures > 0) { diff --git a/tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp b/tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp new file mode 100644 index 0000000..bc591ae --- /dev/null +++ b/tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +namespace fs = std::filesystem; + +// Writes the TMPDIR it was given and the directory fs::temp_directory_path() +// names to the file its first argument names, leaves a file in that +// directory, and exits with the status its second argument gives. With a +// third, `ran-long`, it first dates the run's directory, which holds its own, +// and every other crafter-build-tests-* directory beside that one two minutes +// back, as a test that ran that long leaves them; only when its own is in a +// run's directory. +int main(int argc, char* argv[]) { + if (argc != 3 && argc != 4) return 2; + const bool ranLong = argc == 4; + if (ranLong && std::string_view(argv[3]) != "ran-long") return 2; + const char* given = std::getenv("TMPDIR"); + const fs::path temporary = fs::temp_directory_path(); + std::ofstream(fs::path(argv[1])) << std::format("{}\n{}\n", given != nullptr ? given : "", temporary.string()); + std::ofstream(temporary / "left-behind") << "staged\n"; + if (ranLong && temporary.parent_path().filename().string().starts_with("crafter-build-tests-")) { + const auto then = fs::file_time_type::clock::now() - std::chrono::minutes(2); + std::error_code ec; + for (const fs::directory_entry& entry : fs::directory_iterator(temporary.parent_path().parent_path(), ec)) { + if (entry.path().filename().string().starts_with("crafter-build-tests-")) fs::last_write_time(entry.path(), then, ec); + } + } + return std::stoi(argv[2]); +} diff --git a/tests/TestTemporaryDirectory/main.cpp b/tests/TestTemporaryDirectory/main.cpp new file mode 100644 index 0000000..d58c395 --- /dev/null +++ b/tests/TestTemporaryDirectory/main.cpp @@ -0,0 +1,247 @@ +// 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; + +// Each test runs with TMPDIR naming a directory of its own, /, in +// a directory RunTests makes for the run in the temp directory. Tests stage +// their fixtures under fixed names in fs::temp_directory_path(), and two runs +// at once used to share them, as every run does the machine's /tmp, and in +// crafter-build's Flatpak every sandbox the app's: one run's staged copy was +// written over or removed by the other's, and its test failed. The second +// test of one name in a run, from another configuration, gets -2. What +// a passing test leaves is removed when it ends, and so is the run's +// directory once every test passed; what a failing test leaves is kept, its +// output says where, and the run's directory with it, which a later run +// removes once a minute has passed since the run ended, and one that comes +// sooner leaves alone. That holds when the failing test ran for minutes, so +// that the run's directory had last changed long before the run ended: +// going by that change alone, the next run removed it at once. And one +// directory serves the run, every pass of its sweep over targets: a pass +// that made one of its own made it once the passes before had let go of +// theirs, and making it removed any of those that had not changed for a +// minute, a kept one after a pass that long among them. It is kept the +// moment a test keeps something in it, so that a later pass that throws, as +// one for a target whose runner is given wrong does, does not take it with +// it. Two failing tests of one name each have a log of their own, named as +// their TMPDIRs are, which says where what each left is kept. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // The two lines the probe recorded: the TMPDIR it was given, and the + // directory fs::temp_directory_path() named in it. + std::pair Recorded(const fs::path& file) { + std::ifstream in(file); + std::pair lines; + std::getline(in, lines.first); + std::getline(in, lines.second); + return lines; + } + + // A test of tests/probe/main.cpp, by the name given, with the arguments + // given, which that file describes. + Test& AddProbe(Configuration& owner, std::string_view name, std::vector args, bool second = false) { + Test test; + Configuration& c = test.config; + c.path = "./"; + c.name = name; + c.outputName = name; + c.target = HostTarget(); + c.type = ConfigurationType::Executable; + // Compiled otherwise than the first configuration's test of the same + // name, so that the two are not built into one directory, which the + // run refuses. + if (second) c.defines.push_back({"SECOND_PROBE", ""}); + std::array ifaces = {}; + std::array impls = { "tests/probe/main" }; + c.GetInterfacesAndImplementations(ifaces, impls); + test.args = std::move(args); + owner.tests.push_back(std::move(test)); + return owner.tests.back(); + } + + const TestResult* Find(const TestSummary& summary, std::string_view name) { + for (const TestResult& result : summary.results) { + if (result.name == name) return &result; + } + return nullptr; + } +} + +int main() { + // The runs below make their directories in a temp directory of this + // test's own, which TMPDIR names from here on, set while this is the + // only thread. What the test dates and removes is then in a directory it + // made, even where RunTests gives a probe no TMPDIR and the probe + // reports this test's own. + const fs::path staged = fs::temp_directory_path() / "crafter-build-test-temporary-directory"; + std::error_code ec; + fs::remove_all(staged, ec); + const fs::path records = staged / "records"; + const fs::path temp = staged / "runs"; + fs::create_directories(records); + fs::create_directories(temp); + setenv("TMPDIR", temp.c_str(), 1); + + // As a directory a run let go of looks, made a moment ago, so that the + // run's first look at the temp directory leaves it, and dated two + // minutes back by the failing probe during the first pass: one more pass + // that made a directory of its own would remove it, as it would a kept + // one after a pass of a minute. + const fs::path planted = temp / "crafter-build-tests-planted"; + fs::create_directories(planted); + + // AddProbe resolves tests/probe/main.cpp against the working directory, + // and the tests' outputs land in the fixture's own bin/ and build/. + fs::current_path(fs::current_path() / "tests" / "TestTemporaryDirectory" / "fixture"); + fs::remove_all("bin", ec); + fs::remove_all("build", ec); + + // One test at a time, in the order declared, so that the failing test + // is the last of the host's pass to make or remove anything in the run's + // directory: its own directory there, just before it starts. It then + // dates the run's directory two minutes back before it fails, as a test + // that ran that long leaves it. A test for another target makes a second + // pass, after the host's: the host's own triple, without its vendor, + // with x32 after it, x86_64-linux-gnux32 on an x86_64 glibc host, which + // is never the host's and sorts right after it. It is skipped before it + // is built. + const std::string otherTarget = std::format("{}x32", NormalizeTarget(HostTarget())); + Configuration first; + first.path = "./"; + first.name = "first"; + first.outputName = "first"; + first.target = HostTarget(); + AddProbe(first, "probe", { (records / "first-probe").string(), "0" }); + Configuration second; + second.path = "./"; + second.name = "second"; + second.outputName = "second"; + second.target = HostTarget(); + AddProbe(second, "probe", { (records / "second-probe").string(), "0" }, true); + AddProbe(second, "failing", { (records / "failing").string(), "1", "ran-long" }); + Test& elsewhere = AddProbe(second, "elsewhere", { (records / "elsewhere").string(), "0" }); + elsewhere.config.target = otherTarget; + elsewhere.requires_ = { "tool:crafter-build-no-such-tool" }; + std::array both = { &first, &second }; + RunTestsOptions serial; + serial.jobs = 1; + + const TestSummary run = RunTests(both, serial); + Check(run.passed == 2 && run.failed == 1 && run.skipped == 1, std::format("the run has two passes, one failure and one skip, got {}, {} and {}", run.passed, run.failed, run.skipped)); + Check(fs::is_directory(planted, ec), "the pass for the other target makes no directory of its own, which would have removed what the first pass left a minute old"); + + const auto [firstGiven, firstSeen] = Recorded(records / "first-probe"); + const auto [secondGiven, secondSeen] = Recorded(records / "second-probe"); + const auto [failingGiven, failingSeen] = Recorded(records / "failing"); + const fs::path directory = fs::path(firstGiven).parent_path(); + Check(firstGiven == firstSeen && secondGiven == secondSeen && failingGiven == failingSeen, + std::format("each test's fs::temp_directory_path() is the TMPDIR it was given: {} {} {}", firstSeen, secondSeen, failingSeen)); + const bool madeForRun = fs::equivalent(directory.parent_path(), temp, ec) && directory.filename().string().starts_with("crafter-build-tests-"); + Check(madeForRun, std::format("the run's directory is one made for it in the temp directory: {}", directory.string())); + Check(fs::path(firstGiven) == directory / "probe", std::format("a test's TMPDIR is named after it: {}", firstGiven)); + Check(fs::path(secondGiven) == directory / "probe-2", std::format("the second test of that name gets probe-2: {}", secondGiven)); + Check(fs::path(failingGiven) == directory / "failing", std::format("and every test of the run gets one in the same run directory: {}", failingGiven)); + + Check(!fs::exists(directory / "probe") && !fs::exists(directory / "probe-2"), "what a passing test left is removed"); + Check(fs::exists(directory / "failing" / "left-behind"), "what a failing test left is kept"); + const TestResult* failed = Find(run, "failing"); + Check(failed != nullptr && failed->output.contains((directory / "failing").string()), "and the failing test's output says where"); + const std::string log = [] { + std::ifstream in(fs::path("build") / "test-logs" / "failing.log"); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + }(); + Check(log.contains((directory / "failing").string()), "and so does its log"); + + // A run straight after leaves the failed run's directory alone, though + // the failing test dated it two minutes back; one that comes when it has + // not changed for a minute removes it. + RunTestsOptions passing; + passing.globs = { "probe" }; + std::array justFirst = { &first }; + const TestSummary again = RunTests(justFirst, passing); + Check(again.passed == 1 && again.failed == 0, std::format("the probe passes again, got {} passed, {} failed", again.passed, again.failed)); + const fs::path againDirectory = fs::path(Recorded(records / "first-probe").first).parent_path(); + Check(againDirectory != directory && fs::equivalent(againDirectory.parent_path(), temp, ec), std::format("a second run gets a directory of its own: {}", againDirectory.string())); + Check(!fs::exists(againDirectory), "and removes it when every test passed"); + Check(fs::exists(directory / "failing" / "left-behind"), "the failed run's directory outlives a run that comes at once, though its last test ran long"); + + // Only the failed run's directory is dated, and not a directory a probe + // reported that is not one: that check has failed already. + if (madeForRun) { + fs::last_write_time(directory, fs::file_time_type::clock::now() - std::chrono::minutes(2), ec); + const TestSummary later = RunTests(justFirst, passing); + Check(later.passed == 1, "the probe passes a third time"); + Check(!fs::exists(directory), "a later run removes the failed run's directory once it has not changed for a minute"); + } + + // A run whose later pass throws, as one does where + // CRAFTER_BUILD_RUNNER_ gives the other target's runner wrong, + // keeps what its first pass kept all the same: the failing test's output + // has said where it is. Set while this is the only thread, under the + // name FromEnv reads, '-' and '.' made '_'. + std::string runnerVariable = std::format("CRAFTER_BUILD_RUNNER_{}", otherTarget); + std::ranges::replace(runnerVariable, '-', '_'); + std::ranges::replace(runnerVariable, '.', '_'); + setenv(runnerVariable.c_str(), "no-such-runner", 1); + bool threw = false; + try { + RunTests(both, serial); + } catch (const std::exception&) { + threw = true; + } + unsetenv(runnerVariable.c_str()); + Check(threw, "a run whose runner for the other target is given wrong throws"); + const fs::path thrownDirectory = fs::path(Recorded(records / "failing").first).parent_path(); + Check(thrownDirectory != directory && fs::exists(thrownDirectory / "failing" / "left-behind"), + std::format("and keeps what its first pass kept: {}", thrownDirectory.string())); + + // Two failing tests of one name in a run, as two configurations may + // each declare one: each one's log is its own, named as its TMPDIR is, + // twin-2 for the second, and says where what it left is kept. With one + // log for both, the second's was written over the first's. Each check + // reads to the end of the line: twin's path is the start of twin-2's. + Configuration one; + one.path = "./"; + one.name = "one"; + one.outputName = "one"; + one.target = HostTarget(); + AddProbe(one, "twin", { (records / "twin").string(), "1" }); + Configuration other; + other.path = "./"; + other.name = "other"; + other.outputName = "other"; + other.target = HostTarget(); + AddProbe(other, "twin", { (records / "twin-2").string(), "1" }, true); + std::array twins = { &one, &other }; + RunTests(twins, serial); + const auto logOf = [](std::string_view name) { + std::ifstream in(fs::path("build") / "test-logs" / std::format("{}.log", name)); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + }; + const std::string firstTwin = Recorded(records / "twin").first; + const std::string secondTwin = Recorded(records / "twin-2").first; + Check(!firstTwin.empty() && logOf("twin").contains(std::format("kept in {}\n", firstTwin)), + std::format("the first of two failing tests of one name has a log of its own, which says where it kept what it left: {}", firstTwin)); + Check(!secondTwin.empty() && logOf("twin-2").contains(std::format("kept in {}\n", secondTwin)), + std::format("and so has the second, twin-2.log: {}", secondTwin)); + + fs::remove_all(staged, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} From 0602e282b2642ff34fc3a4bac6861b3176136a61 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:17:58 +0100 Subject: [PATCH 25/27] test: HostFlatpak asks about projects in a directory of its own In the Flatpak, HostFlatpak makes two projects in the sandbox's /tmp, one there and one through a link in the fixture's build/ that leads there, and asks whether the host sees them. They had fixed names, /tmp/crafter-build-host-flatpak and crafter-build-host-flatpak-linked beside it, and every sandbox of the app has the same /tmp, so two runs at once asked about, and removed, the same projects. Both are now in a directory the test makes there, a PrivateDirectory, which the link leads to, and which goes afterwards with the link, or, when the test is killed, when a later one is made, once it has not changed for a minute. The test still names /tmp rather than the TMPDIR it is given, since the sandbox's /tmp is what it asks the host about, and AGENTS.template.md's entry for it says it makes a directory of its own there now. --- AGENTS.template.md | 2 +- tests/HostFlatpak/main.cpp | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 0865356..91de608 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -167,7 +167,7 @@ These were decided deliberately. Do not undo them without the maintainer's say-s - The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. - crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. - CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. -- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make: `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up, and a later run removes what a killed run of it left once that has not changed for a minute (`PrivateDirectory`); and `tests/HostFlatpak`, which in the Flatpak makes its two projects in the sandbox's `/tmp`, the place it asks the host about, under fixed names, so that its next run that makes them removes what a killed one left. +- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make, and a later run removes what a killed one left once that has not changed for a minute (`PrivateDirectory`): `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up; and `tests/HostFlatpak`, which in the Flatpak makes a directory of its own in the sandbox's `/tmp`, the place it asks the host about. ## CI and publishing diff --git a/tests/HostFlatpak/main.cpp b/tests/HostFlatpak/main.cpp index 7aba938..9ffdb38 100644 --- a/tests/HostFlatpak/main.cpp +++ b/tests/HostFlatpak/main.cpp @@ -79,11 +79,18 @@ int main() { } at = info.find("filesystems=", at + 1); } + // Both in a directory of this run's own there, a PrivateDirectory, + // removed at the end of this block: every sandbox of the app has the + // same /tmp, so two runs at once would ask about, and remove, the + // same projects, and what a run that is killed leaves goes when a + // later one is made, once it has not changed for a minute. + const PrivateDirectory own("/tmp", "crafter-build-host-flatpak-"); + const fs::path& scratch = own.path; const fs::path link = fixture / "build" / "to-tmp"; fs::create_directories(link.parent_path(), ec); fs::remove(link, ec); - fs::create_directory_symlink("/tmp", link, ec); - const std::array unseen = {"/tmp/crafter-build-host-flatpak", link / "crafter-build-host-flatpak-linked"}; + fs::create_directory_symlink(scratch, link, ec); + const std::array unseen = {scratch / "project", link / "linked"}; for (const fs::path& project : unseen) { if (tmpShared) { std::println("an override shares the host's /tmp with the sandbox, so the host sees {}: left out", project.string()); @@ -100,6 +107,8 @@ int main() { Check(fs::is_empty(project, ec), std::format("and asking leaves nothing in {}", project.string())); fs::remove_all(fs::weakly_canonical(project, ec), ec); } + // The link goes with the directory it leads to. + fs::remove(link, ec); // From a working directory only the sandbox has, the host is reached // all the same, and sees the fixture. if (permitted) { From e643f83c005560106faf2d24919f8492503c8414 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 09:18:05 +0100 Subject: [PATCH 26/27] docs: the TMPDIR each test's command runs with The README's test conventions say that each test runs with TMPDIR naming a directory of its own, made for the run, so that fs::temp_directory_path() in it is the test's alone while another run goes on, where its runner hands it TMPDIR, which wine does not, a Windows test's TMP, TEMP and temp directory being the Wine prefix's whatever the environment gives, and wasmtime, which hands a test no environment, does not either; how much longer its path is, which a test that binds a socket there has to leave room for; that what it leaves there is removed when it passes or skips and kept, with its place in its log, when it does not; that a later run removes what was kept once the run's directory has gone a minute unchanged, a minute after that run ended or, where it was killed, after its last change to it; and that a test that builds against a sysroot it stages there, or has crafter-build fetch a repository it stages there, whose path keys crafter-build's cache and is a new one every run, points XDG_CACHE_HOME into its TMPDIR as well. AGENTS.template.md's testing conventions say why the fixed staging name is safe now, that a test that writes to /tmp by name makes a directory of its own there, a PrivateDirectory, and that a test that builds against what it stages keeps its cache in its scratch directory. --- AGENTS.template.md | 2 +- README.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 91de608..6e4b9f7 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -90,7 +90,7 @@ Conventions the existing tests follow: - Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape. - Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it. - Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout. -- Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"`, after removing what an earlier run left there, which matters where the test runs by hand: under `crafter-build test` the copy is in the test's own `TMPDIR`, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. +- Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"`, after removing what an earlier run left there, which matters where the test runs by hand: under `crafter-build test` the copy is in the test's own `TMPDIR`, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. The fixed name is safe because `RunTests` gives every test a `TMPDIR` of its own for the run, so two runs at once, natively or in the Flatpak, whose sandboxes all share the app's `/tmp`, stage into different directories. A test that writes to `/tmp` by name, as `HostFlatpak` has to, makes a directory of its own there, a `PrivateDirectory`, which a later run removes, where a killed run left it, once it has not changed for a minute. A test that builds against a sysroot it stages, or has crafter-build fetch a repository it stages, points `XDG_CACHE_HOME` into its scratch directory too, as `SysrootStdModule` and the external-dependency tests do: the cache's key holds that path or URL, which is a new one every run. - Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. - Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. - `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first. diff --git a/README.md b/README.md index ec26f89..3dc7f20 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ Test conventions: - **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH"). - Each test runs in its own subprocess — a segfault doesn't take the runner down. +- Each test runs with `TMPDIR` naming a directory of its own, `/` in a directory made for the run in the temp directory, or, where the run has given that name out already, the first of `-2`, `-3` and on that it has not, so `fs::temp_directory_path()` in a test is the test's alone, even with another run going at the same time. Its path is longer than the temp directory's by 28 bytes and the name of the test's own directory, room a test that binds a Unix socket there has to leave: a socket's path holds 107 bytes. That takes a runner that hands the test `TMPDIR`, as running it directly and qemu-user do: under wine a Windows test does not get `TMPDIR`, and its `TMP`, `TEMP` and temp directory are the Wine prefix's, which every run in that prefix shares; wasmtime gives a test no environment at all. What a test leaves in its `TMPDIR` is removed when it passes or skips. When it fails, crashes or times out, what it left is kept, and its log in `build/test-logs/` says where, as does what is printed of a test that fails or crashes. A later run removes it once the run's directory has gone a minute unchanged: a minute after the run that kept it ended, or, where that run was killed, a minute after it last made or removed a test's directory there. A test that builds against a sysroot or mingw prefix it stages there, or has crafter-build fetch a repository it stages there (an `ExternalDependency` or a `GitProject` of it), keys crafter-build's cache on that path or URL, which is a new one every run: point `XDG_CACHE_HOME` into its `TMPDIR` as well, or every run leaves an entry of its own in the cache. - Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()` tests (`--jobs=`). The steps of their builds share one limit, a build's: as many at once as there are hardware threads. - Stdout+stderr is captured and printed atomically on completion. A test that fails, crashes or times out once it is built also writes what it printed, and what crafter-build said of it, to `build/test-logs/.log`, when that is anything, and, where it sets `Test::wayland` and ran, what its compositor printed, if anything, to `.compositor.log` beside it (what a compositor that did not start printed is in `.log`); one that failed to build, or did not get that far, writes neither. `` is the test's name with `-2`, `-3` and on after it where the run has given that name out already, as two configurations or two targets may each declare a test of one name. - A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run. From c14452848197399448ec6a0f1c93bcc27d6a48be Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 10:22:34 +0100 Subject: [PATCH 27/27] docs(packaging): add the 6.5.0 release entry 6.5.0 gives a test that sets Test::wayland a headless compositor of its own, so that the windows a test opens through WAYLAND_DISPLAY no longer show up on the desktop of whoever runs the suite, ships weston in the Flatpak for it, and runs every test's command with a TMPDIR of its own, so that two runs of `crafter-build test` at once no longer write into each other's temporary files where the test's runner hands it TMPDIR, as running it directly and qemu-user do, and wine and wasmtime do not. A minor release, by the version rule: the notes have New and Fixes and nothing Breaking. The range adds Test::wayland, TestBuilder::Wayland, TestResult::compositorLog, RunTestsOptions::compositorOverride and the export of PrivateDirectory, and two parameters at the end of RunSingleTest, both with defaults, so that the calls to it that compiled before compile unchanged. --- .../flatpak/net.catcrafts.CrafterBuild.metainfo.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml index afaf84a..f9b0307 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml @@ -26,6 +26,19 @@ + + +

New

+
    +
  • A test that sets Test::wayland, or .Wayland() on what AddTest returns, runs with a headless Wayland compositor of its own instead of your session's display, so the windows it opens through WAYLAND_DISPLAY no longer show up on your desktop. The compositor is started for that test alone and stopped when it ends; the test finds it through WAYLAND_DISPLAY, the full path of its socket, and runs without DISPLAY. It is weston on its headless backend with its GL renderer, unless CRAFTER_BUILD_COMPOSITOR or the new --compositor= names another command, and host gives such tests your own display, to watch what they draw. A test whose compositor cannot be started fails, saying why, unless it declares .Requires("tool:weston"), which skips it where weston is missing, and when a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to build/test-logs/<name>.compositor.log, named as the test's own log is. The README's new "Tests that open windows" section has the details.
  • +
  • The Flatpak ships weston 16.0.2, with its headless backend, its GL renderer and its desktop shell: the compositor those tests get.
  • +
+

Fixes

+
    +
  • Two runs of crafter-build test at once no longer write into each other's temporary files. Each test now runs with TMPDIR naming a directory of its own, made for the run, so fs::temp_directory_path() in a test is the test's alone. Tests that staged files under fixed names there collided with another run doing the same: natively every process shares /tmp, and in the Flatpak every instance of the app shares one. What a test leaves there is removed when it passes or skips, and kept when it fails, crashes or times out, with its place in the test's log, until a later run removes it, a minute after the run that kept it ended, or after its last change to it where that run was killed. This takes a runner that passes the test TMPDIR, as running it directly and qemu-user do; under wine, which does not pass it on, and wasmtime, which passes on no environment at all, a test's temporary directory is what it was. A test that builds against a sysroot it stages there, or has crafter-build fetch a repository it stages there, keys crafter-build's cache on a path that is now a new one every run: point XDG_CACHE_HOME into its temporary directory as well.
  • +
+
+

Fixes