// 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; }