diff --git a/AGENTS.template.md b/AGENTS.template.md index 92af9e1..61c7362 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -121,7 +121,7 @@ Beyond the rules: - Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule. - There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. -- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads at run time land, and the directory `-r` runs a host executable in and serves a browser build from; `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. +- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. - Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`) and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. ## Design rules diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index d65465e..26b5cb0 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -667,6 +667,8 @@ namespace { d.desktopFile = config.flatpak.desktopFile; d.metainfo = config.flatpak.metainfo; d.icons = config.flatpak.icons; + d.share = config.flatpak.share; + d.appDir = FlatpakAppDir(config); d.clangxx = tc.clangxx; d.readelf = tc.llvmReadelf; for (const std::string& dir : linked.runPaths) d.libraryDirs.emplace_back(dir); diff --git a/implementations/Crafter.Build-External.cpp b/implementations/Crafter.Build-External.cpp index 5a3d395..3fb8fe9 100644 --- a/implementations/Crafter.Build-External.cpp +++ b/implementations/Crafter.Build-External.cpp @@ -375,6 +375,9 @@ namespace { if (!cfg.flatpak.metainfo.empty()) cfg.flatpak.metainfo = abs(cfg.flatpak.metainfo); for (fs::path& p : cfg.flatpak.icons) p = abs(p); for (fs::path& p : cfg.flatpak.modules) p = abs(p); + for (auto& entry : cfg.flatpak.share) { + if (!entry.source.empty()) entry.source = abs(entry.source); + } return cfg; } diff --git a/implementations/Crafter.Build-Flatpak.cpp b/implementations/Crafter.Build-Flatpak.cpp index 8b52ea7..00228ed 100644 --- a/implementations/Crafter.Build-Flatpak.cpp +++ b/implementations/Crafter.Build-Flatpak.cpp @@ -115,6 +115,46 @@ namespace { return copied; } + // Whether `path` is `ancestor` or lies inside it, element by element. + bool Within(const fs::path& path, const fs::path& ancestor) { + return std::mismatch(ancestor.begin(), ancestor.end(), path.begin(), path.end()).first == ancestor.end(); + } + + // Whether `outer` is `inner` or holds it, as written or where their + // links lead: a project whose bin/ is a link elsewhere holds its files/ + // as written, and not once the link is followed. + bool Holds(const fs::path& outer, const fs::path& inner) { + std::error_code ec; + if (Within(fs::absolute(inner, ec).lexically_normal(), fs::absolute(outer, ec).lexically_normal())) return true; + const fs::path realOuter = fs::weakly_canonical(outer, ec); + if (ec || realOuter.empty()) return false; + const fs::path realInner = fs::weakly_canonical(inner, ec); + if (ec || realInner.empty()) return false; + return Within(realInner, realOuter); + } + + // Adds `relative` to the files a directory is to hold, copied from + // `source`, unless that would put two files at one path, or a file where + // another needs a directory: one share entry over another, or two icons + // of one size. SyncOwned would otherwise copy whichever came last, or + // fail halfway with a filesystem error. + std::string Place(std::map& files, const fs::path& relative, const fs::path& source) { + if (auto it = files.find(relative); it != files.end()) { + return std::format("{} and {} both go to share/{}", it->second.string(), source.string(), relative.string()); + } + // What lies inside a path sorts right after it, element by element. + if (auto it = files.upper_bound(relative); it != files.end() && Within(it->first, relative)) { + return std::format("{} would make share/{} a file, where {} needs it to be a directory", source.string(), relative.string(), it->second.string()); + } + for (fs::path parent = relative.parent_path(); !parent.empty(); parent = parent.parent_path()) { + if (auto it = files.find(parent); it != files.end()) { + return std::format("{} needs share/{} to be a directory, where {} makes it a file", source.string(), parent.string(), it->second.string()); + } + } + files.emplace(relative, source); + return ""; + } + // 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) { @@ -324,19 +364,72 @@ std::string Crafter::WriteFlatpakFiles(const FlatpakFiles& d) { 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 (const std::string clash = Place(share, desktopEntry, d.desktopFile); !clash.empty()) return std::format("{}: {}", d.appId, clash); } if (!d.metainfo.empty()) { const fs::path metainfo = fs::path("metainfo") / std::format("{}.metainfo.xml", d.appId); - share.emplace(metainfo, d.metainfo); + if (const std::string clash = Place(share, metainfo, d.metainfo); !clash.empty()) return std::format("{}: {}", d.appId, clash); } 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); + if (const std::string clash = Place(share, relative, icon); !clash.empty()) return std::format("{}: {}", d.appId, clash); + } + // A share entry's file goes where it says, unless the place is + // another file's (Place), a field's included. Whatever it is, a second + // desktop entry or the metainfo of an add-on, say, flatpak checks + // some of what it exports when install or bundle export the app, as + // for any app: an icon that is not a square image, or a D-Bus + // service that is not a key file, stops the export, the app's own + // desktop entry gets a warning where desktop-file-validate rejects it + // or its Icon= is not the app's, and a second desktop entry, a MIME + // package or metainfo goes as it is. The app's own desktop entry and + // the icons the field places are checked here too, at build time. + for (const FlatpakShareEntry& entry : d.share) { + fs::path target = entry.target.lexically_normal(); + if (!target.empty() && !target.has_filename()) target = target.parent_path(); + if (entry.target.is_absolute() || target.empty() || target == "." || *target.begin() == "..") { + return std::format("{}: the share target '{}' of {} has to be a path inside /app/share, relative to it", d.appId, entry.target.string(), entry.source.string()); + } + std::error_code ec; + if (fs::is_directory(entry.source, ec)) { + // A directory that holds what the build writes would be + // copied into itself, growing each time the app is built or + // exported: files/, where share/'s copies land, and the + // app's directory, where install and bundle put another copy + // of files/ and the exported app; the project's own directory + // holds both. One that lies in them is the build's own + // output, which the next build, install or bundle writes + // again, and no file of the project's. + for (const fs::path& output : {files, d.appDir}) { + if (output.empty()) continue; + if (Holds(entry.source, output)) { + return std::format("{}: {} holds {}, which the build writes, so a share entry would copy it into itself, growing each time the app is built or exported: name the files or directories in it instead", d.appId, entry.source.string(), output.string()); + } + if (Holds(output, entry.source)) { + return std::format("{}: {} lies in {}, which the build writes and writes again: a share entry names a file of the project's", d.appId, entry.source.string(), output.string()); + } + } + // Written with a trailing separator, "data/", the directory is + // taken without it, for each file's path inside it. + const fs::path dir = entry.source.has_filename() ? entry.source : entry.source.parent_path(); + for (const fs::directory_entry& file : fs::recursive_directory_iterator(dir)) { + if (!file.is_regular_file()) continue; + if (const std::string clash = Place(share, target / file.path().lexically_relative(dir), file.path()); !clash.empty()) return std::format("{}: {}", d.appId, clash); + } + } else if (fs::is_regular_file(entry.source, ec)) { + if (const std::string clash = Place(share, target, entry.source); !clash.empty()) return std::format("{}: {}", d.appId, clash); + } else { + return std::format("{}: {} does not exist, so it cannot go to share/{}", d.appId, entry.source.string(), target.string()); + } + } + // The app's desktop entry, applications/.desktop, whether + // cfg.flatpak.desktopFile or a share entry placed it: its Icon= has + // to be the app-id, which the app's icons are installed under. + const auto entry = share.find(desktopEntry); + if (entry != share.end()) { + if (const std::string icon = DesktopIcon(entry->second); !icon.empty() && icon != d.appId) { + return std::format("{}: its Icon= is {}, and has to be the app-id, {}, which its icons are installed as", entry->second.string(), icon, d.appId); + } } SyncOwned(files / "share", share); // desktop-file-validate checks the entry here, where it was written, @@ -344,12 +437,12 @@ std::string Crafter::WriteFlatpakFiles(const FlatpakFiles& d) { // 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) { + if (entry != share.end() && 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)); + return std::format("{} does not pass desktop-file-validate:\n{}", entry->second.string(), Trim(r.output)); } } diff --git a/interfaces/Crafter.Build-Flatpak.cppm b/interfaces/Crafter.Build-Flatpak.cppm index 10faa57..e059ec1 100644 --- a/interfaces/Crafter.Build-Flatpak.cppm +++ b/interfaces/Crafter.Build-Flatpak.cppm @@ -24,6 +24,16 @@ export namespace Crafter { Sdk, }; + // A file or directory of the project installed under /app/share. + struct FlatpakShareEntry { + // A file, or a directory: every regular file in it, at its path + // inside it, leaving out empty directories and links to directories. + fs::path source; + // Where under /app/share, relative to it: "crafter-review/process", + // "licenses/net.example.App/LICENSE". + fs::path target; + }; + // What an executable packaged as a Flatpak is installed as. Read for an // executable whose Configuration::packaging makes it one, except // `permissions`, which every configuration may declare: a library's @@ -44,13 +54,34 @@ export namespace Crafter { // not know. The build itself does not read them. std::vector permissions; // A desktop entry, installed as .desktop. Its Icon= has to be - // the app-id. Empty: none, and the app gets no menu entry. + // the app-id, and desktop-file-validate, where there is one, has to + // pass it, as one a share entry places under that name has to. Empty: + // the app has none but what a share entry places. fs::path desktopFile; // AppStream metadata, installed as .metainfo.xml. fs::path metainfo; // The app's icons, each installed under the app-id: an .svg as // scalable, a .png at its own size, which has to be square. std::vector icons; + // Files the program reads that belong in /app/share rather than next + // to it, where cfg.files goes: data a program finds at /../share/, licences. They are copied into + // files/share, kept there as long as they are listed, and gone from + // it once they are not; files/share is the writer's, and anything + // else in it is removed. -r runs the program from files/bin, so the + // same ../share lookup finds them there. Any file may be one, a + // second desktop entry or an add-on's metainfo among them: flatpak + // build-finish exports what it exports of them by its own rules, as + // for any app's, and build-export refuses an icon that is not a + // square image or a D-Bus service that is not a key file, and warns + // of the app's own desktop entry where desktop-file-validate rejects + // it. None may go where another file goes, a field's included, and a + // directory may neither hold what the build writes, which it would + // copy into itself, nor lie in it, the build's own output: files/, + // and the app's directory, FlatpakAppDir(), where install and bundle + // put another copy of files/ and the exported app, however their + // links lead. + std::vector share; // flatpak-builder module files, in Flatpak's own format (JSON or // YAML), for what the app needs in /app besides the program: a // runtime it starts, a tool it runs, data built from source. With @@ -83,6 +114,10 @@ export namespace Crafter { fs::path desktopFile; fs::path metainfo; std::vector icons; + std::vector share; + // FlatpakAppDir(): build-dir/files there is files/ again once install + // or bundle has run, so no share entry may copy from it. + fs::path appDir; // Where the toolchain's clang++ and llvm-readelf are: clang names the // LLVM runtime libraries the program links, readelf what it needs. fs::path clangxx; @@ -100,14 +135,15 @@ export namespace Crafter { }; // Lays out what becomes /app around the program Build() linked into // files/bin: files/share with the desktop file, metainfo and icons under - // the app-id, and files/lib with the shared libraries the program needs - // that the runtime does not have. Those are the LLVM runtime libraries - // the toolchain links into every program, and whatever else of its - // NEEDED entries, and theirs, `libraryDirs` holds; a name found in - // neither is the runtime's. That is the files/ of a Flatpak build - // directory; its metadata and export/ are flatpak build-finish's to - // write, which decides what the sandbox's permissions mean and what the - // host sees of the app. + // the app-id and the `share` entries at the paths they name, and + // files/lib with the shared libraries the program needs that the + // runtime does not have. Those are the LLVM runtime libraries the + // toolchain links into every program, and whatever else of its NEEDED + // entries, and theirs, `libraryDirs` holds; a name found in neither is + // the runtime's. That is the files/ of a Flatpak build directory; its + // metadata and export/ are flatpak build-finish's to write, which + // decides what the sandbox's permissions mean and what the host sees of + // the app. // // The writer owns files/lib and files/share outright, and changes a file // only when what it would write differs, so a build that changed nothing diff --git a/project.cpp b/project.cpp index b64dc76..dd7112f 100644 --- a/project.cpp +++ b/project.cpp @@ -291,6 +291,8 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("FlatpakIncremental").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("FlatpakLibraryChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("FlatpakDesktop").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakShare").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakShareLarge").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("HostFlatpak").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("FlatpakBundle").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("FlatpakPermissions").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/data/note.txt b/tests/FlatpakDependencyExecutable/fixture/packaged/data/note.txt new file mode 100644 index 0000000..8046689 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/data/note.txt @@ -0,0 +1 @@ +the packaged sibling's own note diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp b/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp index 197c3a7..97b2ab5 100644 --- a/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp @@ -21,6 +21,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.flatpak.metainfo = "packaging/packaged.metainfo.xml"; cfg.flatpak.icons = { "packaging/icon.svg" }; cfg.flatpak.modules = { "packaging/extra.json" }; + cfg.flatpak.share = { { "data/note.txt", "packaged/note.txt" } }; std::array ifaces = {}; std::array impls = { "main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); diff --git a/tests/FlatpakDependencyExecutable/main.cpp b/tests/FlatpakDependencyExecutable/main.cpp index 6449e5d..03fb5da 100644 --- a/tests/FlatpakDependencyExecutable/main.cpp +++ b/tests/FlatpakDependencyExecutable/main.cpp @@ -88,6 +88,7 @@ int main() { const fs::path own = scratch / "packaged" / "packaging"; Check(ReadFile(share / "metainfo" / "net.example.Packaged.metainfo.xml") == ReadFile(own / "packaged.metainfo.xml"), "its metainfo is its own"); Check(ReadFile(share / "icons" / "hicolor" / "scalable" / "apps" / "net.example.Packaged.svg") == ReadFile(own / "icon.svg"), "and so is its icon"); + Check(ReadFile(share / "packaged" / "note.txt") == ReadFile(scratch / "packaged" / "data" / "note.txt"), "and so is the data it installs under /app/share"); } } } catch (const std::exception& e) { diff --git a/tests/FlatpakShare/fixture/data/LICENSE b/tests/FlatpakShare/fixture/data/LICENSE new file mode 100644 index 0000000..336fa25 --- /dev/null +++ b/tests/FlatpakShare/fixture/data/LICENSE @@ -0,0 +1 @@ +A licence text for crafter-build's FlatpakShare test. diff --git a/tests/FlatpakShare/fixture/data/app.metainfo.xml b/tests/FlatpakShare/fixture/data/app.metainfo.xml new file mode 100644 index 0000000..656395d --- /dev/null +++ b/tests/FlatpakShare/fixture/data/app.metainfo.xml @@ -0,0 +1,7 @@ + + + net.example.Share + Share + A fixture for crafter-build's tests + CC0-1.0 + diff --git a/tests/FlatpakShare/fixture/data/process/lens.md b/tests/FlatpakShare/fixture/data/process/lens.md new file mode 100644 index 0000000..d1ed20f --- /dev/null +++ b/tests/FlatpakShare/fixture/data/process/lens.md @@ -0,0 +1 @@ +the lens as first written diff --git a/tests/FlatpakShare/fixture/data/process/steps/one.md b/tests/FlatpakShare/fixture/data/process/steps/one.md new file mode 100644 index 0000000..7960b7a --- /dev/null +++ b/tests/FlatpakShare/fixture/data/process/steps/one.md @@ -0,0 +1 @@ +a step in a subdirectory diff --git a/tests/FlatpakShare/fixture/main.cpp b/tests/FlatpakShare/fixture/main.cpp new file mode 100644 index 0000000..e0562fc --- /dev/null +++ b/tests/FlatpakShare/fixture/main.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +namespace fs = std::filesystem; + +// Finds its data the way Crafter.Review finds its process/ directory: at +// /../share/, which is /app/share installed and +// files/share under -r. +int main() { + const fs::path lens = fs::read_symlink("/proc/self/exe").parent_path() / ".." / "share" / "demo" / "process" / "lens.md"; + std::ifstream in(lens, std::ios::binary); + if (!in) { + std::println(std::cerr, "no {}", lens.string()); + return 1; + } + std::print("{}", std::string(std::istreambuf_iterator(in), std::istreambuf_iterator())); + return 0; +} diff --git a/tests/FlatpakShare/main.cpp b/tests/FlatpakShare/main.cpp new file mode 100644 index 0000000..b86ac5f --- /dev/null +++ b/tests/FlatpakShare/main.cpp @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + std::string ReadFile(const fs::path& path) { + std::ifstream in(path, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + } + + std::string BuildIt(Configuration& cfg) { + std::unordered_map> depResults; + std::mutex depMutex; + return Build(cfg, depResults, depMutex).result; + } + + std::map Mtimes(const fs::path& root) { + std::map 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; + } +} + +// cfg.flatpak.share puts files the program reads under /app/share rather +// than next to it, where cfg.files goes: a directory with everything in it +// and single files, each at the path under share/ it names. Crafter.Review +// finds its process/ directory at /../share/crafter-review, +// and the Flatpak's files/share is the writer's own, which it prunes, so +// before this there was no way to put it there. The fixture program reads +// its data the same way, and is run from files/bin as -r runs it. The +// entries are kept while listed: a build that changed nothing writes +// nothing, an edited source is copied again, a removed one goes, and so does +// an entry no longer listed. The build only places them: what is exported of +// them is flatpak build-finish's to decide, and build-export's to check, as +// for any app's files. A target outside share/, a missing source, and two +// files for one path, or a file where another needs a directory, are +// refused, naming what clashed, a field's own file among them. So is a +// directory that holds what the build writes, files/ or the app's +// directory, where install and bundle put another copy of files/, which +// would be copied into itself, as written and where links lead, so the +// directory of a project whose bin/ is a link elsewhere as well; and one +// that lies in them, the build's own output. The +// app's desktop entry is held to the field's checks whichever placed it, so +// one a share entry places with another Icon= is refused. Anything else is +// placed like any other file: a second desktop entry, an add-on's metainfo, +// the legacy appdata/, any icon, of the app's or not, and the app's D-Bus +// services, MIME packages, search providers and KRunner plugins, which no +// field of their own carries. +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-share"; + 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"; + setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1); + if (NormalizeTarget(GetToolchain().hostTriple) != "x86_64-linux-gnu") { + std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple); + return 77; + } + if (!GetToolchain().libcxxDir.empty()) { + std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak"); + return 77; + } + + const fs::path fixture = fs::current_path() / "tests" / "FlatpakShare" / "fixture"; + fs::remove_all(fixture / "bin", ec); + fs::remove_all(fixture / "build", ec); + // The data is edited and deleted below, so it is staged. + const fs::path data = scratch / "data"; + fs::copy(fixture / "data", data, fs::copy_options::recursive); + + Configuration app; + app.path = fixture; + app.name = "share-app"; + app.outputName = "share"; + app.target = HostTarget(); + app.packaging = Packaging::Flatpak; + app.flatpak.appId = "net.example.Share"; + app.flatpak.metainfo = data / "app.metainfo.xml"; + const FlatpakShareEntry process = { data / "process", "demo/process" }; + const FlatpakShareEntry license = { data / "LICENSE", "licenses/net.example.Share/LICENSE" }; + app.flatpak.share = { process, license }; + { + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + } + if (const std::string failed = BuildIt(app); !failed.empty()) { + std::println(std::cerr, "FAIL: build failed: {}", failed); + return 1; + } + + const fs::path root = app.BinDir(); + const fs::path share = root / "files" / "share"; + Check(ReadFile(share / "demo" / "process" / "lens.md") == ReadFile(data / "process" / "lens.md"), "a directory entry is copied under its target"); + Check(fs::is_regular_file(share / "demo" / "process" / "steps" / "one.md"), "with everything in it"); + Check(ReadFile(share / "licenses" / "net.example.Share" / "LICENSE") == ReadFile(data / "LICENSE"), "a file entry is copied to its target"); + Check(fs::is_regular_file(share / "metainfo" / "net.example.Share.metainfo.xml"), "the metainfo is still placed beside them"); + Check(!fs::exists(root / "export"), "the build writes no export/, which build-finish does"); + + const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30)); + Check(run.exitCode == 0 && run.output == "the lens as first written\n", std::format("the program finds its data at /../share (exit {}): {}", run.exitCode, run.output)); + + const std::map before = Mtimes(share); + Check(BuildIt(app).empty(), "the second build succeeds"); + Check(Mtimes(share) == before, "a build that changed nothing leaves files/share alone"); + + std::ofstream(data / "process" / "lens.md", std::ios::trunc) << "the lens as edited\n"; + fs::remove(data / "process" / "steps" / "one.md"); + Check(BuildIt(app).empty(), "the build after the edits succeeds"); + Check(ReadFile(share / "demo" / "process" / "lens.md") == "the lens as edited\n", "an edited source is copied again"); + Check(!fs::exists(share / "demo" / "process" / "steps"), "a removed source goes, and the directory it leaves empty with it"); + + app.flatpak.share = { process }; + Check(BuildIt(app).empty(), "the build without the licence entry succeeds"); + Check(!fs::exists(share / "licenses"), "an entry no longer listed goes"); + Check(fs::exists(share / "demo" / "process" / "lens.md"), "the one still listed stays"); + + // A directory entry that holds an icon of the app, among others. + const fs::path theme = data / "theme" / "hicolor" / "scalable"; + fs::create_directories(theme / "apps"); + fs::create_directories(theme / "actions"); + std::ofstream(theme / "apps" / "net.example.Share.svg") << "\n"; + std::ofstream(theme / "actions" / "demo-action.svg") << "\n"; + + struct Refusal { + std::string_view what; + std::vector share; + std::string_view reason; + }; + // The app's directory, where install and bundle make build-dir/files of + // files/ again, as they would have by now. + fs::create_directories(FlatpakAppDir(app) / "build-dir" / "files"); + const std::array refusals = {{ + {"an absolute target", {{data / "LICENSE", "/etc/LICENSE"}}, "has to be a path inside /app/share"}, + {"a target leaving share/", {{data / "LICENSE", "../bin/LICENSE"}}, "has to be a path inside /app/share"}, + {"share/ itself", {{data / "LICENSE", "."}}, "has to be a path inside /app/share"}, + {"a missing source", {{data / "NOTICE", "licenses/NOTICE"}}, "does not exist"}, + {"two files for one path", {{data / "LICENSE", "x/LICENSE"}, {data / "app.metainfo.xml", "x/LICENSE"}}, "both go to share/x/LICENSE"}, + {"a file where a directory goes", {process, {data / "LICENSE", "demo/process"}}, "would make share/demo/process a file"}, + {"a directory where a file went", {{data / "LICENSE", "demo/process"}, process}, "needs share/demo/process to be a directory"}, + {"a file over the metainfo cfg.flatpak.metainfo places", {{data / "LICENSE", "metainfo/net.example.Share.metainfo.xml"}}, "both go to share/metainfo/net.example.Share.metainfo.xml"}, + {"the project's directory, which holds files/share", {{fixture, "project"}}, "so a share entry would copy it into itself"}, + {"the bin dir's files/", {{root / "files", "build"}}, "so a share entry would copy it into itself"}, + {"the project's build/, which holds the app's directory", {{fixture / "build", "build"}}, "so a share entry would copy it into itself"}, + {"a directory inside the app's directory", {{FlatpakAppDir(app) / "build-dir", "app"}}, "which the build writes and writes again"}, + }}; + for (const Refusal& refusal : refusals) { + app.flatpak.share = refusal.share; + const std::string result = BuildIt(app); + Check(result.contains(refusal.reason), std::format("{} is refused, saying '{}': {}", refusal.what, refusal.reason, result)); + } + + // A project whose bin/ is a link elsewhere holds its files/ as written + // and not once the link is followed, and its own directory is refused + // all the same: its walk would otherwise copy build/, and with it the + // app's build-dir, deeper with every install. + const fs::path linked = scratch / "linked"; + fs::create_directories(linked); + fs::create_directories(scratch / "linked-bin"); + fs::copy_file(fixture / "main.cpp", linked / "main.cpp"); + fs::create_directory_symlink(scratch / "linked-bin", linked / "bin"); + Configuration other; + other.path = linked; + other.name = "share-linked"; + other.outputName = "linked"; + other.target = HostTarget(); + other.packaging = Packaging::Flatpak; + other.flatpak.appId = "net.example.ShareLinked"; + other.flatpak.share = { {linked, "project"} }; + { + std::array ifaces = {}; + std::array impls = { "main" }; + other.GetInterfacesAndImplementations(ifaces, impls); + } + const std::string linkedRefused = BuildIt(other); + Check(linkedRefused.contains("so a share entry would copy it into itself"), std::format("the directory of a project whose bin/ is a link is refused: {}", linkedRefused)); + + // The app's desktop entry is checked where it lands, whichever placed + // it: one a share entry puts at applications/.desktop is held to + // its Icon= as the field's is. + std::ofstream(data / "wrong-icon.desktop") << "[Desktop Entry]\nType=Application\nName=Share\nExec=share\nIcon=other\n"; + app.flatpak.share = { {data / "wrong-icon.desktop", "applications/net.example.Share.desktop"} }; + const std::string wrongIcon = BuildIt(app); + Check(wrongIcon.contains("has to be the app-id"), std::format("a share entry's desktop entry of the app with another Icon= is refused: {}", wrongIcon)); + + // Anything else is placed as it is, for flatpak to export and check as + // it does any app's: a second desktop entry, an add-on's metainfo, the + // legacy appdata/, the app's icon where the icons field puts none, + // inside a directory entry too, an icon of something else, an action + // icon say, and the app's symbolic one or one named with a '+'. + std::ofstream(data / "editor.desktop") << "[Desktop Entry]\nType=Application\nName=Share Editor\nExec=share --edit\nIcon=net.example.Share\n"; + app.flatpak.share = { + {data / "editor.desktop", "applications/net.example.Share.Editor.desktop"}, + {data / "app.metainfo.xml", "metainfo/net.example.Share.Plugin.metainfo.xml"}, + {data / "app.metainfo.xml", "appdata/net.example.Share.appdata.xml"}, + {data / "LICENSE", "icons/hicolor/256x256/apps/net.example.Share.png"}, + {data / "theme", "icons"}, + {data / "LICENSE", "icons/hicolor/scalable/apps/net.example.SharePlus.svg"}, + {data / "LICENSE", "icons/hicolor/scalable/apps/net.example.Share-symbolic.svg"}, + {data / "LICENSE", "icons/hicolor/scalable/apps/net.example.Share+x.svg"}, + }; + const std::string placed = BuildIt(app); + Check(placed.empty(), std::format("a second desktop entry, other metainfo and any icon build: {}", placed)); + const fs::path apps = share / "icons" / "hicolor" / "scalable" / "apps"; + for (const fs::path& place : {fs::path("applications/net.example.Share.Editor.desktop"), fs::path("metainfo/net.example.Share.Plugin.metainfo.xml"), fs::path("appdata/net.example.Share.appdata.xml"), fs::path("icons/hicolor/256x256/apps/net.example.Share.png"), fs::path("icons/hicolor/scalable/apps/net.example.Share.svg"), fs::path("icons/hicolor/scalable/actions/demo-action.svg")}) { + Check(fs::is_regular_file(share / place), std::format("share/{} is placed", place.string())); + } + Check(fs::is_regular_file(apps / "net.example.SharePlus.svg") && fs::is_regular_file(apps / "net.example.Share-symbolic.svg") && fs::is_regular_file(apps / "net.example.Share+x.svg"), "and so are the app's icons the icons field does not make"); + + // So are the files of the app's that no field carries: D-Bus + // activation, a MIME type, a search provider, a KRunner plugin. + const std::array others = { + "dbus-1/services/net.example.Share.service", + "mime/packages/net.example.Share.xml", + "gnome-shell/search-providers/net.example.Share.search-provider.ini", + "krunner/dbusplugins/net.example.Share.desktop", + }; + app.flatpak.share.clear(); + for (const fs::path& place : others) app.flatpak.share.push_back({data / "LICENSE", place}); + const std::string othersBuilt = BuildIt(app); + Check(othersBuilt.empty(), std::format("the app's D-Bus service, MIME package, search provider and KRunner plugin build: {}", othersBuilt)); + for (const fs::path& place : others) Check(fs::is_regular_file(share / place), std::format("share/{} is placed", place.string())); + + // A source directory written with a trailing separator, "process/", is + // the directory: each file lands at its path inside it, under the target. + app.flatpak.share = { {data / "process" / "", "slashed"} }; + Check(BuildIt(app).empty() && fs::is_regular_file(share / "slashed" / "lens.md"), "a source directory written with a trailing separator is copied under its target"); + + fs::remove_all(scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/FlatpakShareLarge/main.cpp b/tests/FlatpakShareLarge/main.cpp new file mode 100644 index 0000000..479b9eb --- /dev/null +++ b/tests/FlatpakShareLarge/main.cpp @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +#include +#include +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 process's address space now, in bytes: the first field of + // /proc/self/statm, in pages. + std::uint64_t AddressSpace() { + std::ifstream statm("/proc/self/statm"); + std::uint64_t pages = 0; + statm >> pages; + return pages * static_cast(sysconf(_SC_PAGESIZE)); + } +} + +// A share entry can be a program's data, gigabytes of it, and the writer +// compares each with its copy in files/share on every build, to leave an +// unchanged one alone. It compared them by reading both files whole, so a +// build with nothing to copy held twice the largest entry in memory, and +// failed where that did not fit, every time after the first. A files/ with +// a 32 MiB share entry is written, then written again with nothing changed +// in a child process whose address space may grow by no more than 16 MiB: +// that rewrite has to succeed. A change in the entry's last byte, in the +// short block a comparison reads last, is still copied. The writer is +// called directly, with a stand-in llvm-readelf: a whole Build() would start +// compiles and threads, and the real llvm-readelf a write starts for the +// libraries, which the same limit would hold as well. +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-share-large"; + std::error_code ec; + fs::remove_all(scratch, ec); + fs::create_directories(scratch / "app" / "files" / "bin"); + fs::create_directories(scratch / "build"); + // The program, and a stand-in for llvm-readelf that says it needs + // nothing: the writer reads the program's libraries on every write, and + // the real llvm-readelf, started under the child's limit below, does not + // fit in it. The libraries are not what is measured here. + std::ofstream(scratch / "app" / "files" / "bin" / "large") << "a program\n"; + const fs::path readelf = scratch / "readelf"; + std::ofstream(readelf) << "#!/bin/sh\necho 'NeededLibraries ['\necho ']'\n"; + fs::permissions(readelf, fs::perms::owner_all); + // Not a whole number of blocks, so the last one is short. + constexpr std::uintmax_t Size = (32 * 1024 * 1024) + 3; + const fs::path data = scratch / "data.bin"; + std::ofstream(data, std::ios::binary).close(); + fs::resize_file(data, Size); + + const Toolchain& tc = GetToolchain(); + FlatpakFiles d; + d.root = scratch / "app"; + d.record = scratch / "build" / "flatpak-record"; + d.appId = "net.example.ShareLarge"; + d.command = "large"; + d.share = { {data, "large/data.bin"} }; + d.clangxx = tc.clangxx; + d.readelf = readelf; + d.programEntries = {"large"}; + + const std::string first = WriteFlatpakFiles(d); + const fs::path copy = d.root / "files" / "share" / "large" / "data.bin"; + Check(first.empty() && fs::file_size(copy, ec) == Size, std::format("the share entry is copied: {}", first)); + + // The rewrite, in a child under the limit: its exit status is whether + // the writer finished. No thread runs here to be lost in the fork, and + // nothing buffered is written twice. + std::fflush(nullptr); + const pid_t child = fork(); + if (child == 0) { + rlimit limit{}; + getrlimit(RLIMIT_AS, &limit); + limit.rlim_cur = std::min(AddressSpace() + (16 * 1024 * 1024), limit.rlim_max); + if (setrlimit(RLIMIT_AS, &limit) != 0) _exit(2); + const std::string again = WriteFlatpakFiles(d); + if (!again.empty()) std::println(std::cerr, "the rewrite failed: {}", again); + _exit(again.empty() ? 0 : 1); + } + std::int32_t status = 0; + if (child > 0) waitpid(child, &status, 0); + Check(child > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0, std::format("rewriting it with nothing changed fits in 16 MiB more than the process has (status {})", status)); + + // The comparison still sees a change in the last, short block. + { + std::fstream out(data, std::ios::binary | std::ios::in | std::ios::out); + out.seekp(static_cast(Size - 1)); + out.put('x'); + } + const std::string changed = WriteFlatpakFiles(d); + std::ifstream in(copy, std::ios::binary); + in.seekg(static_cast(Size - 1)); + Check(changed.empty() && in.get() == 'x', std::format("a change in the entry's last byte is copied: {}", changed)); + in.close(); + + fs::remove_all(scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/VariantId/main.cpp b/tests/VariantId/main.cpp index f751ef2..0fc170c 100644 --- a/tests/VariantId/main.cpp +++ b/tests/VariantId/main.cpp @@ -66,6 +66,7 @@ int main() { described.flatpak.runtime = FlatpakRuntime::Sdk; described.flatpak.permissions = {"--socket=wayland"}; described.flatpak.modules = {"packaging/extra.json"}; + described.flatpak.share = {{"data", "app/data"}}; Configuration library = MakeBase(); library.type = ConfigurationType::LibraryStatic; Configuration flatpakLibrary = MakeBase(); @@ -73,7 +74,7 @@ int main() { flatpakLibrary.packaging = Packaging::Flatpak; Check(plain.VariantId() == none.VariantId(), "Default and None share a directory"); Check(plain.VariantId() != flatpak.VariantId(), "a Flatpak gets a directory of its own"); - Check(flatpak.VariantId() == described.VariantId(), "the app-id, desktop entry, icons, runtime, permissions and modules do not move the directory"); + Check(flatpak.VariantId() == described.VariantId(), "the app-id, desktop entry, icons, runtime, permissions, modules and share entries do not move the directory"); Check(library.VariantId() == flatpakLibrary.VariantId(), "a library ignores packaging"); Check(flatpak.ProgramDir() == flatpak.BinDir() / "files" / "bin" && plain.ProgramDir() == plain.BinDir(), "a Flatpak's program lives in files/bin, everything else's in the bin dir"); }