Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
c144528481 |
|||
|
e643f83c00 |
|||
|
0602e282b2 |
|||
|
ab8935826d |
|||
|
93f1c8d9b9 |
|||
|
fcfac0d9cf |
|||
|
0a91b128cf |
|||
|
67e97d0a2a |
|||
|
dc8e9e6f9e |
|||
|
cb8914d387 |
|||
|
fe25d7aeff |
|||
|
043b1a3015 |
|||
|
090d8f6363 |
|||
|
8019f9d44f |
23 changed files with 1885 additions and 43 deletions
|
|
@ -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.
|
||||
|
|
@ -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/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"` 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/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"`, 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.
|
||||
|
|
@ -162,11 +162,12 @@ 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:<command>` 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 <name>` 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.
|
||||
- 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. 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
|
||||
|
||||
|
|
@ -206,7 +207,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 <hardware threads>` 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 (`<build>/.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.
|
||||
|
|
@ -214,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/<major>/`, one `libcxx-<major>-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/<triple>/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.
|
||||
|
|
|
|||
22
README.md
22
README.md
|
|
@ -299,8 +299,9 @@ 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, `<run>/<name>` in a directory made for the run in the temp directory, or, where the run has given that name out already, the first of `<name>-2`, `<name>-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. Failed/crashed/timed-out tests also write to `build/test-logs/<name>.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/<name>.log`, when that is anything, and, where it sets `Test::wayland` and ran, what its compositor printed, if anything, to `<name>.compositor.log` beside it (what a compositor that did not start printed is in `<name>.log`); one that failed to build, or did not get that far, writes neither. `<name>` 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:
|
||||
|
|
@ -313,6 +314,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 +377,24 @@ cmd:<command> # 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-<n>` 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-<n>` 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/<name>.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/<name>.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:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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<ScannedUnit> 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<std::string> 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
|
||||
|
|
@ -2924,6 +2949,13 @@ Test options (after the `test` subcommand):
|
|||
--runner=<spec> Override the test runner for this run. Specs:
|
||||
local
|
||||
cmd:<command> (e.g. cmd:wine)
|
||||
--compositor=<command> The headless Wayland compositor each test that sets
|
||||
Test::wayland runs with, a command run through sh
|
||||
that listens on a wayland-<n> 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=<triple> Filter to tests whose cfg.target matches. Default:
|
||||
sweep across every distinct target declared by the
|
||||
project's tests plus the host triple.
|
||||
|
|
@ -3027,6 +3059,9 @@ Environment:
|
|||
CRAFTER_BUILD_RUNNER_<TARGET> 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
|
||||
|
|
@ -3150,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") {
|
||||
|
|
|
|||
|
|
@ -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<std::string> 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<std::string> 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<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None);
|
||||
if (!tu) {
|
||||
CXTranslationUnit tu = nullptr;
|
||||
if (lc.parseTranslationUnit2FullArgv(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None, &tu) != CXError_Success || !tu) {
|
||||
lc.disposeIndex(index);
|
||||
result.error = "clang could not create a translation unit";
|
||||
return result;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ module;
|
|||
#include <dlfcn.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <signal.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
module Crafter.Build:Platform_impl;
|
||||
|
|
@ -874,6 +876,168 @@ 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<const EnvironmentChange> 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<char*, 4> argv = { shell.data(), flag.data(), script.data(), nullptr };
|
||||
|
||||
std::vector<std::string> 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<char*> 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<std::int32_t> 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<id_t>(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;
|
||||
// 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;
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
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);
|
||||
}
|
||||
|
||||
std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
|
||||
CacheLock lock(stdPcm.parent_path());
|
||||
if(config.target == "x86_64-w64-mingw32") {
|
||||
|
|
|
|||
|
|
@ -64,12 +64,78 @@ namespace {
|
|||
}
|
||||
}
|
||||
|
||||
void WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) {
|
||||
// Writes build/test-logs/<name>.log and returns its path, or nothing
|
||||
// when the directory cannot be made.
|
||||
std::optional<fs::path> 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
|
||||
// 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.
|
||||
constexpr std::chrono::seconds CompositorStartup{30};
|
||||
|
||||
std::string CompositorCommand(const std::optional<std::string>& 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-<n> socket a compositor made in `directory`. Any number:
|
||||
// libwayland's wl_display_add_socket_auto starts at 0 and weston at 1.
|
||||
std::optional<fs::path> 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<char>(in), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
void PrintResult(const TestResult& r, std::string_view runnerName) {
|
||||
|
|
@ -259,27 +325,91 @@ 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<std::string>& compositorOverride, const fs::path& temporaryDirectory) {
|
||||
TestResult result;
|
||||
result.name = test.config.name;
|
||||
|
||||
std::map<std::string, std::string> 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);
|
||||
}
|
||||
|
||||
// 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.
|
||||
const std::string compositor = test.wayland ? CompositorCommand(compositorOverride) : std::string();
|
||||
std::optional<CompositorDirectory> directory;
|
||||
std::optional<BackgroundCommand> 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<EnvironmentChange, 4> 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<fs::path> socket = WaylandSocket(directory->path);
|
||||
std::optional<std::int32_t> 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-<n> 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;
|
||||
}
|
||||
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);
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
|
||||
result.output = std::move(r.output);
|
||||
|
|
@ -292,6 +422,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<std::int32_t> 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 +590,7 @@ TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.pu
|
|||
TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> 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;
|
||||
|
|
@ -457,14 +601,30 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
|
||||
}
|
||||
|
||||
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> 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<PrivateDirectory> directory;
|
||||
std::set<std::string> used;
|
||||
};
|
||||
}
|
||||
|
||||
// RunTests, with the run's temporaries.
|
||||
static TestSummary RunTestsWith(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> 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<Configuration*> 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
|
||||
|
|
@ -491,7 +651,7 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> 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;
|
||||
|
|
@ -571,6 +731,28 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, co
|
|||
}
|
||||
}
|
||||
|
||||
// Each test runs with TMPDIR naming a directory of its own, <run>/<name>,
|
||||
// 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-<name>), 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 <name>-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<fs::path> 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());
|
||||
|
|
@ -691,16 +873,47 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> 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);
|
||||
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, <name>-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<fs::path> 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);
|
||||
}
|
||||
|
||||
{
|
||||
|
|
@ -746,3 +959,8 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, co
|
|||
|
||||
return summary;
|
||||
}
|
||||
|
||||
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
|
||||
RunTemporaries run;
|
||||
return RunTestsWith(configurations, opts, projectArgs, run);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -151,6 +151,24 @@ namespace {
|
|||
std::atomic<bool> 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;
|
||||
|
|
|
|||
|
|
@ -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<std::string> 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,
|
||||
|
|
|
|||
|
|
@ -58,6 +58,67 @@ 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<std::string> 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<std::int32_t> exitCode;
|
||||
bool reaped = false;
|
||||
public:
|
||||
BackgroundCommand(std::string_view command, std::span<const EnvironmentChange> 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<std::int32_t> 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, 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<bool> 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
|
||||
// project's own directory, named whatever its owner chose. Quoted for
|
||||
|
|
|
|||
|
|
@ -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<std::string> 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<std::string> compositorOverride;
|
||||
};
|
||||
|
||||
struct TestSummary {
|
||||
|
|
@ -98,7 +105,34 @@ 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<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> 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).
|
||||
// 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
|
||||
// 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-<n> 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 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<std::string>& 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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -26,6 +26,28 @@
|
|||
</provides>
|
||||
<content_rating type="oars-1.1"/>
|
||||
<releases>
|
||||
<release version="6.5.0" date="2026-11-28">
|
||||
<description>
|
||||
<p>New</p>
|
||||
<ul>
|
||||
<li>A test that sets <code>Test::wayland</code>, or <code>.Wayland()</code> on what <code>AddTest</code> returns, runs with a headless Wayland compositor of its own instead of your session's display, so the windows it opens through <code>WAYLAND_DISPLAY</code> 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 <code>WAYLAND_DISPLAY</code>, the full path of its socket, and runs without <code>DISPLAY</code>. It is weston on its headless backend with its GL renderer, unless <code>CRAFTER_BUILD_COMPOSITOR</code> or the new <code>--compositor=</code> names another command, and <code>host</code> gives such tests your own display, to watch what they draw. A test whose compositor cannot be started fails, saying why, unless it declares <code>.Requires("tool:weston")</code>, 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 <code>build/test-logs/<name>.compositor.log</code>, named as the test's own log is. The README's new "Tests that open windows" section has the details.</li>
|
||||
<li>The Flatpak ships weston 16.0.2, with its headless backend, its GL renderer and its desktop shell: the compositor those tests get.</li>
|
||||
</ul>
|
||||
<p>Fixes</p>
|
||||
<ul>
|
||||
<li>Two runs of <code>crafter-build test</code> at once no longer write into each other's temporary files. Each test now runs with <code>TMPDIR</code> naming a directory of its own, made for the run, so <code>fs::temp_directory_path()</code> 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 <code>/tmp</code>, 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 <code>TMPDIR</code>, 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 <code>XDG_CACHE_HOME</code> into its temporary directory as well.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="6.4.3" date="2026-11-27">
|
||||
<description>
|
||||
<p>Fixes</p>
|
||||
<ul>
|
||||
<li>In crafter-build's Flatpak, <code>crafter-build lint</code> runs the rules that read a file's AST on a source that includes a header of the C++ standard library, such as <code><algorithm></code>, in a build for the host that names no libc++ directory of its own through a sysroot, <code>CRAFTER_BUILD_LIBCXX_DIR</code> or its flags (#46). There such a source built, and lint then ran none of those rules on it, printed <code>'algorithm' file not found</code> and exited 1. The parse of such a build took the first libc++ it found under <code>../include</code> from the working directory, <code>/usr/local/include</code> and <code>/usr/include</code>, wherever the build's compiler keeps its own (<code>/app</code> in the Flatpak, whose <code>/usr</code> 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 <code>clang++.cfg</code>.</li>
|
||||
<li>A build no longer fails to scan its sources where its compiler is reached through a link from another directory, as a <code>bin/clang++</code> under <code>CRAFTER_BUILD_LLVM_DIR</code> 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.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="6.4.2" date="2026-11-27">
|
||||
<description>
|
||||
<p>Fixes</p>
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -314,6 +314,8 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> 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() });
|
||||
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
|
||||
|
|
@ -352,6 +354,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> 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
|
||||
|
|
|
|||
517
tests/HeadlessCompositor/main.cpp
Normal file
517
tests/HeadlessCompositor/main.cpp
Normal file
|
|
@ -0,0 +1,517 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
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-<n> 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. 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
|
||||
// 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 = "<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, and the TMPDIR a test is given.
|
||||
constexpr std::array<std::string_view, 5> 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;
|
||||
}
|
||||
|
||||
std::string ReadFile(const fs::path& file) {
|
||||
std::ifstream in(file, std::ios::binary);
|
||||
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
// 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<std::string, std::string> ReadEnvironment(const fs::path& file) {
|
||||
std::map<std::string, std::string> 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<const sockaddr*>(&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<bool()>& 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/<pid>/stat, "<pid> (<comm>) <state>
|
||||
// <ppid> ...", 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<const sockaddr*>(&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<PrivateDirectory> 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<std::string, std::string> server = ReadEnvironment(state / "compositor.env");
|
||||
std::map<std::string, std::string> 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<std::string, std::string> 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");
|
||||
}
|
||||
|
||||
// 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<std::string, std::string> 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<std::string, std::string> 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));
|
||||
std::map<std::string, std::string> 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<std::string, std::string> 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;
|
||||
}
|
||||
|
|
@ -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<fs::path, 2> unseen = {"/tmp/crafter-build-host-flatpak", link / "crafter-build-host-flatpak-linked"};
|
||||
fs::create_directory_symlink(scratch, link, ec);
|
||||
const std::array<fs::path, 2> 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) {
|
||||
|
|
|
|||
|
|
@ -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<const LintDecl> 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 <string> 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<fs::path, 1> ifaces = { "Demo" };
|
||||
std::array<fs::path, 0> 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<const LintDecl> 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
|
||||
|
|
|
|||
235
tests/LintCompilerHeaders/main.cpp
Normal file
235
tests/LintCompilerHeaders/main.cpp
Normal file
|
|
@ -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<std::streamsize>(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<std::string_view> 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 <algorithm> 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 <algorithm>\n#include <crafter_issue46.h>\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<fs::path, 0> interfaces = {};
|
||||
std::array<fs::path, 1> implementations = { "unit" };
|
||||
cfg.GetInterfacesAndImplementations(interfaces, implementations);
|
||||
|
||||
{
|
||||
std::unordered_map<fs::path, std::shared_future<BuildResult>> 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<std::string> 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 <crafter_issue46_cfg.h>\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 <triple>-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<fs::path, 1> writtenImplementations = { "written" };
|
||||
written.GetInterfacesAndImplementations(interfaces, writtenImplementations);
|
||||
|
||||
{
|
||||
std::unordered_map<fs::path, std::shared_future<BuildResult>> 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<std::string> 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;
|
||||
}
|
||||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
#include <stdlib.h>
|
||||
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");
|
||||
|
||||
|
|
|
|||
30
tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp
Normal file
30
tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp
Normal file
|
|
@ -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 : "<unset>", 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]);
|
||||
}
|
||||
247
tests/TestTemporaryDirectory/main.cpp
Normal file
247
tests/TestTemporaryDirectory/main.cpp
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
#include <stdlib.h>
|
||||
import std;
|
||||
import Crafter.Build;
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Crafter;
|
||||
|
||||
// Each test runs with TMPDIR naming a directory of its own, <run>/<name>, 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 <name>-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<std::string, std::string> Recorded(const fs::path& file) {
|
||||
std::ifstream in(file);
|
||||
std::pair<std::string, std::string> 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<std::string> 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<fs::path, 0> ifaces = {};
|
||||
std::array<fs::path, 1> 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<Configuration*, 2> 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<char>(in), std::istreambuf_iterator<char>());
|
||||
}();
|
||||
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<Configuration*, 1> 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_<triple> 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<Configuration*, 2> 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<char>(in), std::istreambuf_iterator<char>());
|
||||
};
|
||||
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;
|
||||
}
|
||||
Loading…
Reference in a new issue