// 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 Split(std::string_view s, char separator) { std::vector 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(in), std::istreambuf_iterator()); } // 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 x(Block); std::vector y(Block); while (left && right) { left.read(x.data(), static_cast(Block)); right.read(y.data(), static_cast(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(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 SyncOwned(const fs::path& dir, const std::map& wanted) { std::set copied; std::error_code ec; if (fs::exists(dir, ec)) { std::vector files; std::vector 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(std::tolower(static_cast(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(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 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> 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 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 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 Libraries(const FlatpakFiles& d, const fs::path& program) { std::vector libraries; std::set seen; std::deque 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 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 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& 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 libraries; for (const fs::path& library : Libraries(d, program)) libraries.emplace(library.filename(), library); SyncOwned(files / "lib", libraries); std::map 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 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 ""; }