Files
Build-System/src/Install/Installer.cpp
T
faumaray b7c224cf67
VoidBuildSystem CI / signing-openssl-gcc16 (push) Successful in 1m36s
VoidBuildSystem CI / fuzz-clang (push) Failing after 1m43s
VoidBuildSystem CI / sanitizers-gcc16 (push) Successful in 3m9s
VoidBuildSystem CI / build-and-test-gcc16 (push) Canceled after 7m56s
feat(install): generate NuGet packages
2026-12-05 14:31:31 +03:00

1385 lines
58 KiB
C++

#include <Void/Build/Install/Installer.hpp>
#include <Void/Build/Package/Archive.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Provenance/Signing.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Core/Scope.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Str.hpp>
#include <algorithm>
#include <array>
#include <format>
#include <fstream>
#include <set>
#include <unistd.h>
namespace Void::Build::Install {
namespace {
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, std::move(msg));
}
bool is_safe_relative_dest(const std::filesystem::path &rel) {
if (rel.empty() || rel.is_absolute()) {
return false;
}
const auto norm = rel.lexically_normal();
for (const auto &part : norm) {
if (part == "..") {
return false;
}
}
return true;
}
std::string default_dest_for_kind(TargetKind kind) {
switch (kind) {
case TargetKind::Executable:
case TargetKind::Test:
return "bin";
case TargetKind::StaticLibrary:
case TargetKind::SharedLibrary:
case TargetKind::ObjectLibrary:
return "lib";
case TargetKind::HeaderOnly:
case TargetKind::CustomAction:
return "share";
}
return "share";
}
std::string escape_cmake_str(std::string_view s) {
std::string out;
for (const char c : s) {
if (c == '\\' || c == '"' || c == '$' || c == ';') {
out.push_back('\\');
}
out.push_back(c);
}
return out;
}
void put_u16(std::string &out, std::uint16_t value) {
out.push_back(static_cast<char>(value & 0xFFu));
out.push_back(static_cast<char>((value >> 8) & 0xFFu));
}
void put_u32(std::string &out, std::uint32_t value) {
for (int shift = 0; shift < 32; shift += 8) {
out.push_back(static_cast<char>((value >> shift) & 0xFFu));
}
}
std::uint32_t crc32_bytes(std::string_view data) {
static const auto table = [] {
std::array<std::uint32_t, 256> t{};
for (std::uint32_t i = 0; i < 256; ++i) {
std::uint32_t c = i;
for (int k = 0; k < 8; ++k) {
c = (c & 1u) != 0u ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
}
t[i] = c;
}
return t;
}();
std::uint32_t crc = 0xFFFFFFFFu;
for (const char ch : data) {
crc = table[(crc ^ static_cast<std::uint8_t>(ch)) & 0xFFu] ^ (crc >> 8);
}
return crc ^ 0xFFFFFFFFu;
}
std::string ar_member_header(std::string_view name, std::uint64_t size) {
std::string header;
std::string padded_name{name};
padded_name.push_back('/');
header.reserve(60);
header += padded_name;
header.resize(16, ' ');
header += std::format("{:<12}", 0); // mtime
header += std::format("{:<6}", 0); // uid
header += std::format("{:<6}", 0); // gid
header += std::format("{:<8}", 100644); // mode
header += std::format("{:<10}", size); // size
header += "`\n";
return header;
}
void append_ar_member(std::string &out, std::string_view name, std::string_view data) {
out += ar_member_header(name, data.size());
out += data;
if (data.size() % 2 != 0) {
out.push_back('\n');
}
}
void append_ar_member_to_stream(std::ostream &out, std::string_view name, std::string_view data) {
out << ar_member_header(name, data.size());
out.write(data.data(), static_cast<std::streamsize>(data.size()));
if (data.size() % 2 != 0) {
out.put('\n');
}
}
// Streams a file into an ar member so payloads of any size bypass read limits.
Void::Result::Result<void, Void::Result::Error>
append_ar_member_file(std::ostream &out, std::string_view name,
const std::filesystem::path &source) {
std::error_code ec;
const auto size = std::filesystem::file_size(source, ec);
if (ec) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("cannot stat '{}': {}", source.string(), ec.message()), ec.value())};
}
std::ifstream in{source, std::ios::binary};
if (!in) {
return std::unexpected{
Void::System::make_system_error(Void::System::SystemErrorCode::io_error,
std::format("cannot open '{}'", source.string()))};
}
out << ar_member_header(name, size);
std::array<char, 64 * 1024> buffer{};
std::uint64_t copied = 0;
while (in) {
in.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
const auto count = in.gcount();
if (count > 0) {
out.write(buffer.data(), count);
copied += static_cast<std::uint64_t>(count);
}
}
if (copied != size) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error,
std::format("short read while archiving '{}'", source.string()))};
}
if (size % 2 != 0) {
out.put('\n');
}
return {};
}
// ── Minimal native RPM writer (uncompressed newc cpio payload) ──────────────────────────────
namespace rpm {
constexpr std::uint32_t kInt16 = 3;
constexpr std::uint32_t kInt32 = 4;
constexpr std::uint32_t kString = 6;
constexpr std::uint32_t kBin = 7;
constexpr std::uint32_t kStringArray = 8;
constexpr std::uint32_t kI18nString = 9;
struct Tag {
std::uint32_t tag{0};
std::uint32_t type{0};
std::string data;
std::uint32_t count{0};
};
void put_be32(std::string &out, std::uint32_t value) {
out.push_back(static_cast<char>((value >> 24) & 0xFFu));
out.push_back(static_cast<char>((value >> 16) & 0xFFu));
out.push_back(static_cast<char>((value >> 8) & 0xFFu));
out.push_back(static_cast<char>(value & 0xFFu));
}
Tag string_tag(std::uint32_t tag, std::string value, std::uint32_t type = kString) {
value.push_back('\0');
return Tag{tag, type, std::move(value), 1};
}
Tag int32_tag(std::uint32_t tag, std::vector<std::uint32_t> values) {
std::string data;
for (const auto value : values) {
put_be32(data, value);
}
return Tag{tag, kInt32, std::move(data), static_cast<std::uint32_t>(values.size())};
}
Tag int16_tag(std::uint32_t tag, std::vector<std::uint16_t> values) {
std::string data;
for (const auto value : values) {
data.push_back(static_cast<char>((value >> 8) & 0xFFu));
data.push_back(static_cast<char>(value & 0xFFu));
}
return Tag{tag, kInt16, std::move(data), static_cast<std::uint32_t>(values.size())};
}
Tag string_array_tag(std::uint32_t tag, const std::vector<std::string> &values) {
std::string data;
for (const auto &value : values) {
data += value;
data.push_back('\0');
}
return Tag{tag, kStringArray, std::move(data), static_cast<std::uint32_t>(values.size())};
}
std::string build_header(std::vector<Tag> tags, std::uint32_t region_tag) {
std::ranges::sort(tags, {}, &Tag::tag);
std::string store;
struct Index {
std::uint32_t tag;
std::uint32_t type;
std::uint32_t offset;
std::uint32_t count;
};
std::vector<Index> index;
for (const auto &entry : tags) {
if (entry.type == kInt16 || entry.type == kInt32) {
while (store.size() % 4 != 0) {
store.push_back('\0');
}
}
index.push_back(
{entry.tag, entry.type, static_cast<std::uint32_t>(store.size()), entry.count});
store += entry.data;
}
const auto trailer_pos = static_cast<std::uint32_t>(store.size());
const auto nindex = static_cast<std::uint32_t>(index.size() + 1);
put_be32(store, region_tag);
put_be32(store, kBin);
put_be32(store, 0u - nindex * 16u);
put_be32(store, 16);
index.insert(index.begin(), Index{region_tag, kBin, trailer_pos, 16});
std::string out{'\x8e', '\xad', '\xe8', 1, 0, 0, 0, 0};
put_be32(out, static_cast<std::uint32_t>(index.size()));
put_be32(out, static_cast<std::uint32_t>(store.size()));
for (const auto &entry : index) {
put_be32(out, entry.tag);
put_be32(out, entry.type);
put_be32(out, entry.offset);
put_be32(out, entry.count);
}
out += store;
return out;
}
std::string cpio_entry(std::string_view name, std::string_view data, std::uint32_t mode,
std::uint32_t ino) {
std::string out = std::format(
"070701{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}{:08X}", ino,
mode, 0u, 0u, 1u, 0u, static_cast<std::uint32_t>(data.size()), 0u, 0u, 0u, 0u,
static_cast<std::uint32_t>(name.size() + 1), 0u);
out += name;
out.push_back('\0');
out += data;
while (out.size() % 4 != 0) {
out.push_back('\0');
}
return out;
}
std::string cpio_archive(
const std::vector<std::pair<std::string, std::pair<std::string, std::uint32_t>>> &files) {
std::string out;
std::uint32_t ino = 1;
for (const auto &[name, content] : files) {
out += cpio_entry(name, content.first, content.second, ino++);
}
out += cpio_entry("TRAILER!!!", "", 0, 0);
while (out.size() % 512 != 0) {
out.push_back('\0');
}
return out;
}
std::string arch_name(std::string arch) {
arch = Void::Str::to_lower_ascii(arch);
if (arch == "amd64") {
return "x86_64";
}
if (arch == "arm64") {
return "aarch64";
}
return arch;
}
} // namespace rpm
// RPM package: lead + signature header + main header + uncompressed newc cpio payload.
Void::Result::Result<void, Void::Result::Error>
write_rpm_package(const std::filesystem::path &output, const InstallOptions &options,
const Graph::BuildGraph &graph,
const std::vector<Package::ArchiveEntrySpec> &entries) {
std::vector<std::pair<std::string, std::pair<std::string, std::uint32_t>>> payload_files;
std::vector<std::string> basenames;
std::vector<std::string> dirnames;
std::vector<std::uint32_t> dirindexes;
std::vector<std::uint32_t> file_sizes;
std::vector<std::uint16_t> file_modes;
std::vector<std::uint16_t> file_rdevs;
std::vector<std::uint32_t> file_mtimes;
std::vector<std::uint32_t> file_flags;
std::vector<std::string> file_digests;
std::vector<std::string> file_users;
std::vector<std::string> file_groups;
for (const auto &entry : entries) {
auto content = Void::FileSystem::read_file(entry.source_file);
if (!content) {
return std::unexpected{content.error()};
}
const auto dir = std::filesystem::path{entry.archive_path}.parent_path();
std::string dirname = dir.empty() ? std::string{} : dir.generic_string() + "/";
const auto dir_it = std::ranges::find(dirnames, dirname);
if (dir_it == dirnames.end()) {
dirnames.push_back(dirname);
dirindexes.push_back(static_cast<std::uint32_t>(dirnames.size() - 1));
} else {
dirindexes.push_back(
static_cast<std::uint32_t>(std::distance(dirnames.begin(), dir_it)));
}
basenames.push_back(std::filesystem::path{entry.archive_path}.filename().string());
file_sizes.push_back(static_cast<std::uint32_t>(content->size()));
file_modes.push_back(static_cast<std::uint16_t>(entry.mode == 0755u ? 0100755u : 0100644u));
file_rdevs.push_back(0);
file_mtimes.push_back(0);
file_flags.push_back(0);
file_digests.push_back(Util::sha256_hex(*content));
file_users.emplace_back("root");
file_groups.emplace_back("root");
payload_files.emplace_back(entry.archive_path, std::pair{std::move(*content), entry.mode});
}
const std::string payload = rpm::cpio_archive(payload_files);
std::uint64_t total_size = 0;
for (const auto size : file_sizes) {
total_size += size;
}
std::vector<rpm::Tag> main_tags;
main_tags.push_back(rpm::string_tag(1000, options.package_name));
main_tags.push_back(rpm::string_tag(1001, options.package_version));
main_tags.push_back(rpm::string_tag(1002, "1"));
main_tags.push_back(rpm::string_tag(
1004,
options.package_description.empty() ? options.package_name : options.package_description,
rpm::kI18nString));
main_tags.push_back(rpm::string_tag(1005, "Generated by VoidBuildSystem", rpm::kI18nString));
main_tags.push_back(rpm::int32_tag(1006, {0}));
main_tags.push_back(rpm::string_tag(1007, "localhost"));
main_tags.push_back(rpm::int32_tag(1009, {static_cast<std::uint32_t>(total_size)}));
main_tags.push_back(rpm::string_tag(1014, "MIT"));
main_tags.push_back(rpm::string_tag(1016, "Applications/System", rpm::kI18nString));
main_tags.push_back(rpm::string_tag(1021, "linux"));
main_tags.push_back(rpm::string_tag(1022, rpm::arch_name(graph.profile.architecture)));
main_tags.push_back(rpm::int32_tag(1028, file_sizes));
main_tags.push_back(rpm::int16_tag(1030, file_modes));
main_tags.push_back(rpm::int16_tag(1033, file_rdevs));
main_tags.push_back(rpm::int32_tag(1034, file_mtimes));
main_tags.push_back(rpm::string_array_tag(1035, file_digests));
main_tags.push_back(rpm::string_array_tag(1039, file_users));
main_tags.push_back(rpm::string_array_tag(1040, file_groups));
main_tags.push_back(rpm::int32_tag(1045, file_flags));
main_tags.push_back(rpm::int32_tag(1116, dirindexes));
main_tags.push_back(rpm::string_array_tag(1117, basenames));
main_tags.push_back(rpm::string_array_tag(1118, dirnames));
main_tags.push_back(rpm::string_tag(1124, "cpio"));
main_tags.push_back(rpm::string_tag(1126, ""));
main_tags.push_back(rpm::int32_tag(5011, {8})); // SHA-256 file digests
main_tags.push_back(rpm::string_array_tag(5092, {Util::sha256_hex(payload)}));
const std::string main_header = rpm::build_header(std::move(main_tags), 63);
std::vector<rpm::Tag> sig_tags;
sig_tags.push_back(rpm::string_tag(273, Util::sha256_hex(main_header)));
sig_tags.push_back(
rpm::int32_tag(1000, {static_cast<std::uint32_t>(main_header.size() + payload.size())}));
std::string signature = rpm::build_header(std::move(sig_tags), 62);
while ((96 + signature.size()) % 8 != 0) {
signature.push_back('\0');
}
std::string lead{'\xed', '\xab', '\xee', '\xdb', 3, 0, 0, 0, 0, 1};
const std::string name_version = options.package_name + "-" + options.package_version + "-1";
lead += name_version;
lead.resize(10 + 66, '\0');
lead += {0, 1, 0, 5};
lead.resize(96, '\0');
const std::string package = lead + signature + main_header + payload;
return Platform::atomic_write_file(output, package, true);
}
std::string wix_guid_from(std::string_view seed) {
const std::string digest = Util::sha256_hex(seed);
std::string guid = digest.substr(0, 8) + "-" + digest.substr(8, 4) + "-4" +
digest.substr(13, 3) + "-a" + digest.substr(17, 3) + "-" +
digest.substr(20, 12);
std::ranges::transform(guid, guid.begin(), [](char c) {
return static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
});
return guid;
}
std::string wix_id(std::string_view prefix, std::string_view text) {
std::string out{prefix};
for (const char c : text) {
out.push_back(std::isalnum(static_cast<unsigned char>(c)) != 0 ? c : '_');
}
return out;
}
std::string wix_xml_escape(std::string_view text) {
std::string out;
for (const char c : text) {
switch (c) {
case '&':
out += "&amp;";
break;
case '<':
out += "&lt;";
break;
case '>':
out += "&gt;";
break;
case '"':
out += "&quot;";
break;
default:
out.push_back(c);
break;
}
}
return out;
}
// WiX v3 source (the CPack WIX model): consumed by candle/light on Windows to produce an MSI.
Void::Result::Result<void, Void::Result::Error>
write_wix_source(const std::filesystem::path &output, const InstallOptions &options,
const std::vector<Package::ArchiveEntrySpec> &entries) {
const std::string product_guid = wix_guid_from("product:" + options.package_name);
const std::string upgrade_guid = wix_guid_from("upgrade:" + options.package_name);
const std::string manufacturer =
options.maintainer.empty() ? std::string{"Void"} : options.maintainer;
const std::string description =
options.package_description.empty() ? options.package_name : options.package_description;
std::map<std::string, std::vector<std::string>, std::less<>> files_by_dir;
for (const auto &entry : entries) {
const auto rel = std::filesystem::path{entry.archive_path};
files_by_dir[rel.parent_path().generic_string()].push_back(rel.filename().string());
}
std::string xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\">\n"
" <Product Id=\"" +
product_guid + "\" Name=\"" + wix_xml_escape(options.package_name) +
"\" Language=\"1033\" Version=\"" + wix_xml_escape(options.package_version) +
"\" Manufacturer=\"" + wix_xml_escape(manufacturer) + "\" UpgradeCode=\"" + upgrade_guid +
"\">\n"
" <Package InstallerVersion=\"200\" Compressed=\"yes\" "
"Platform=\"x64\" InstallScope=\"perMachine\" Description=\"" +
wix_xml_escape(description) +
"\"/>\n"
" <MajorUpgrade DowngradeErrorMessage=\"A newer version is installed.\"/>\n"
" <MediaTemplate EmbedCab=\"yes\"/>\n"
" <Directory Id=\"TARGETDIR\" Name=\"SourceDir\">\n"
" <Directory Id=\"ProgramFiles64Folder\">\n"
" <Directory Id=\"INSTALLDIR\" Name=\"" +
wix_xml_escape(options.package_name) + "\">\n";
for (const auto &[dir, files] : files_by_dir) {
if (dir.empty()) {
continue;
}
xml += " <Directory Id=\"" + wix_id("d_", dir) + "\" Name=\"" +
wix_xml_escape(std::filesystem::path{dir}.filename().string()) + "\">\n";
for (const auto &file : files) {
const std::string rel = dir + "/" + file;
xml += " <Component Id=\"" + wix_id("c_", rel) +
"\" Guid=\"*\">\n"
" <File Id=\"" +
wix_id("f_", rel) + "\" Source=\"" + wix_xml_escape(rel) +
"\" KeyPath=\"yes\"/>\n"
" </Component>\n";
}
xml += " </Directory>\n";
}
xml += " </Directory>\n"
" </Directory>\n"
" </Directory>\n"
" <Feature Id=\"DefaultFeature\" Title=\"" +
wix_xml_escape(options.package_name) +
"\" Level=\"1\" Display=\"expand\">\n"
" <ComponentGroupRef Id=\"ProductComponents\"/>\n"
" </Feature>\n"
" </Product>\n"
" <Fragment>\n"
" <ComponentGroup Id=\"ProductComponents\">\n";
for (const auto &entry : entries) {
xml += " <ComponentRef Id=\"" + wix_id("c_", entry.archive_path) + "\"/>\n";
}
xml += " </ComponentGroup>\n"
" </Fragment>\n"
"</Wix>\n";
return Platform::atomic_write_file(output, xml, true);
}
// ── UDIF (DMG) trailer ─────────────────────────────────────────────────────────────────────
// A DMG is a data fork (the disk image payload) followed by a 512-byte "koly" trailer. This
// writer produces a valid UDIF container whose payload is the deterministic tar of the package;
// macOS DiskImageMounter additionally needs a filesystem payload (HFS+/APFS), which is macOS-only
// work. Checksums are CRC-32 as in the UDIF specification.
class Crc32 {
public:
void update(std::string_view data) {
for (const char ch : data) {
crc_ ^= static_cast<std::uint32_t>(static_cast<unsigned char>(ch));
for (int bit = 0; bit < 8; ++bit) {
crc_ = (crc_ >> 1) ^ (0xEDB88320u & (0u - (crc_ & 1u)));
}
}
}
[[nodiscard]] std::uint32_t value() const { return ~crc_; }
private:
std::uint32_t crc_{0xFFFFFFFFu};
};
void put_be32(std::string &out, std::size_t offset, std::uint32_t value) {
for (int i = 3; i >= 0; --i) {
out[offset + static_cast<std::size_t>(i)] = static_cast<char>(value & 0xFFu);
value >>= 8;
}
}
void put_be64(std::string &out, std::size_t offset, std::uint64_t value) {
for (int i = 7; i >= 0; --i) {
out[offset + static_cast<std::size_t>(i)] = static_cast<char>(value & 0xFFu);
value >>= 8;
}
}
std::string make_koly_trailer(std::uint64_t data_fork_length, std::uint32_t data_crc,
std::string_view segment_seed) {
std::string koly(512, '\0');
koly[0] = 'k';
koly[1] = 'o';
koly[2] = 'l';
koly[3] = 'y';
put_be32(koly, 4, 4); // version
put_be32(koly, 8, 512); // header size
put_be32(koly, 12, 1); // flags
put_be64(koly, 16, 0); // running data fork offset
put_be64(koly, 24, 0); // data fork offset
put_be64(koly, 32, data_fork_length);
put_be64(koly, 40, 0); // resource fork offset
put_be64(koly, 48, 0); // resource fork length
put_be32(koly, 56, 1); // segment number
put_be32(koly, 60, 1); // segment count
const std::string digest = Util::sha256_hex(segment_seed);
for (std::size_t i = 0; i < 16; ++i) {
koly[64 + i] = static_cast<char>(std::stoul(digest.substr(i * 2, 2), nullptr, 16));
}
// Data fork checksum: type 2 (CRC-32), 32-bit.
put_be32(koly, 80, 2);
put_be32(koly, 84, 32);
put_be32(koly, 88, data_crc);
put_be64(koly, 216, 0); // no XML plist
put_be64(koly, 224, 0);
// Master checksum mirrors the data fork checksum.
put_be32(koly, 352, 2);
put_be32(koly, 356, 32);
put_be32(koly, 360, data_crc);
put_be32(koly, 488, 1); // image variant
put_be64(koly, 492, (data_fork_length + 511u) / 512u); // sector count
return koly;
}
Void::Result::Result<void, Void::Result::Error>
write_dmg_archive(const std::filesystem::path &output, const std::filesystem::path &payload) {
std::ifstream in{payload, std::ios::binary};
if (!in) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error,
std::format("cannot open DMG payload '{}'", payload.string()))};
}
std::ofstream out{output, std::ios::binary | std::ios::trunc};
if (!out) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error,
std::format("cannot create DMG '{}'", output.string()))};
}
Crc32 crc;
std::uint64_t length = 0;
std::array<char, 64 * 1024> buffer{};
while (in) {
in.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
const auto count = in.gcount();
if (count > 0) {
out.write(buffer.data(), count);
crc.update(std::string_view{buffer.data(), static_cast<std::size_t>(count)});
length += static_cast<std::uint64_t>(count);
}
}
const std::string koly = make_koly_trailer(length, crc.value(), payload.filename().string());
out.write(koly.data(), static_cast<std::streamsize>(koly.size()));
out.flush();
if (!out) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error,
std::format("failed writing DMG '{}'", output.string()))};
}
return {};
}
// ── NuGet package (.nupkg) ─────────────────────────────────────────────────────────────────
// A .nupkg is an OPC ZIP (a nuspec manifest plus content parts). Native assets follow the
// `runtimes/<rid>/native` convention; public headers go to `build/native/include`.
std::string nuget_rid(std::string_view os, std::string_view architecture) {
const std::string arch = architecture == "aarch64" || architecture == "arm64" ? "arm64"
: architecture == "x86" || architecture == "i686" ? "x86"
: "x64";
const auto lower_os = Void::Str::to_lower_ascii(os);
if (lower_os == "windows" || lower_os == "win32") {
return "win-" + arch;
}
if (lower_os == "darwin" || lower_os == "macos") {
return "osx-" + arch;
}
return "linux-" + arch;
}
Void::Result::Result<void, Void::Result::Error>
write_nuget_package(const std::filesystem::path &output, const InstallOptions &options,
const Graph::BuildGraph &graph,
const std::vector<Package::ArchiveEntrySpec> &entries) {
const std::string id = options.package_name;
const std::string version =
options.package_version.empty() ? std::string{"1.0.0"} : options.package_version;
const std::string rid = nuget_rid(graph.profile.os, graph.profile.architecture);
const std::string authors =
options.maintainer.empty() ? std::string{"Void"} : options.maintainer;
const std::string description = options.package_description.empty()
? options.package_name
: options.package_description;
// Map the installed tree onto the NuGet layout.
std::vector<std::pair<std::string, std::filesystem::path>> mapped;
std::set<std::string> extensions;
for (const auto &entry : entries) {
const auto rel = entry.archive_path;
std::string dest;
if (rel.starts_with("include/")) {
dest = "build/native/include/" + rel.substr(std::string{"include/"}.size());
} else {
dest = "runtimes/" + rid + "/native/" + rel;
}
mapped.emplace_back(dest, entry.source_file);
const auto dot = dest.rfind('.');
if (dot != std::string::npos && dot > dest.rfind('/')) {
extensions.insert(dest.substr(dot + 1));
}
}
const std::string nuspec =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">\n"
" <metadata>\n"
" <id>" +
wix_xml_escape(id) + "</id>\n"
" <version>" + wix_xml_escape(version) + "</version>\n"
" <authors>" + wix_xml_escape(authors) + "</authors>\n"
" <description>" + wix_xml_escape(description) + "</description>\n"
" <tags>native;c++;vbs</tags>\n"
" </metadata>\n"
"</package>\n";
std::string content_types =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\n"
" <Default Extension=\"rels\" "
"ContentType=\"application/vnd.openxmlformats-package.relationships+xml\" />\n"
" <Default Extension=\"nuspec\" ContentType=\"application/octet\" />\n";
for (const auto &ext : extensions) {
content_types += " <Default Extension=\"" + wix_xml_escape(ext) +
"\" ContentType=\"application/octet\" />\n";
}
content_types += "</Types>\n";
const std::string rels =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\n"
" <Relationship Type=\"http://schemas.microsoft.com/packaging/2010/07/manifest\" "
"Target=\"/" +
wix_xml_escape(id) +
".nuspec\" Id=\"Re0\" />\n"
"</Relationships>\n";
const auto staging = output.parent_path() / (output.filename().string() + ".stage");
std::error_code ec;
std::filesystem::remove_all(staging, ec);
std::filesystem::create_directories(staging, ec);
if (ec) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("cannot create NuGet staging directory '{}'", staging.string()),
ec.value())};
}
auto cleanup = Void::Scope::on_exit([&] {
std::error_code cleanup_ec;
std::filesystem::remove_all(staging, cleanup_ec);
});
std::vector<Package::ArchiveEntrySpec> zip_entries;
const auto stage_file = [&](std::string_view name,
std::string_view content) -> std::optional<std::filesystem::path> {
const auto path = staging / std::filesystem::path{name};
std::error_code file_ec;
std::filesystem::create_directories(path.parent_path(), file_ec);
if (auto written = Platform::atomic_write_file(path, content, true); !written) {
return std::nullopt;
}
return path;
};
const auto nuspec_path = stage_file(id + ".nuspec", nuspec);
const auto types_path = stage_file("[Content_Types].xml", content_types);
const auto rels_path = stage_file("_rels/.rels", rels);
if (!nuspec_path || !types_path || !rels_path) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error, "cannot stage NuGet metadata")};
}
zip_entries.push_back({"[Content_Types].xml", *types_path, 0644u});
zip_entries.push_back({"_rels/.rels", *rels_path, 0644u});
zip_entries.push_back({id + ".nuspec", *nuspec_path, 0644u});
for (const auto &[name, source] : mapped) {
zip_entries.push_back({name, source, 0644u});
}
return Package::create_stored_zip(output, zip_entries);
}
// Debian package: ar container with debian-binary, control.tar and data.tar (uncompressed).
Void::Result::Result<void, Void::Result::Error>
write_deb_package(const std::filesystem::path &output, const InstallOptions &options,
const Graph::BuildGraph &graph,
const std::vector<Package::ArchiveEntrySpec> &entries) {
const auto scratch = output.parent_path() / (output.filename().string() + ".members");
std::filesystem::remove_all(scratch);
std::error_code ec;
std::filesystem::create_directories(scratch, ec);
auto cleanup = Void::Scope::on_exit([&] { std::filesystem::remove_all(scratch, ec); });
const auto data_tar = scratch / "data.tar";
auto data = Package::create_deterministic_tar(data_tar, entries, 0);
if (!data) {
return std::unexpected{data.error()};
}
std::uint64_t installed_size = 0;
for (const auto &entry : entries) {
if (const auto meta = Platform::stat_lstat(entry.source_file); meta && meta->exists) {
installed_size += meta->size;
}
}
std::string deb_arch = graph.profile.architecture;
std::ranges::transform(deb_arch, deb_arch.begin(), [](char c) {
return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
});
if (deb_arch == "x86_64") {
deb_arch = "amd64";
} else if (deb_arch == "aarch64" || deb_arch == "arm64") {
deb_arch = "arm64";
}
const std::string control_text =
"Package: " + options.package_name + "\n" + "Version: " + options.package_version + "\n" +
"Architecture: " + deb_arch + "\n" + "Maintainer: " +
(options.maintainer.empty() ? "Void Build <noreply@localhost>" : options.maintainer) +
"\n" + "Installed-Size: " + std::to_string(installed_size / 1024) + "\n" +
"Section: misc\nPriority: optional\n" + "Description: " +
(options.package_description.empty() ? options.package_name : options.package_description) +
"\n";
const auto control_file = scratch / "control";
if (auto wrote = Platform::atomic_write_file(control_file, control_text, false); !wrote) {
return std::unexpected{wrote.error()};
}
const auto control_tar = scratch / "control.tar";
auto control =
Package::create_deterministic_tar(control_tar, {{"control", control_file, 0644u}}, 0);
if (!control) {
return std::unexpected{control.error()};
}
// Stream the members: package payloads can exceed in-memory read limits.
const auto temp_deb = output.parent_path() / (output.filename().string() + ".tmp");
std::ofstream deb{temp_deb, std::ios::binary | std::ios::trunc};
if (!deb) {
return std::unexpected{
Void::System::make_system_error(Void::System::SystemErrorCode::io_error,
std::format("cannot create '{}'", temp_deb.string()))};
}
deb << "!<arch>\n";
append_ar_member_to_stream(deb, "debian-binary", "2.0\n");
if (auto member = append_ar_member_file(deb, "control.tar", control_tar); !member) {
return std::unexpected{member.error()};
}
if (auto member = append_ar_member_file(deb, "data.tar", data_tar); !member) {
return std::unexpected{member.error()};
}
deb.flush();
deb.close();
if (!deb) {
return std::unexpected{
Void::System::make_system_error(Void::System::SystemErrorCode::io_error,
std::format("failed writing '{}'", temp_deb.string()))};
}
std::error_code rename_ec;
std::filesystem::rename(temp_deb, output, rename_ec);
if (rename_ec) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(rename_ec.value()),
std::format("cannot publish '{}': {}", output.string(), rename_ec.message()),
rename_ec.value())};
}
return {};
}
// Canonical short message signed for installer archives (independent of archive size).
std::string installer_signing_message(std::string_view archive_sha256) {
return "vbs-installer-v1\n" + std::string{archive_sha256} + "\n";
}
} // namespace
Void::Result::Result<InstallReport, Void::Result::Error>
install_project(const Graph::ProjectDescription &description, const Graph::BuildGraph &graph,
const InstallOptions &options) {
if (options.prefix.empty()) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument, "install prefix is empty")};
}
if (options.package_name.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"install package_name is empty")};
}
std::error_code ec;
const auto prefix_abs = std::filesystem::weakly_canonical(options.prefix, ec);
const auto proj_root = graph.project_root;
if (Platform::path_is_within(proj_root, prefix_abs) &&
!Platform::path_is_within(graph.profile_build_dir, prefix_abs) && prefix_abs == proj_root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::permission_denied,
"refusing to install directly onto project source root")};
}
// Build complete list of staged copy operations and detect destination collisions upfront!
struct StagedItem {
std::filesystem::path src;
std::filesystem::path rel_dest;
std::uint32_t mode{0644};
std::string target_name;
};
std::vector<StagedItem> items;
std::set<std::filesystem::path> dest_set;
auto add_item =
[&](const std::filesystem::path &src, const std::filesystem::path &rel_dest,
std::uint32_t mode,
std::string target_name = {}) -> Void::Result::Result<void, Void::Result::Error> {
if (!is_safe_relative_dest(rel_dest)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::permission_denied,
std::format("install destination '{}' escapes prefix", rel_dest.string()))};
}
const auto norm = rel_dest.lexically_normal();
if (!dest_set.insert(norm).second) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
std::format("install destination collision on '{}'", norm.string()))};
}
if (!std::filesystem::is_regular_file(src, ec)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("install source artifact '{}' does not exist (build target first)",
src.string()))};
}
items.push_back({src, norm, mode, std::move(target_name)});
return {};
};
// 1. Installed targets.
struct ExportedTarget {
std::string name;
TargetKind kind;
std::filesystem::path rel_artifact;
std::vector<std::string> public_defines;
std::vector<std::string> public_compile_opts;
std::vector<std::string> local_deps;
};
std::vector<ExportedTarget> exported_targets;
std::set<std::string> bundled_library_names;
std::vector<std::filesystem::path> bundled_libraries;
for (const auto &trec : description.targets) {
if (!trec.install_rule) {
continue;
}
if (options.component && trec.install_rule->component != *options.component) {
continue;
}
const std::string dest_dir = trec.install_rule->destination.empty()
? default_dest_for_kind(trec.kind)
: trec.install_rule->destination;
const auto sum_it =
std::ranges::find(graph.targets, trec.name, &Graph::ResolvedTargetSummary::name);
if (sum_it == graph.targets.end()) {
continue;
}
ExportedTarget et;
et.name = trec.name;
et.kind = trec.kind;
for (const auto &d : trec.defines) {
if (d.visibility != Visibility::Private) {
et.public_defines.push_back(d.value);
}
}
for (const auto &o : trec.scoped_compile_options) {
if (o.visibility != Visibility::Private) {
et.public_compile_opts.push_back(o.value);
}
}
for (const auto &l : trec.links) {
if (l.kind == LinkKind::Local &&
(l.visibility != Visibility::Private || trec.kind == TargetKind::StaticLibrary)) {
et.local_deps.push_back(l.target);
}
}
if (!sum_it->primary_outputs.empty()) {
const auto &art = sum_it->primary_outputs.front();
const auto rel_dest = std::filesystem::path{dest_dir} / art.filename();
const std::uint32_t mode =
(trec.kind == TargetKind::Executable || trec.kind == TargetKind::SharedLibrary)
? 0755u
: 0644u;
if (auto r = add_item(art, rel_dest, mode, trec.name); !r) {
return std::unexpected{r.error()};
}
et.rel_artifact = rel_dest;
}
// Bundle runtime shared libraries so the prefix is self-contained.
if (options.bundle_runtime_dependencies) {
for (const auto &library_path : sum_it->runtime_shared_libraries) {
const std::string filename = library_path.filename().string();
if (!bundled_library_names.insert(filename).second) {
continue;
}
const auto rel_dest = std::filesystem::path{"lib"} / filename;
if (auto r = add_item(library_path, rel_dest, 0755u, trec.name); !r) {
return std::unexpected{r.error()};
}
bundled_libraries.push_back(library_path);
}
}
exported_targets.push_back(std::move(et));
}
// 2. Project file & directory install rules (headers/data).
for (const auto &rule : description.install_rules) {
if (options.component && rule.component != *options.component) {
continue;
}
const auto src_abs = std::filesystem::path{rule.source_path}.is_absolute()
? std::filesystem::path{rule.source_path}
: (proj_root / rule.source_path);
if (rule.is_directory) {
if (!std::filesystem::is_directory(src_abs, ec)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("install directory '{}' does not exist", src_abs.string()))};
}
for (const auto &ent : std::filesystem::recursive_directory_iterator(src_abs, ec)) {
if (ent.is_regular_file(ec)) {
const auto rel = ent.path().lexically_relative(src_abs);
if (auto r = add_item(ent.path(), std::filesystem::path{rule.destination} / rel,
0644u);
!r) {
return std::unexpected{r.error()};
}
}
}
} else {
const auto rel_dest = std::filesystem::path{rule.destination} / src_abs.filename();
if (auto r = add_item(src_abs, rel_dest, 0644u); !r) {
return std::unexpected{r.error()};
}
}
}
// 3. Stage everything privately first so failed installs never leave broken metadata.
const auto stage_root = graph.profile_build_dir /
std::format("install-stage-{}", static_cast<long long>(::getpid()));
std::filesystem::remove_all(stage_root, ec);
std::filesystem::create_directories(stage_root, ec);
auto stage_guard = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage_root, ec); });
std::vector<std::filesystem::path> owned_rel_files;
for (const auto &item : items) {
const auto staged = stage_root / item.rel_dest;
auto copied = Platform::copy_isolated(item.src, staged, item.mode);
if (!copied) {
return std::unexpected{copied.error()};
}
owned_rel_files.push_back(item.rel_dest);
}
// 4. Generate relocatable native package metadata (ZERO build/snapshot paths!).
std::optional<std::filesystem::path> native_rel;
if (options.export_native_metadata) {
using Util::json_array;
using Util::json_quote;
native_rel = std::filesystem::path{"share"} / "vbs" / options.package_name / "package.json";
std::string pjson =
"{\"schema_version\":1,\"name\":" + json_quote(options.package_name) +
",\"version\":" + json_quote(options.package_version) +
",\"profile\":" + json_quote(graph.profile.name) +
",\"compiler\":" + json_quote(compiler_name(graph.profile.compiler)) +
",\"os\":" + json_quote(graph.profile.os) +
",\"architecture\":" + json_quote(graph.profile.architecture) +
",\"include_dir\":\"include\",\"targets\":" +
json_array(exported_targets,
[](const ExportedTarget &et) {
return "{\"name\":" + json_quote(et.name) +
",\"kind\":" + json_quote(target_kind_name(et.kind)) +
",\"artifact\":" + json_quote(et.rel_artifact.generic_string()) +
",\"defines\":" + json_array(et.public_defines, json_quote) +
",\"compile_options\":" +
json_array(et.public_compile_opts, json_quote) +
",\"dependencies\":" + json_array(et.local_deps, json_quote) +
'}';
}) +
"}\n";
if (auto w = Platform::atomic_write_file(stage_root / *native_rel, pjson, false); !w) {
return std::unexpected{w.error()};
}
owned_rel_files.push_back(*native_rel);
}
// 5. Generate relocatable CMake Config + Targets files using ${_vbs_prefix} relative paths!
std::optional<std::filesystem::path> cmake_rel;
if (options.export_cmake_config) {
const auto cmake_dir = std::filesystem::path{"lib"} / "cmake" / options.package_name;
cmake_rel = cmake_dir / (options.package_name + "Config.cmake");
const auto targets_rel = cmake_dir / (options.package_name + "Targets.cmake");
std::string cfg_cmake =
"# Relocatable CMake config generated by VoidBuildSystem\n"
"get_filename_component(_vbs_prefix \"${CMAKE_CURRENT_LIST_DIR}/../../..\" ABSOLUTE)\n"
"include(\"${CMAKE_CURRENT_LIST_DIR}/" +
options.package_name + "Targets.cmake\")\n";
std::string tgt_cmake =
"# Relocatable CMake imported targets generated by VoidBuildSystem\n"
"get_filename_component(_vbs_prefix \"${CMAKE_CURRENT_LIST_DIR}/../../..\" ABSOLUTE)\n";
for (const auto &et : exported_targets) {
const std::string full = options.package_name + "::" + et.name;
std::string cm_type = "STATIC";
if (et.kind == TargetKind::SharedLibrary) {
cm_type = "SHARED";
} else if (et.kind == TargetKind::HeaderOnly) {
cm_type = "INTERFACE";
} else if (et.kind == TargetKind::Executable) {
continue;
}
tgt_cmake += "if(NOT TARGET " + full + ")\n";
tgt_cmake += " add_library(" + full + " " + cm_type + " IMPORTED)\n";
tgt_cmake += " set_target_properties(" + full + " PROPERTIES\n";
if (!et.rel_artifact.empty()) {
tgt_cmake += " IMPORTED_LOCATION \"${_vbs_prefix}/" +
escape_cmake_str(et.rel_artifact.generic_string()) + "\"\n";
}
tgt_cmake += " INTERFACE_INCLUDE_DIRECTORIES \"${_vbs_prefix}/include\"\n";
if (!et.public_defines.empty()) {
tgt_cmake += " INTERFACE_COMPILE_DEFINITIONS \"";
for (std::size_t i = 0; i < et.public_defines.size(); ++i) {
if (i > 0) {
tgt_cmake += ";";
}
tgt_cmake += escape_cmake_str(et.public_defines[i]);
}
tgt_cmake += "\"\n";
}
if (!et.local_deps.empty()) {
tgt_cmake += " INTERFACE_LINK_LIBRARIES \"";
for (std::size_t i = 0; i < et.local_deps.size(); ++i) {
if (i > 0) {
tgt_cmake += ";";
}
tgt_cmake += options.package_name + "::" + et.local_deps[i];
}
tgt_cmake += "\"\n";
}
tgt_cmake += " )\nendif()\n";
}
if (auto w = Platform::atomic_write_file(stage_root / *cmake_rel, cfg_cmake, false); !w) {
return std::unexpected{w.error()};
}
if (auto w = Platform::atomic_write_file(stage_root / targets_rel, tgt_cmake, false); !w) {
return std::unexpected{w.error()};
}
owned_rel_files.push_back(*cmake_rel);
owned_rel_files.push_back(targets_rel);
}
// 6. Publish staged files into prefix atomically and write ownership manifest.
std::filesystem::create_directories(prefix_abs, ec);
InstallReport report;
report.prefix = prefix_abs;
for (const auto &rel : owned_rel_files) {
const auto staged = stage_root / rel;
const auto final_dst = prefix_abs / rel;
auto meta = Platform::stat_lstat(staged);
auto copied = Platform::copy_isolated(staged, final_dst, meta ? meta->mode : 0644u);
if (!copied) {
return std::unexpected{copied.error()};
}
report.installed_files.push_back(final_dst);
}
report.manifest_path = prefix_abs / ".vbs-install-manifest.json";
if (native_rel) {
report.native_package_file = prefix_abs / *native_rel;
}
if (cmake_rel) {
report.cmake_config_file = prefix_abs / *cmake_rel;
}
const std::string manifest_json =
"{\"schema_version\":1,\"package\":" + Util::json_quote(options.package_name) +
",\"files\":" +
Util::json_array(
owned_rel_files,
[](const std::filesystem::path &p) { return Util::json_quote(p.generic_string()); }) +
"}\n";
auto mw = Platform::atomic_write_file(report.manifest_path, manifest_json, true);
if (!mw) {
return std::unexpected{mw.error()};
}
report.bundled_libraries = std::move(bundled_libraries);
// 7. Optional deterministic installer archive of the published prefix.
if (options.archive_path) {
std::vector<Package::ArchiveEntrySpec> archive_entries;
archive_entries.reserve(report.installed_files.size());
for (const auto &file : report.installed_files) {
const auto meta = Platform::stat_lstat(file);
archive_entries.push_back({file.lexically_relative(prefix_abs).generic_string(), file,
meta ? (meta->mode & 0777u) : 0644u});
}
if (options.archive_format == "zip") {
if (auto zipped = Package::create_stored_zip(*options.archive_path, archive_entries);
!zipped) {
return std::unexpected{zipped.error()};
}
} else if (options.archive_format == "deb") {
if (auto packed =
write_deb_package(*options.archive_path, options, graph, archive_entries);
!packed) {
return std::unexpected{packed.error()};
}
} else if (options.archive_format == "rpm") {
if (auto packed =
write_rpm_package(*options.archive_path, options, graph, archive_entries);
!packed) {
return std::unexpected{packed.error()};
}
} else if (options.archive_format == "wix") {
if (auto packed = write_wix_source(*options.archive_path, options, archive_entries);
!packed) {
return std::unexpected{packed.error()};
}
} else if (options.archive_format == "dmg") {
const auto payload = stage_root / "installer-payload.tar";
auto archived =
Package::create_deterministic_tar(payload, std::move(archive_entries), 0);
if (!archived) {
return std::unexpected{archived.error()};
}
if (auto packed = write_dmg_archive(*options.archive_path, payload); !packed) {
return std::unexpected{packed.error()};
}
} else if (options.archive_format == "nuget") {
if (auto packed =
write_nuget_package(*options.archive_path, options, graph, archive_entries);
!packed) {
return std::unexpected{packed.error()};
}
} else {
const bool archive_as_script = options.archive_format == "sh";
const auto archive_target = archive_as_script
? stage_root / "installer-payload.tar"
: std::filesystem::path{*options.archive_path};
auto archived =
Package::create_deterministic_tar(archive_target, std::move(archive_entries), 0);
if (!archived) {
return std::unexpected{archived.error()};
}
if (archive_as_script) {
// Self-extracting installer: a POSIX sh header followed by the tar payload.
const auto make_header = [&](std::size_t payload_line) {
return "#!/bin/sh\n"
"# VoidBuildSystem self-extracting installer for " +
options.package_name + " " + options.package_version +
"\n"
"# Usage: sh <installer> [--prefix DIR] (default: "
"${PREFIX:-/usr/local})\n"
"set -eu\n"
"prefix=\"${PREFIX:-/usr/local}\"\n"
"if [ \"${1:-}\" = \"--prefix\" ]; then\n"
" prefix=\"${2:?--prefix requires a directory}\"\n"
"fi\n"
"tmp=\"$(mktemp -d)\"\n"
"trap 'rm -rf \"$tmp\"' EXIT\n"
"tail -n +" +
std::to_string(payload_line) +
" \"$0\" > \"$tmp/payload.tar\"\n"
"mkdir -p \"$prefix\"\n"
"tar -x -f \"$tmp/payload.tar\" -C \"$prefix\"\n"
"echo \"installed " +
options.package_name +
" to $prefix\"\n"
"exit 0\n";
};
std::size_t header_lines = 0;
for (const char c : make_header(0)) {
if (c == '\n') {
++header_lines;
}
}
const std::string header = make_header(header_lines + 1);
auto payload = Void::FileSystem::read_file(archive_target);
if (!payload) {
return std::unexpected{payload.error()};
}
std::string script = header;
script += *payload;
if (auto written =
Platform::atomic_write_file(*options.archive_path, script, true, 0755);
!written) {
return std::unexpected{written.error()};
}
}
}
report.archive_path = *options.archive_path;
// Optional detached signature and checksums over the final archive. The signed message
// is a short canonical digest statement, not the archive bytes, so archives of any size
// stay within the crypto one-shot limit.
if (options.signing_seed_path) {
auto digest = Util::sha256_file_hex(*options.archive_path);
if (!digest) {
return std::unexpected{digest.error()};
}
report.archive_sha256 = *digest;
report.checksum_path = options.archive_path->string() + ".sha256";
if (auto written = Platform::atomic_write_file(
*report.checksum_path,
report.archive_sha256 + " " + options.archive_path->filename().string() + "\n",
true);
!written) {
return std::unexpected{written.error()};
}
const std::string canonical_message = installer_signing_message(report.archive_sha256);
auto signature =
Provenance::sign_message(std::as_bytes(std::span<const char>{
canonical_message.data(), canonical_message.size()}),
*options.signing_seed_path);
if (!signature) {
return std::unexpected{signature.error()};
}
auto public_key = Provenance::public_key_from_seed(*options.signing_seed_path);
if (!public_key) {
return std::unexpected{public_key.error()};
}
report.signature_path = options.archive_path->string() + ".sig";
if (auto written =
Platform::atomic_write_file(*report.signature_path, *signature + "\n", true);
!written) {
return std::unexpected{written.error()};
}
report.public_key_path = options.archive_path->string() + ".pub";
if (auto written =
Platform::atomic_write_file(*report.public_key_path, *public_key + "\n", true);
!written) {
return std::unexpected{written.error()};
}
if (auto written = Platform::atomic_write_file(options.archive_path->string() + ".msg",
canonical_message, true);
!written) {
return std::unexpected{written.error()};
}
}
}
return report;
}
Void::Result::Result<std::size_t, Void::Result::Error>
uninstall_prefix(const std::filesystem::path &prefix) {
const auto manifest_path = prefix / ".vbs-install-manifest.json";
auto text = Void::FileSystem::read_file(manifest_path);
if (!text) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("no VBS install manifest found at '{}'", manifest_path.string()))};
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"corrupt VBS install manifest")};
}
const auto *root = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"invalid VBS install manifest")};
}
std::size_t removed = 0;
std::error_code ec;
const auto canon_prefix = std::filesystem::weakly_canonical(prefix, ec);
const auto fit = root->find("files");
if (fit != root->end()) {
if (const auto *arr = std::get_if<Void::Json::Strict::Value::Array>(&fit->second.value)) {
for (const auto &v : *arr) {
if (const auto *s = std::get_if<std::string>(&v.value)) {
const std::filesystem::path rel{*s};
if (!is_safe_relative_dest(rel)) {
continue;
}
const auto target = (canon_prefix / rel).lexically_normal();
if (Platform::path_is_within(canon_prefix, target) &&
std::filesystem::is_regular_file(target, ec)) {
std::filesystem::remove(target, ec);
if (!ec) {
++removed;
}
}
}
}
}
}
std::filesystem::remove(manifest_path, ec);
return removed;
}
} // namespace Void::Build::Install