feat: lay an executable out as the files/ of a Flatpak

A Linux executable built by the Flatpak crafter-build links the libc++,
libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs
inside crafter-build's sandbox and practically nowhere else: a host
needs glibc 2.38 or newer and all three LLVM libraries, which not even
Arch has. A program built here is meant to run in a Flatpak, so it can
now be laid out as one: with cfg.packaging = Packaging::Flatpak, or
--packaging=flatpak where the project.cpp crafter-build was pointed at
calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in
the app's sandbox, and -r runs the program there against the libraries
the app carries.

The program is linked into files/bin, where its shaders, files and
assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path,
and the new :Flatpak partition writes the rest of files/: files/lib with
the LLVM runtime libraries, located one by one through clang, and
whatever else the program needs, read with llvm-readelf, that the
directories of the shared libraries it is built on hold, the ones an
unpackaged link records as run paths, or the toolchain's own lib dir,
/app/lib in crafter-build's Flatpak, which the link searches too; and
the desktop entry, metainfo and icons under the app-id in files/share,
the entry refused when its Icon= is not the app-id or
desktop-file-validate, where there is one, rejects it, and an icon that
is not an .svg or a square .png. The metadata and export/ of a build
directory are flatpak build-finish's to write, and crafter-build keeps
no copy of its rules: what a permission means and what the host sees of
an app change with flatpak's releases, and a copy would have to follow
every one. The writer copies a file only when its content differs,
compared a block at a time so that a large file costs no more memory
than a small one, and writes one only when what it would write differs,
never deciding by an mtime, which ostree sets to 0 for every file of
/app, and works the program's libraries out on every write, which reads
only their dynamic sections, since a library replaced in place, as by a
toolchain update, can need others, which FlatpakLibraryChange checks; it
prunes from files/bin each top-level entry an earlier build put there
and this one does not, reporting those the program wrote there itself.

What cannot be a Flatpak is refused before anything is built, saying
why: a Windows or wasm executable, a build against a sysroot or for
musl, another architecture than the runtime's, a build against
CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and
a build by a native crafter-build, which links the host's glibc: a
native process knows no Flatpak runtime, from /.flatpak-info, unless
CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one.
Default stays the executable as linked for now, RunTests runs every test
as linked, whatever its Configuration asks for, and RunLint works out
its compile command so, and a forwarded --packaging= leaves a
dependency's executables alone, since consumers run them by path. A
dependency that packages its own executable gets its desktop file,
metainfo and icons rebased by the loader as its cfg.files are, so they
are its own whatever directory the consumer builds from. Only a Flatpak
is keyed into VariantId, so every other configuration keeps its
directory, but for one given --packaging=, which was a project arg,
hashed into VariantId, and is a standard arg now, a dependency's
included. The app-id and what a Flatpak is installed as are not keyed:
they change files/share, never what is compiled. The asset name map,
kept three times, twice in Build() and once for the browser runtime's
files.json, is one function now, CompressedAssetName; CompressAsset, in
Crafter.Build-Asset.cpp, keeps the list of the extensions it loads,
which has to agree with it. Each copy a Flatpak build makes into the
program's directory, of its shaders, assets, cfg.files and what its
dependencies forward, records the top-level name it places there, the
names of what a directory holds for one copied into it itself ("data/",
"data/."), and those are what the writer keeps in files/bin; a build
that fails after copying adds them to the writer's record all the same,
so the next write removes what no build places any more.

SharedLibraryRuns now also packages its program as a Flatpak, whose
files/lib has to carry libgreet.so for it to start.
This commit is contained in:
Jorijn van der Graaf 2026-11-01 19:20:55 +01:00
commit 27031ed8e3
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
56 changed files with 2314 additions and 74 deletions

View file

@ -16,6 +16,7 @@ import :Script;
import :Agents;
import :Progress;
import :Asset;
import :Flatpak;
namespace fs = std::filesystem;
using namespace Crafter;
@ -579,6 +580,85 @@ namespace {
}
return "";
}
// Why `config` cannot be the Flatpak it asks for; empty when it can be,
// or does not ask. Checked before anything is built, like WasmBuildError:
// each of these would otherwise surface as an app that does not start
// once installed, or not at all on the machine it was meant for.
std::string FlatpakBuildError(const Configuration& config) {
if (config.ResolvedPackaging() != Packaging::Flatpak) return "";
if (config.target == "x86_64-w64-mingw32") return std::format("{}: a Windows executable is not packaged as a Flatpak; it stays an .exe", config.name);
if (config.target.starts_with("wasm32")) return std::format("{}: a wasm build is not packaged as a Flatpak; it stays a .wasm", config.name);
const Toolchain& tc = GetToolchain();
if (tc.flatpakBranch.empty()) {
return std::format("{}: only the Flatpak crafter-build packages a Flatpak: a native one links the program against the host's glibc and libc++, which no Flatpak runtime matches", config.name);
}
if (!config.sysroot.empty()) {
return std::format("{}: a build against a sysroot ({}) links that sysroot's libraries, its C library among them, and not those of the runtime the app runs on", config.name, config.sysroot);
}
if (NormalizeTarget(config.target) != std::format("{}-linux-gnu", tc.flatpakArch)) {
if (config.target.ends_with("-linux-musl")) return std::format("{}: {} links musl, which no Flatpak runtime provides", config.name, config.target);
return std::format("{}: {} is not packaged as a Flatpak: the runtime crafter-build runs on, and the libc++ it would bundle, are {}", config.name, config.target, tc.flatpakArch);
}
// The libc++ a Flatpak carries is the toolchain's own, built against
// the runtime's glibc. One from CRAFTER_BUILD_LIBCXX_DIR is what the
// program would be compiled and linked against instead, and nothing
// says which glibc it needs: bundled, it may not load on the
// runtime; not bundled, the program loads a libc++ it was not built
// against.
if (!tc.libcxxDir.empty()) {
return std::format("{}: a build against CRAFTER_BUILD_LIBCXX_DIR ({}) links that libc++, and a Flatpak carries the toolchain's own, built against the runtime's glibc: unset it to package a Flatpak", config.name, tc.libcxxDir.string());
}
return "";
}
// What an asset is compressed to, by the extension Crafter.Asset reads:
// the formats stb_image loads (behind TextureAsset::LoadPNG) to .ctex,
// .obj to .cmesh; nullopt for anything else. The one rule for an
// executable's own assets and the ones its dependencies forward to it.
std::optional<fs::path> CompressedAssetName(const fs::path& src) {
std::string ext = src.extension().string();
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(c)));
if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") {
return fs::path(src.filename()).replace_extension(".ctex");
}
if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh");
return std::nullopt;
}
// The writer's record: one per bin dir, as there is one bin dir per
// BuildDir(). VariantId() does not hold outputName, and under a name of
// its own the record of a program renamed in place was not found, so
// the old program stayed in files/bin as one it wrote.
fs::path FlatpakRecordPath(const Configuration& config) {
return config.BuildDir() / "flatpak-record";
}
// Gathers what WriteFlatpakFiles needs from `config`, the link that just
// ran and the top-level names Build()'s copies placed in files/bin, and
// has it lay out files/.
std::string WriteFlatpak(const Configuration& config, const BuildResult& linked, const std::set<std::string>& placed) {
const Toolchain& tc = GetToolchain();
FlatpakFiles d;
d.root = config.BinDir();
d.record = FlatpakRecordPath(config);
d.appId = config.flatpak.appId.empty() ? DefaultFlatpakAppId(config.outputName) : config.flatpak.appId;
d.command = ExpectedOutput(config).filename().string();
d.desktopFile = config.flatpak.desktopFile;
d.metainfo = config.flatpak.metainfo;
d.icons = config.flatpak.icons;
d.clangxx = tc.clangxx;
d.readelf = tc.llvmReadelf;
for (const std::string& dir : linked.runPaths) d.libraryDirs.emplace_back(dir);
// Last, the toolchain's own lib dir, which the link searches as well
// (LibcxxSearchFlags): a library it takes from there, libclang or
// libedit of crafter-build's /app/lib, is no runtime's. -r would not
// show it missing, since crafter-build's sandbox has /app/lib on the
// loader's path, but the installed app would not start.
if (const fs::path toolchainLib = tc.LibcxxLibDir(); !toolchainLib.empty()) d.libraryDirs.push_back(toolchainLib);
d.programEntries = placed;
return WriteFlatpakFiles(d);
}
}
BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex) {
@ -641,6 +721,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
}
// As early as the duplicate-module check, so a refused build leaves no
// directory behind and starts no thread, but after the sysroot is known.
// A Flatpak asked of a target that cannot be one says so before anything
// the target itself would refuse: that is the request to change.
if (std::string refused = FlatpakBuildError(config); !refused.empty()) {
return {std::move(refused), false, {}};
}
if (std::string refused = WasmBuildError(config); !refused.empty()) {
return {std::move(refused), false, {}};
}
@ -649,6 +734,39 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// Everything this configuration produces lands here: a library's archive
// and module PCMs, an executable and the files it reads at run time.
fs::path outputDir = config.ProgramDir();
// The top-level names this build places in outputDir, which a Flatpak's
// writer keeps in files/bin and an earlier build's it removes. Each copy
// below records its own destination as it decides it: the name that
// follows outputDir in it, or, for a directory copied into outputDir
// itself ("data/", "data/."), the names of what that directory holds.
std::set<std::string> placed = {ExpectedOutput(config).filename().string()};
const auto withoutSeparator = [](fs::path path) {
path = fs::absolute(path).lexically_normal();
return path.has_filename() ? path : path.parent_path();
};
const fs::path outputRoot = withoutSeparator(outputDir);
const auto place = [&](const fs::path& destination, const fs::path& source) {
const fs::path normal = withoutSeparator(destination);
if (normal != outputRoot) {
placed.insert(normal.lexically_relative(outputRoot).begin()->string());
return;
}
std::error_code ec;
for (const fs::directory_entry& child : fs::directory_iterator(source, ec)) placed.insert(child.path().filename().string());
};
// A build that fails has copied into files/bin all the same, so what it
// placed joins the writer's record on every way out of Build(): the next
// write removes what no build places any more, rather than take it for
// a file the program wrote. After a write, the record holds these names
// already.
struct PlacedOnExit {
const Configuration& config;
const std::set<std::string>& names;
~PlacedOnExit() {
if (config.ResolvedPackaging() == Packaging::Flatpak) RecordFlatpakPlaced(FlatpakRecordPath(config), names);
}
};
const PlacedOnExit placedOnExit{config, placed};
if (!fs::exists(buildDir)) {
fs::create_directories(buildDir);
@ -705,6 +823,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
}
for (const Shader& shader : config.shaders) {
if (buildCancelled.load(std::memory_order_relaxed)) break;
place(outputDir / shader.OutputName(), {});
if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue;
threads.emplace_back([&shader, &outputDir, &buildDir, &shaderIncludeDirs, &buildError, &buildCancelled]() {
// A source registered more than once shows up once per variant;
@ -732,18 +851,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// Skipped per-file if the output is newer than the source. Each
// compress runs in its own thread; passthrough copies are bundled into
// a single thread to match the cfg.files pattern.
auto compressedName = [](const fs::path& src) -> std::optional<fs::path> {
std::string ext = src.extension().string();
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(c)));
// stb_image (used by CompressAsset → TextureAsset::LoadPNG) handles
// png/tga/jpg/bmp; all map to .ctex.
if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") {
return fs::path(src.filename()).replace_extension(".ctex");
}
if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh");
return std::nullopt;
};
auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) {
place(outputDir / outRelative, {});
fs::path out = outputDir / outRelative;
if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return;
threads.emplace_back([sourcePath = std::move(sourcePath), out = std::move(out), &buildError, &buildCancelled]() {
@ -766,14 +875,15 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
for (const auto& entry : fs::recursive_directory_iterator(asset)) {
if (!entry.is_regular_file()) continue;
fs::path rel = fs::relative(entry.path(), asset);
if (std::optional<fs::path> compName = compressedName(entry.path())) {
if (std::optional<fs::path> compName = CompressedAssetName(entry.path())) {
submitCompress(entry.path(), topName / rel.parent_path() / *compName);
} else {
place(outputDir / topName / rel, {});
assetPassthroughs.emplace_back(entry.path(), topName / rel);
}
}
} else {
std::optional<fs::path> outName = compressedName(asset);
std::optional<fs::path> outName = CompressedAssetName(asset);
if (!outName) {
buildCancelled.store(true);
buildError = std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string());
@ -805,6 +915,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
});
}
for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile);
threads.emplace_back([&config, &outputDir, &buildCancelled, &buildError]() {
Progress::Task task(std::format("Copying files for {}", config.name));
if (buildCancelled.load(std::memory_order_relaxed)) return;
@ -1085,11 +1196,13 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
for (const Shader& shader : dep->shaders) {
fs::path src = depBinDir / shader.OutputName();
if (!fs::exists(src)) continue;
place(outputDir / src.filename(), src);
copyTree(src, outputDir / src.filename());
}
for (const fs::path& additionalFile : dep->files) {
fs::path src = depBinDir / additionalFile.filename();
if (!fs::exists(src)) continue;
place(outputDir / additionalFile.filename(), src);
copyTree(src, outputDir / additionalFile.filename());
}
for (const fs::path& asset : dep->assets) {
@ -1100,22 +1213,16 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
if (fs::is_directory(asset)) {
fs::path src = depBinDir / asset.filename();
if (!fs::exists(src)) continue;
place(outputDir / asset.filename(), src);
copyTree(src, outputDir / asset.filename());
continue;
}
std::string ext = asset.extension().string();
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(c)));
fs::path srcName = asset.filename();
if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") {
srcName.replace_extension(".ctex");
} else if (ext == ".obj") {
srcName.replace_extension(".cmesh");
} else {
continue;
}
fs::path src = depBinDir / srcName;
const std::optional<fs::path> srcName = CompressedAssetName(asset);
if (!srcName) continue;
fs::path src = depBinDir / *srcName;
if (!fs::exists(src)) continue;
copyTree(src, outputDir / srcName);
place(outputDir / *srcName, src);
copyTree(src, outputDir / *srcName);
}
for (Configuration* sub : dep->dependencies) forwardDepArtifacts(sub);
};
@ -1219,18 +1326,29 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
}
// The program loads its shared dependencies from where they were built,
// the external cache among them. ExternalOutputs leaves the mingw target
// without any: PE resolves DLLs another way.
for (const std::string& dir : buildResult.runPaths) linkExtras += RunPathFlags(dir);
// without any: PE resolves DLLs another way. A Flatpak has none of those
// directories once installed, and nothing outside its own /app and the
// runtime: WriteFlatpak copies what the program needs from them into
// files/lib, beside files/bin, and that is the one place it looks, under
// -r as well as installed.
const bool flatpak = config.ResolvedPackaging() == Packaging::Flatpak;
if (flatpak) {
linkExtras += " -Wl,-rpath,'$ORIGIN/../lib'";
} else {
for (const std::string& dir : buildResult.runPaths) linkExtras += RunPathFlags(dir);
}
// Link-only LTO/section flags (empty in Debug and for wasm). Every exe/lib
// link below ends with linkExtras, so this reaches them all; the static-lib
// archive path uses ar instead and is handled separately.
linkExtras += ltoLinkFlags;
// Host links use the toolchain's own libc++. When the toolchain lives
// outside /usr (a bundled one) the binary needs an rpath to find
// libc++.so.1 at run time. mingw links libstdc++ and every sysroot build
// (wasm included) brings its own libc++.
// libc++.so.1 at run time; a Flatpak finds the copy in its files/lib
// through the run path above instead, as it does anything else this -L
// lets the link take from that directory. mingw links libstdc++ and
// every sysroot build (wasm included) brings its own libc++.
if (config.target != "x86_64-w64-mingw32" && config.sysroot.empty()) {
linkExtras += GetToolchain().LibcxxLinkFlags();
linkExtras += flatpak ? GetToolchain().LibcxxSearchFlags() : GetToolchain().LibcxxLinkFlags();
}
// mingw uses libstdc++; C++26 std::print/format extras live in libstdc++exp.
// libstdc++ on mingw uses winpthreads for std::atomic_wait /
@ -1421,13 +1539,20 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
buildResult.libs.insert(std::format("-l{}", config.outputName));
}
// A program built on a shared library loads it from where it was linked
// from: its run path names this directory. Only for the consumers: the
// library's own link is done. On Windows a DLL is found beside the
// from: its run path names this directory, or, packaged as a Flatpak, it
// carries a copy in files/lib, taken from here. Only for the consumers:
// the library's own link is done. On Windows a DLL is found beside the
// program instead, where the mingw link copies it.
if (config.type == ConfigurationType::LibraryDynamic && config.target != "x86_64-w64-mingw32") {
buildResult.runPaths.insert(fs::absolute(outputDir).string());
}
// After every build, linked or not: the writer changes only what differs,
// and a permission or desktop file can change without a link.
if (buildResult.result.empty() && flatpak) {
buildResult.result = WriteFlatpak(config, buildResult, placed);
}
// Browser-wasm feature-detected variants. The baseline outputName.wasm is
// now built (above). For each declared variant, recompile the entire build
// graph with the variant's extra codegen flags and drop the result next to
@ -1545,21 +1670,10 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) {
// wasm side. Basename collisions across subdirs aren't supported on
// the wasi runtime today; if two assets share a basename, the last
// one preloaded wins. Avoid collisions in the source tree.
auto compressedExt = [](const fs::path& src) -> std::optional<std::string> {
std::string ext = src.extension().string();
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(c)));
if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") {
return std::string(".ctex");
}
if (ext == ".obj") return std::string(".cmesh");
return std::nullopt;
};
auto compressedRel = [&](const fs::path& rel) -> fs::path {
if (auto ext = compressedExt(rel)) {
fs::path out = rel;
out.replace_extension(*ext);
return out;
}
// The name Build() writes an asset under, by the rule its own copy uses,
// so the manifest cannot list a file the build never wrote.
auto compressedRel = [](const fs::path& rel) -> fs::path {
if (const std::optional<fs::path> name = CompressedAssetName(rel)) return rel.parent_path() / *name;
return rel;
};
std::vector<std::string> assetFiles;
@ -1581,8 +1695,9 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) {
}
// cfg.assets — mirror the bin-dir layout the build emits: a
// directory entry becomes <topName>/<rel inside dir>, single
// files land flat at the bin root. .png/.obj are compressed in
// place; everything else passes through under its original name.
// files land flat at the bin root. What CompressedAssetName maps
// is compressed in place; everything else passes through under its
// original name.
for (const fs::path& a : c->assets) {
if (fs::is_directory(a)) {
const fs::path topName = a.filename();
@ -1747,6 +1862,14 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span<const std::str
else if (a.starts_with("--march=")) cfg.march = std::string(a.substr(std::string_view("--march=").size()));
else if (a.starts_with("--mtune=")) cfg.mtune = std::string(a.substr(std::string_view("--mtune=").size()));
else if (a.starts_with("--sysroot=")) cfg.sysroot = std::string(a.substr(std::string_view("--sysroot=").size()));
else if (a.starts_with("--packaging=")) {
const std::string_view kind = a.substr(std::string_view("--packaging=").size());
if (kind != "none" && kind != "flatpak") throw std::invalid_argument(std::format("--packaging={}: expected none or flatpak", kind));
// The args reach every dependency the project loads, whose
// executables stay as linked: their consumers run them by path.
// So only the project crafter-build was pointed at reads it.
if (IsTopLevelProject()) cfg.packaging = kind == "flatpak" ? Packaging::Flatpak : Packaging::None;
}
// Anything else is the project's own flag. Its effect on the output is
// opaque to the framework, so it has to key into VariantId or two flag
// settings share a bin dir and leave a bundle matching neither.

View file

@ -368,6 +368,12 @@ namespace {
for (fs::path& p : cfg.files) p = abs(p);
for (fs::path& p : cfg.buildFiles) p = abs(p);
for (Shader& s : cfg.shaders) s.path = abs(s.path);
// A dependency that packages its own executable as a Flatpak names
// the files it is installed with as it names its cfg.files. An
// empty one is none, and stays empty.
if (!cfg.flatpak.desktopFile.empty()) cfg.flatpak.desktopFile = abs(cfg.flatpak.desktopFile);
if (!cfg.flatpak.metainfo.empty()) cfg.flatpak.metainfo = abs(cfg.flatpak.metainfo);
for (fs::path& p : cfg.flatpak.icons) p = abs(p);
return cfg;
}

View file

@ -0,0 +1,380 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Crafter.Build:Flatpak_impl;
import :Flatpak;
import :Platform;
import :Progress;
import std;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
// flatpak's own rule for the characters of a name's segments: a dash is
// allowed in the last segment only, a digit anywhere but first.
bool NameStart(char c, bool lastSegment) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (lastSegment && c == '-');
}
bool NameChar(char c, bool lastSegment) {
return NameStart(c, lastSegment) || (c >= '0' && c <= '9');
}
std::string_view Trim(std::string_view s) {
while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\n' || s.front() == '\r')) s.remove_prefix(1);
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\n' || s.back() == '\r')) s.remove_suffix(1);
return s;
}
std::vector<std::string_view> Split(std::string_view s, char separator) {
std::vector<std::string_view> parts;
for (std::size_t begin = 0;;) {
const std::size_t end = s.find(separator, begin);
parts.push_back(s.substr(begin, end == std::string_view::npos ? std::string_view::npos : end - begin));
if (end == std::string_view::npos) return parts;
begin = end + 1;
}
}
// ---- the files ----
std::string ReadAll(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error(std::format("could not read {}", path.string()));
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// Whether `b` is a regular file holding exactly what `a` does: by size,
// then a block at a time, so comparing costs the same memory whatever
// the files' size. Reading both whole held twice the largest file on
// every build that had nothing to copy, and failed where that did not
// fit.
bool SameContent(const fs::path& a, const fs::path& b) {
std::error_code ec;
if (!fs::is_regular_file(b, ec) || fs::is_symlink(b, ec)) return false;
if (fs::file_size(a) != fs::file_size(b, ec) || ec) return false;
std::ifstream left(a, std::ios::binary);
if (!left) throw std::runtime_error(std::format("could not read {}", a.string()));
std::ifstream right(b, std::ios::binary);
if (!right) return false;
constexpr std::size_t Block = 64 * 1024;
std::vector<char> x(Block);
std::vector<char> y(Block);
while (left && right) {
left.read(x.data(), static_cast<std::streamsize>(Block));
right.read(y.data(), static_cast<std::streamsize>(Block));
if (left.gcount() != right.gcount() || !std::equal(x.begin(), x.begin() + left.gcount(), y.begin())) return false;
}
return left.eof() && right.eof();
}
// Writes `content` to `path` unless the file already holds exactly that,
// so an unchanged build leaves its mtime alone.
void WriteIfDifferent(const fs::path& path, std::string_view content) {
std::error_code ec;
if (fs::is_regular_file(path, ec) && !fs::is_symlink(path, ec) && fs::file_size(path, ec) == content.size() && ReadAll(path) == content) return;
fs::create_directories(path.parent_path());
fs::remove(path, ec);
std::ofstream out(path, std::ios::binary | std::ios::trunc);
out.write(content.data(), static_cast<std::streamsize>(content.size()));
if (!out) throw std::runtime_error(std::format("could not write {}", path.string()));
}
// Makes `dir` hold exactly `wanted`, relative path to the file copied
// there, and nothing else: every other file goes, and the directories
// left empty. A copy is made only when its content differs, and anything
// in the way is replaced rather than written through, a link included.
// Returns the relative paths it copied.
std::set<fs::path> SyncOwned(const fs::path& dir, const std::map<fs::path, fs::path>& wanted) {
std::set<fs::path> copied;
std::error_code ec;
if (fs::exists(dir, ec)) {
std::vector<fs::path> files;
std::vector<fs::path> dirs;
for (const fs::directory_entry& entry : fs::recursive_directory_iterator(dir)) {
if (entry.is_directory() && !entry.is_symlink()) dirs.push_back(entry.path());
else if (!wanted.contains(entry.path().lexically_relative(dir))) files.push_back(entry.path());
}
for (const fs::path& file : files) fs::remove(file);
// Deepest first, so a parent is empty by the time it is looked at.
std::ranges::sort(dirs, std::greater{});
for (const fs::path& d : dirs) {
if (fs::is_empty(d)) fs::remove(d);
}
}
for (const auto& [relative, source] : wanted) {
const fs::path target = dir / relative;
if (!fs::exists(source)) throw std::runtime_error(std::format("{} does not exist", source.string()));
if (SameContent(source, target)) continue;
fs::create_directories(target.parent_path());
if (fs::is_directory(target, ec) && !fs::is_symlink(target, ec)) fs::remove_all(target);
else fs::remove(target, ec);
fs::copy_file(source, target);
copied.insert(relative);
}
return copied;
}
// Where an icon goes under share/: an .svg as scalable, a .png in the
// directory of its own size, read from its header.
fs::path IconPath(const fs::path& icon, std::string_view appId) {
std::string ext = icon.extension().string();
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(c)));
if (ext == ".svg") return fs::path("icons") / "hicolor" / "scalable" / "apps" / std::format("{}.svg", appId);
if (ext != ".png") throw std::runtime_error(std::format("{}: an icon has to be an .svg or a .png", icon.string()));
const std::string header = ReadAll(icon).substr(0, 24);
if (header.size() < 24 || !header.starts_with("\x89PNG\r\n\x1a\n") || header.substr(12, 4) != "IHDR") {
throw std::runtime_error(std::format("{}: not a PNG file", icon.string()));
}
const auto bigEndian = [&](std::size_t at) {
std::uint32_t value = 0;
for (std::size_t i = 0; i < 4; ++i) value = (value << 8) | static_cast<std::uint8_t>(header[at + i]);
return value;
};
const std::uint32_t width = bigEndian(16);
const std::uint32_t height = bigEndian(20);
if (width != height) throw std::runtime_error(std::format("{}: an icon has to be square, this one is {}x{}", icon.string(), width, height));
return fs::path("icons") / "hicolor" / std::format("{}x{}", width, width) / "apps" / std::format("{}.png", appId);
}
// The Icon= of a desktop entry's [Desktop Entry] group; empty without one.
std::string DesktopIcon(const fs::path& desktopFile) {
bool inEntry = false;
for (const std::string_view line : Split(ReadAll(desktopFile), '\n')) {
const std::string_view t = Trim(line);
if (t.starts_with("[")) {
inEntry = t == "[Desktop Entry]";
continue;
}
if (!inEntry) continue;
// The key and the value either side of the first '=', without
// the space the Desktop Entry spec lets surround it: `Icon =
// other` is Icon=other to desktop-file-validate and to flatpak.
const std::size_t eq = t.find('=');
if (eq != std::string_view::npos && Trim(t.substr(0, eq)) == "Icon") return std::string(Trim(t.substr(eq + 1)));
}
return "";
}
// ---- the libraries ----
// The libraries clang links into every C++ program it builds against its
// libc++. They are looked up one by one, never by searching the
// directory they are in: on a distribution that keeps libc++ in
// /usr/lib64, that directory holds libc.so.6 as well.
constexpr std::array<std::string_view, 3> LlvmRuntimeLibraries = {"libc++.so.1", "libc++abi.so.1", "libunwind.so.1"};
// The toolchain's own copy of `name`, as the link finds it; empty when
// clang has none (Arch's LLVM ships no libunwind.so.1). Asked once per
// name and process.
fs::path ToolchainLibrary(const fs::path& clangxx, std::string_view name) {
static std::mutex Mutex;
static std::map<std::string, fs::path, std::less<>> Found;
std::lock_guard lock(Mutex);
if (auto it = Found.find(name); it != Found.end()) return it->second;
const CommandResult r = RunCommandChecked(std::format("{} -print-file-name={}", ShellQuote(clangxx.string()), name));
// clang prints the bare name back when it has no such file.
fs::path path = Trim(r.output);
std::error_code ec;
if (r.exitCode != 0 || !path.is_absolute() || !fs::exists(path, ec)) path.clear();
else path = path.lexically_normal();
Found.emplace(std::string(name), path);
return path;
}
std::vector<std::string> NeededLibraries(const fs::path& readelf, const fs::path& file) {
const CommandResult r = RunCommandChecked(std::format("{} --needed-libs {}", ShellQuote(readelf.string()), ShellQuote(file.string())));
if (r.exitCode != 0) {
throw std::runtime_error(std::format("{} could not read {}: {}", readelf.filename().string(), file.string(), Trim(r.output)));
}
std::vector<std::string> names;
bool inList = false;
for (const std::string_view line : Split(r.output, '\n')) {
const std::string_view t = Trim(line);
if (!inList) {
inList = t.starts_with("NeededLibraries [");
continue;
}
if (t == "]") break;
if (!t.empty()) names.emplace_back(t);
}
return names;
}
// The files `program` needs that are not the runtime's, with what they
// need in turn: the LLVM runtime libraries, and any NEEDED name found in
// one of `dirs`, the first one holding it winning as for the loader.
std::vector<fs::path> Libraries(const FlatpakFiles& d, const fs::path& program) {
std::vector<fs::path> libraries;
std::set<std::string> seen;
std::deque<fs::path> pending = {program};
while (!pending.empty()) {
const fs::path file = std::move(pending.front());
pending.pop_front();
for (const std::string& name : NeededLibraries(d.readelf, file)) {
if (!seen.insert(name).second) continue;
fs::path found;
if (std::ranges::contains(LlvmRuntimeLibraries, std::string_view(name))) found = ToolchainLibrary(d.clangxx, name);
std::error_code ec;
for (const fs::path& dir : d.libraryDirs) {
if (!found.empty()) break;
if (fs::exists(dir / name, ec)) found = dir / name;
}
if (found.empty()) continue;
libraries.push_back(found);
pending.push_back(found);
}
}
return libraries;
}
// ---- the record ----
// What a write placed, kept so the next one knows which files in
// files/bin were the build's.
struct Record {
std::set<std::string> placed;
};
Record ReadRecord(const fs::path& file) {
Record record;
std::error_code ec;
if (!fs::exists(file, ec)) return record;
for (const std::string_view line : Split(ReadAll(file), '\n')) {
const std::size_t tab = line.find('\t');
if (tab == std::string_view::npos) continue;
const std::string_view kind = line.substr(0, tab);
const std::string value(line.substr(tab + 1));
if (kind == "placed") record.placed.insert(value);
}
return record;
}
void WriteRecord(const fs::path& file, const Record& record) {
std::string text;
for (const std::string& name : record.placed) text += std::format("placed\t{}\n", name);
WriteIfDifferent(file, text);
}
}
std::string Crafter::DefaultFlatpakAppId(std::string_view outputName) {
std::string segment;
for (const char c : outputName) segment.push_back(NameChar(c, true) ? c : '_');
if (segment.empty() || !NameStart(segment.front(), true)) segment.insert(segment.begin(), '_');
return std::format("local.crafterbuild.{}", segment);
}
std::string Crafter::FlatpakAppIdError(std::string_view appId) {
if (appId.empty()) return "it is empty";
if (appId.size() > 255) return "it is longer than 255 characters";
const std::vector<std::string_view> segments = Split(appId, '.');
if (segments.size() < 3) return "it needs at least three segments, like org.example.App";
for (std::size_t i = 0; i < segments.size(); ++i) {
const std::string_view segment = segments[i];
const bool last = i + 1 == segments.size();
if (segment.empty()) return "it has an empty segment";
for (std::size_t j = 0; j < segment.size(); ++j) {
const char c = segment[j];
if (j == 0 ? NameStart(c, last) : NameChar(c, last)) continue;
if (c == '-') return std::format("its segment '{}' has a '-', which only the last segment may have", segment);
if (j == 0 && c >= '0' && c <= '9') return std::format("its segment '{}' starts with a digit", segment);
return std::format("it holds '{}', which an application ID cannot", c);
}
}
return "";
}
void Crafter::RecordFlatpakPlaced(const fs::path& record, const std::set<std::string>& names) {
try {
Record merged = ReadRecord(record);
const std::size_t before = merged.placed.size();
merged.placed.insert(names.begin(), names.end());
if (merged.placed.size() == before) return;
std::error_code ec;
fs::create_directories(record.parent_path(), ec);
WriteRecord(record, merged);
} catch (const std::exception&) {
// Not written: the next write takes those names for the program's,
// and says so, which is all a record that cannot be written costs.
}
}
std::string Crafter::WriteFlatpakFiles(const FlatpakFiles& d) {
if (const std::string bad = FlatpakAppIdError(d.appId); !bad.empty()) {
return std::format("{} is not a Flatpak application ID: {}", d.appId, bad);
}
try {
const fs::path files = d.root / "files";
const fs::path program = files / "bin" / d.command;
const Record old = ReadRecord(d.record);
Record now;
// Worked out on every write, from the program and what each library
// it carries needs in turn, which reads only their dynamic sections:
// a library replaced in place, as by a toolchain update, can need
// others, and only reading it again finds them. -r would not show a
// library missing, as crafter-build's sandbox has its own /app/lib on
// the loader's path; the installed app would not start.
std::map<fs::path, fs::path> libraries;
for (const fs::path& library : Libraries(d, program)) libraries.emplace(library.filename(), library);
SyncOwned(files / "lib", libraries);
std::map<fs::path, fs::path> share;
const fs::path desktopEntry = fs::path("applications") / std::format("{}.desktop", d.appId);
if (!d.desktopFile.empty()) {
if (!fs::exists(d.desktopFile)) return std::format("{}: the desktop file {} does not exist", d.appId, d.desktopFile.string());
if (const std::string icon = DesktopIcon(d.desktopFile); !icon.empty() && icon != d.appId) {
return std::format("{}: its Icon= is {}, and has to be the app-id, {}, which its icons are installed as", d.desktopFile.string(), icon, d.appId);
}
share.emplace(desktopEntry, d.desktopFile);
}
if (!d.metainfo.empty()) {
const fs::path metainfo = fs::path("metainfo") / std::format("{}.metainfo.xml", d.appId);
share.emplace(metainfo, d.metainfo);
}
for (const fs::path& icon : d.icons) {
const fs::path relative = IconPath(icon, d.appId);
if (share.contains(relative)) return std::format("{}: two icons go to {}", d.appId, relative.string());
share.emplace(relative, icon);
}
SyncOwned(files / "share", share);
// desktop-file-validate checks the entry here, where it was written,
// on every write that places one, not only one that copies it: a
// write that copied the entry and then failed would leave it
// unchecked for every write after. Where the tool exists: the Sdk has
// it, a development box may not.
if (share.contains(desktopEntry) && RunCommandChecked("command -v desktop-file-validate").exitCode == 0) {
const CommandResult r = RunCommandChecked(std::format("desktop-file-validate {}", ShellQuote((files / "share" / desktopEntry).string())));
if (r.exitCode != 0) {
std::error_code ec;
fs::remove(files / "share" / desktopEntry, ec);
return std::format("{} does not pass desktop-file-validate:\n{}", d.desktopFile.string(), Trim(r.output));
}
}
// In files/bin, what an earlier write placed and this one does not
// is a stale build output, a removed cfg.files entry or a renamed
// shader. What neither placed the program wrote, under -r, since it
// runs there.
std::vector<std::string> foreign;
for (const fs::directory_entry& entry : fs::directory_iterator(files / "bin")) {
const std::string name = entry.path().filename().string();
if (d.programEntries.contains(name)) continue;
if (old.placed.contains(name)) fs::remove_all(entry.path());
else foreign.push_back(name);
}
now.placed = d.programEntries;
if (!foreign.empty()) {
std::ranges::sort(foreign);
std::string names;
for (const std::string& name : foreign) names += std::format("{}{}", names.empty() ? "" : ", ", name);
Progress::Diagnostic(std::format("{}: {} in {} {} not put there by the build, so the program wrote {}, presumably under -r. {} with the app; installed, /app is read-only and a program cannot write there.", d.appId, names, (files / "bin").string(), foreign.size() == 1 ? "was" : "were", foreign.size() == 1 ? "it" : "them", foreign.size() == 1 ? "It ships" : "They ship"));
}
WriteRecord(d.record, now);
} catch (const std::exception& e) {
return std::format("{}: {}", d.appId, e.what());
}
return "";
}

View file

@ -8,6 +8,7 @@ export module Crafter.Build:Lint_impl;
import std;
import :Lint;
import :Clang;
import :Test;
import :Platform;
import :Toolchain;
import :Progress;
@ -1084,6 +1085,8 @@ LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& op
: opts.projectFile.parent_path();
std::vector<Configuration*> localConfigs = CollectLocalConfigs(projectCfg, projectRoot);
// The tests' compile commands are worked out as RunTests builds them.
for (Configuration* c : localConfigs) UnpackageTests(*c);
// Collect rules root-first, dedup by name (first registration wins).
std::vector<const LintRule*> rules;

View file

@ -878,10 +878,11 @@ std::string Crafter::GetBaseCommand(const Configuration& config) {
}
namespace {
constexpr std::array<std::string_view, 14> CrafterBuildModules = {
constexpr std::array<std::string_view, 15> CrafterBuildModules = {
"Crafter.Build-Toolchain",
"Crafter.Build-Shader",
"Crafter.Build-Platform",
"Crafter.Build-Flatpak",
"Crafter.Build-Interface",
"Crafter.Build-Implementation",
"Crafter.Build-External",

View file

@ -442,7 +442,12 @@ TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> d) {
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; }
void Crafter::UnpackageTests(Configuration& cfg) {
for (Test& test : cfg.tests) test.config.packaging = Packaging::None;
}
TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
UnpackageTests(projectCfg);
// Multi-target sweep: when no --target= was given, the run covers every
// distinct target declared across projectCfg.tests plus the host target.
// Lets a bare `crafter-build test` exercise cross-arch tests without the

View file

@ -21,9 +21,40 @@ namespace {
"CRAFTER_BUILD_LIBCXX_DIR",
"CRAFTER_BUILD_LIBCLANG",
"CRAFTER_BUILD_WASI_SYSROOT",
"CRAFTER_BUILD_FLATPAK_INFO",
"CRAFTER_MINGW_DIR",
};
// The arch and branch of the runtime=runtime/<id>/<arch>/<branch> line
// in the [Application] group of a .flatpak-info; empty when it has none.
std::pair<std::string, std::string> FlatpakRuntimeOf(std::string_view info) {
bool inApplication = false;
for (std::size_t begin = 0; begin < info.size();) {
std::size_t end = info.find('\n', begin);
if (end == std::string_view::npos) end = info.size();
std::string_view line = info.substr(begin, end - begin);
begin = end + 1;
if (line.ends_with('\r')) line.remove_suffix(1);
if (line.starts_with("[")) {
inApplication = line == "[Application]";
continue;
}
if (!inApplication || !line.starts_with("runtime=")) continue;
std::vector<std::string_view> parts;
std::string_view ref = line.substr(std::string_view("runtime=").size());
for (std::size_t at = 0;;) {
const std::size_t slash = ref.find('/', at);
parts.push_back(ref.substr(at, slash == std::string_view::npos ? std::string_view::npos : slash - at));
if (slash == std::string_view::npos) break;
at = slash + 1;
}
if (parts.size() == 4 && parts[0] == "runtime" && !parts[2].empty() && !parts[3].empty()) {
return {std::string(parts[2]), std::string(parts[3])};
}
}
return {};
}
std::string_view Env(const ToolchainInputs& in, std::string_view name) {
auto it = in.env.find(name);
return it == in.env.end() ? std::string_view{} : std::string_view(it->second);
@ -81,20 +112,27 @@ std::string Toolchain::LibcxxCompileFlags() const {
return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string());
}
// clang searches its per-target runtime directory and the system library
// paths for -lc++, not <prefix>/lib, so a toolchain outside /usr with the
// classic layout needs the search path as well as the run-time path.
fs::path Toolchain::LibcxxLibDir() const {
if (!libcxxDir.empty()) return libcxxDir / "lib";
if (!prefix.empty() && prefix != "/usr") return prefix / "lib";
return {};
}
std::string Toolchain::LibcxxLinkFlags() const {
// clang searches its per-target runtime directory and the system library
// paths for -lc++, not <prefix>/lib, so a toolchain outside /usr with the
// classic layout needs the search path as well as the run-time path.
fs::path lib;
if (!libcxxDir.empty()) {
lib = libcxxDir / "lib";
} else if (!prefix.empty() && prefix != "/usr") {
lib = prefix / "lib";
}
const fs::path lib = LibcxxLibDir();
if (lib.empty()) return {};
return std::format(" -L{} -Wl,-rpath,{}", lib.string(), lib.string());
}
std::string Toolchain::LibcxxSearchFlags() const {
const fs::path lib = LibcxxLibDir();
if (lib.empty()) return {};
return std::format(" -L{}", lib.string());
}
std::string Toolchain::Key() const {
std::string identity;
for (const std::string& part : {clangxx.string(), clangVersion, libcxxDir.string(), stdCppm.string()}) {
@ -124,10 +162,12 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.clangxx = "clang++";
tc.clang = "clang";
tc.llvmAr = "llvm-ar";
tc.llvmReadelf = "llvm-readelf";
} else {
tc.clangxx = tc.prefix / "bin" / "clang++";
tc.clang = tc.prefix / "bin" / "clang";
tc.llvmAr = tc.prefix / "bin" / "llvm-ar";
tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf";
if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) {
tc.llvmIncludeDir = tc.prefix / "include";
}
@ -181,6 +221,7 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.mingwPrefix = PrefixPath(in.hostRoot / "usr");
tc.mingwPrefixIsSystem = true;
}
std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo);
return tc;
}
@ -198,6 +239,13 @@ const Toolchain& Crafter::GetToolchain() {
in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path();
} catch (const std::exception&) {}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
{
auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO");
const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info");
if (std::ifstream file(info, std::ios::binary); file) {
in.flatpakInfo.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
}
Toolchain tc = ResolveToolchain(in);
if (!tc.error.empty()) return tc;