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

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("hello from a Flatpak");
return 0;
}

View file

@ -0,0 +1 @@
read beside the program

View file

@ -0,0 +1,181 @@
// 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;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The NEEDED entries of an ELF file, by the toolchain's llvm-readelf.
std::set<std::string> Needed(const fs::path& readelf, const fs::path& file) {
const auto r = RunCommandWithTimeout(std::format("{} --needed-libs {}", ShellQuote(readelf.string()), ShellQuote(file.string())), std::chrono::seconds(30));
std::set<std::string> names;
bool inList = false;
std::istringstream lines(r.output);
for (std::string line; std::getline(lines, line);) {
const std::size_t first = line.find_first_not_of(" \t");
const std::string t = first == std::string::npos ? std::string() : line.substr(first);
if (!inList) {
inList = t.starts_with("NeededLibraries [");
continue;
}
if (t == "]") break;
if (!t.empty()) names.insert(t);
}
return names;
}
// Whether the toolchain has its own copy of an LLVM runtime library.
bool ToolchainHas(const fs::path& clangxx, std::string_view name) {
const auto r = RunCommandWithTimeout(std::format("{} -print-file-name={}", ShellQuote(clangxx.string()), name), std::chrono::seconds(30));
std::string out = r.output;
while (!out.empty() && (out.back() == '\n' || out.back() == '\r')) out.pop_back();
const fs::path path = out;
std::error_code ec;
return r.exitCode == 0 && path.is_absolute() && fs::exists(path, ec);
}
std::map<fs::path, fs::file_time_type> Mtimes(const fs::path& root) {
std::map<fs::path, fs::file_time_type> times;
for (const fs::directory_entry& entry : fs::recursive_directory_iterator(root)) {
if (entry.is_regular_file()) times.emplace(entry.path(), entry.last_write_time());
}
return times;
}
}
// An executable packaged as a Flatpak comes out as the files/ of a Flatpak
// build directory, what becomes /app: the program and its files in
// files/bin, which ExpectedOutput and ProgramDir name, and in files/lib
// exactly the libraries of the toolchain the program needs, found there
// through its one run path, $ORIGIN/../lib. The Platform has no libc++, so
// an app without them would not start. The metadata and export/ are flatpak
// build-finish's to write, so the build writes neither. A second build
// changes nothing. The runtime is staged through CRAFTER_BUILD_FLATPAK_INFO,
// so the native loop packages too; inside the Flatpak the staged file wins
// over the sandbox's own.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-output";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
// Before anything asks for the toolchain, which reads it once.
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
const Toolchain& tc = GetToolchain();
if (NormalizeTarget(tc.hostTriple) != "x86_64-linux-gnu") {
std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", tc.hostTriple);
return 77;
}
if (!tc.libcxxDir.empty()) {
std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak");
return 77;
}
Check(tc.flatpakArch == "x86_64" && tc.flatpakBranch == "26.08", std::format("the staged runtime is read: '{}' '{}'", tc.flatpakArch, tc.flatpakBranch));
const fs::path fixture = fs::current_path() / "tests" / "FlatpakOutput" / "fixture";
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
Configuration app;
app.path = fixture;
app.name = "flatpak-hello";
app.outputName = "hello";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.files.push_back(fixture / "message.txt");
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult r = Build(app, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", r.result);
return 1;
}
}
const fs::path root = app.BinDir();
const fs::path program = ExpectedOutput(app);
Check(app.ProgramDir() == root / "files" / "bin", std::format("ProgramDir is files/bin: {}", app.ProgramDir().string()));
Check(program == root / "files" / "bin" / "hello", std::format("ExpectedOutput is files/bin/hello: {}", program.string()));
Check(fs::is_regular_file(program), "the program is linked into files/bin");
Check(fs::is_regular_file(root / "files" / "bin" / "message.txt"), "cfg.files land beside the program");
Check(!fs::exists(root / "metadata") && !fs::exists(root / "export"), "no metadata or export/, which flatpak build-finish writes");
// files/lib holds what the toolchain links and the program needs, and
// nothing the runtime has.
const fs::path lib = root / "files" / "lib";
std::set<std::string> bundled;
for (const fs::directory_entry& entry : fs::directory_iterator(lib, ec)) bundled.insert(entry.path().filename().string());
std::set<std::string> needed = Needed(tc.llvmReadelf, program);
for (const std::string& name : bundled) needed.merge(Needed(tc.llvmReadelf, lib / name));
Check(bundled.contains("libc++.so.1"), "libc++.so.1 is bundled");
for (const std::string_view name : {"libc++.so.1", "libc++abi.so.1", "libunwind.so.1"}) {
if (needed.contains(std::string(name)) && ToolchainHas(tc.clangxx, name)) Check(bundled.contains(std::string(name)), std::format("{}, which the toolchain links, is bundled", name));
}
for (const std::string& name : bundled) Check(needed.contains(name), std::format("{} is bundled because something needs it", name));
for (const std::string_view name : {"libc.so.6", "libm.so.6", "libgcc_s.so.1", "ld-linux-x86-64.so.2"}) {
Check(!bundled.contains(std::string(name)), std::format("{}, the runtime's, is not bundled", name));
}
const auto dynamic = RunCommandWithTimeout(std::format("{} -d {}", ShellQuote(tc.llvmReadelf.string()), ShellQuote(program.string())), std::chrono::seconds(30));
Check(dynamic.output.contains("Library runpath: [$ORIGIN/../lib]"), std::format("the one run path is $ORIGIN/../lib:\n{}", dynamic.output));
// The loader takes libc++ from files/lib, not from wherever the
// toolchain keeps it.
if (std::system("command -v ldd > /dev/null 2>&1") == 0) {
// Without LD_LIBRARY_PATH, which flatpak-builder's build sandbox, where
// CI runs this suite, sets to /app/lib ahead of the program's run path:
// the check is what the installed app's loader does, and `flatpak run`
// sets none.
const auto ldd = RunCommandWithTimeout(std::format("env -u LD_LIBRARY_PATH ldd {}", ShellQuote(program.string())), std::chrono::seconds(30));
std::istringstream lines(ldd.output);
bool resolved = false;
for (std::string line; std::getline(lines, line);) {
const std::size_t arrow = line.find("libc++.so.1 => ");
if (arrow == std::string::npos) continue;
const std::string rest = line.substr(arrow + std::string_view("libc++.so.1 => ").size());
const fs::path path = rest.substr(0, rest.find(" ("));
resolved = fs::equivalent(path, lib / "libc++.so.1", ec);
}
Check(resolved, std::format("libc++.so.1 resolves to the bundled copy:\n{}", ldd.output));
}
const auto run = RunCommandWithTimeout(ShellQuote(program.string()), std::chrono::seconds(30));
Check(run.exitCode == 0 && run.output.contains("hello from a Flatpak"), std::format("the program runs (exit {}): {}", run.exitCode, run.output));
// A build with nothing to do writes nothing.
const std::map<fs::path, fs::file_time_type> before = Mtimes(root);
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult r = Build(app, depResults, depMutex);
Check(r.result.empty(), std::format("the second build succeeds: {}", r.result));
}
Check(Mtimes(root) == before, "a second build leaves every file of the bin dir alone");
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}