Files
Build-System/src/Platform/Linux/FileOps.cpp
T
faumaray 8e3fffd636
VoidBuildSystem CI / 1 · Requirements (push) Successful in 6s
VoidBuildSystem CI / 2B · Windows Wine build (debug) (push) Successful in 4m17s
VoidBuildSystem CI / 2A · Linux build (debug) (push) Successful in 4m25s
VoidBuildSystem CI / 2B · Windows Wine build (sanitizers) (push) Successful in 5m11s
VoidBuildSystem CI / 2A · Linux build (sanitizers) (push) Successful in 5m25s
VoidBuildSystem CI / 2A · Linux build (relwithdebinfo) (push) Successful in 6m12s
VoidBuildSystem CI / 2C · Windows native build (debug) (push) Successful in 6m20s
VoidBuildSystem CI / 2C · Windows native build (sanitizers) (push) Failing after 22s
VoidBuildSystem CI / 2B · Windows Wine build (relwithdebinfo) (push) Successful in 3m35s
VoidBuildSystem CI / 3A · Linux test (sanitizers) (push) Successful in 1m38s
VoidBuildSystem CI / 3B · Windows Wine test (relwithdebinfo) (push) Successful in 2m42s
VoidBuildSystem CI / 3B · Windows Wine test (sanitizers) (push) Successful in 2m45s
VoidBuildSystem CI / 3B · Windows Wine test (debug) (push) Successful in 2m55s
VoidBuildSystem CI / 2C · Windows native build (relwithdebinfo) (push) Successful in 4m10s
VoidBuildSystem CI / 3C · Windows native test (debug) (push) Failing after 55s
VoidBuildSystem CI / 3C · Windows native test (sanitizers) (push) Failing after 15s
VoidBuildSystem CI / 3A · Linux test (relwithdebinfo) (push) Failing after 6m29s
VoidBuildSystem CI / 3A · Linux test (debug) (push) Failing after 6m34s
VoidBuildSystem CI / 4A · Linux package (debug) (push) Skipped
VoidBuildSystem CI / 4A · Linux package (relwithdebinfo) (push) Skipped
VoidBuildSystem CI / 4A · Linux package (sanitizers) (push) Skipped
VoidBuildSystem CI / 3C · Windows native test (relwithdebinfo) (push) Failing after 48s
VoidBuildSystem CI / 4B · Windows package (debug) (push) Successful in 1m54s
VoidBuildSystem CI / 4B · Windows package (sanitizers) (push) Successful in 16s
VoidBuildSystem CI / 4B · Windows package (relwithdebinfo) (push) Successful in 4m0s
VoidBuildSystem CI / 5 · Release (push) Skipped
chore(deps): bump VoidLibrary to de1fdcda
The new pin vendors SQLite for every platform (Sqlite is now qualified
on Windows), implements FileLock, symlink swap, reflink copy and
timestamps on Windows (Void/Library#66), so the local Win32 lock and
mtime workarounds go back to the VoidLibrary primitives, and VBS enables
Void::Sqlite unconditionally since Void resolves its own backend.

Verified: MinGW-w64 Windows build of all targets, vbs under Wine, SDK
suite 17/17 under Wine, and the Linux suite 8/8.
2026-12-06 02:30:49 +03:00

431 lines
16 KiB
C++

#include <Void/Build/Platform/FileOps.hpp>
#include <Void/System/Types.hpp>
#include <cerrno>
#include <chrono>
#include <format>
#include <set>
#include <system_error>
#include <utility>
#if defined(_WIN32)
#include <windows.h>
#else
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#if !defined(__linux__) && !defined(_WIN32)
#error \
"VoidBuildSystem's process and file backends currently support Linux and Windows hosts only (Track C2/C3 ports are planned)"
#endif
namespace Void::Build::Platform {
namespace {
Void::Result::Error sys_err(int err, std::string message) {
return Void::System::make_system_error(Void::System::map_errno_to_system_code(err),
std::move(message), err);
}
} // namespace
Void::Result::Result<FileLock, Void::Result::Error>
FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool non_blocking) {
std::error_code ec;
if (lock_path.has_parent_path()) {
std::filesystem::create_directories(lock_path.parent_path(), ec);
if (ec) {
return std::unexpected{
sys_err(ec.value(), std::format("FileLock: failed creating parent for '{}': {}",
lock_path.string(), ec.message()))};
}
}
const auto vl_mode = (mode == LockMode::Exclusive) ? Void::FileSystem::LockMode::Exclusive
: Void::FileSystem::LockMode::Shared;
if (non_blocking) {
auto res = Void::FileSystem::FileLock::try_lock(lock_path, vl_mode);
if (!res) {
return std::unexpected{std::move(res.error())};
}
if (!res->has_value()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
std::format("FileLock: '{}' is already locked", lock_path.string()), EAGAIN)};
}
return FileLock{std::move(**res)};
}
auto res = Void::FileSystem::FileLock::lock(lock_path, vl_mode);
if (!res) {
return std::unexpected{std::move(res.error())};
}
return FileLock{std::move(*res)};
}
Void::Result::Result<FileMetadata, Void::Result::Error>
stat_lstat(const std::filesystem::path &path) {
#if defined(_WIN32)
std::error_code ec;
const auto status = std::filesystem::symlink_status(path, ec);
if (ec) {
if (ec == std::errc::no_such_file_or_directory || ec == std::errc::not_a_directory) {
FileMetadata missing;
return missing;
}
return std::unexpected{sys_err(
ec.value(), std::format("stat_lstat: symlink_status failed for '{}': {}",
path.string(), ec.message()))};
}
if (!std::filesystem::exists(status)) {
FileMetadata missing;
return missing;
}
FileMetadata meta;
meta.exists = true;
meta.is_regular = std::filesystem::is_regular_file(status);
meta.is_directory = std::filesystem::is_directory(status);
meta.is_symlink = std::filesystem::is_symlink(status);
if (meta.is_symlink) {
std::error_code target_ec;
const auto target = std::filesystem::read_symlink(path, target_ec);
if (!target_ec) {
meta.symlink_target = target.string();
}
}
const auto followed = std::filesystem::status(path, ec);
if (!ec) {
if (std::filesystem::is_regular_file(followed)) {
const auto size = std::filesystem::file_size(path, ec);
if (!ec) {
meta.size = static_cast<std::uint64_t>(size);
}
ec.clear();
}
const auto mtime = std::filesystem::last_write_time(path, ec);
if (!ec) {
const auto sys = std::chrono::file_clock::to_sys(mtime);
const auto secs = std::chrono::floor<std::chrono::seconds>(sys);
meta.mtime_sec = static_cast<std::int64_t>(secs.time_since_epoch().count());
meta.mtime_nsec = static_cast<std::int64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(sys - secs).count());
}
}
// Identity through a Win32 handle (volume serial, file index, link count).
const HANDLE handle = ::CreateFileW(path.c_str(), FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
if (handle != INVALID_HANDLE_VALUE) {
BY_HANDLE_FILE_INFORMATION info{};
if (::GetFileInformationByHandle(handle, &info) != 0) {
meta.dev = info.dwVolumeSerialNumber;
meta.ino = (static_cast<std::uint64_t>(info.nFileIndexHigh) << 32) |
static_cast<std::uint64_t>(info.nFileIndexLow);
meta.nlink = info.nNumberOfLinks;
}
::CloseHandle(handle);
}
meta.mode = meta.is_directory ? 0755u : 0644u;
return meta;
#else
struct stat st{};
if (::lstat(path.c_str(), &st) != 0) {
const int err = errno;
if (err == ENOENT || err == ENOTDIR) {
FileMetadata missing;
missing.exists = false;
return missing;
}
return std::unexpected{
sys_err(err, std::format("stat_lstat: lstat failed for '{}'", path.string()))};
}
FileMetadata meta;
meta.exists = true;
meta.is_regular = S_ISREG(st.st_mode);
meta.is_directory = S_ISDIR(st.st_mode);
meta.is_symlink = S_ISLNK(st.st_mode);
meta.dev = static_cast<std::uint64_t>(st.st_dev);
meta.ino = static_cast<std::uint64_t>(st.st_ino);
meta.size = static_cast<std::uint64_t>(st.st_size);
meta.nlink = static_cast<std::uint64_t>(st.st_nlink);
meta.mode = static_cast<std::uint32_t>(st.st_mode & 07777u);
meta.mtime_sec = static_cast<std::int64_t>(st.st_mtim.tv_sec);
meta.mtime_nsec = static_cast<std::int64_t>(st.st_mtim.tv_nsec);
if (meta.is_symlink) {
std::size_t buf_size =
st.st_size > 0 ? static_cast<std::size_t>(st.st_size) + 1 : std::size_t{256};
for (int attempt = 0; attempt < 8; ++attempt) {
std::string target(buf_size, '\0');
const ssize_t n = ::readlink(path.c_str(), target.data(), target.size());
if (n < 0) {
const int err = errno;
return std::unexpected{sys_err(
err, std::format("stat_lstat: readlink failed for '{}'", path.string()))};
}
if (static_cast<std::size_t>(n) < target.size()) {
target.resize(static_cast<std::size_t>(n));
meta.symlink_target = std::move(target);
break;
}
buf_size *= 2;
}
}
return meta;
#endif
}
Void::Result::Result<bool, Void::Result::Error>
copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst,
std::optional<std::uint32_t> mode_override) {
std::error_code ec;
if (dst.has_parent_path()) {
std::filesystem::create_directories(dst.parent_path(), ec);
if (ec) {
return std::unexpected{sys_err(
ec.value(), std::format("copy_isolated: cannot create parent dir for '{}': {}",
dst.string(), ec.message()))};
}
}
Void::FileSystem::CopyOptions opts;
opts.overwrite = true;
opts.preserve_permissions = !mode_override.has_value();
opts.durability = Void::FileSystem::ReplaceDurability::atomic_visibility;
auto res = Void::FileSystem::reflink_copy_file(src, dst, opts);
if (!res) {
return std::unexpected{std::move(res.error())};
}
#if !defined(_WIN32)
if (mode_override) {
(void)::chmod(dst.c_str(), static_cast<mode_t>(*mode_override));
}
#else
(void)mode_override;
#endif
return res->method == Void::FileSystem::CopyMethod::Reflink;
}
Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds) {
return Void::FileSystem::set_canonical_mtime(path, epoch_seconds, 0);
}
Void::Result::Result<void, Void::Result::Error>
atomic_write_bytes(const std::filesystem::path &path, std::span<const std::byte> bytes,
bool durable_sync, unsigned mode) {
std::error_code ec;
if (path.has_parent_path()) {
std::filesystem::create_directories(path.parent_path(), ec);
if (ec) {
return std::unexpected{sys_err(
ec.value(), std::format("atomic_write_bytes: create_directories failed for '{}'",
path.string()))};
}
}
Void::FileSystem::ReplaceOptions opts;
opts.durability = durable_sync ? Void::FileSystem::ReplaceDurability::durable_sync
: Void::FileSystem::ReplaceDurability::atomic_visibility;
opts.mode = mode;
auto res = Void::FileSystem::replace_file(path, bytes, opts);
if (!res) {
return std::unexpected{std::move(res.error().error)};
}
return {};
}
Void::Result::Result<void, Void::Result::Error> atomic_write_file(const std::filesystem::path &path,
std::string_view content,
bool durable_sync,
unsigned mode) {
return atomic_write_bytes(path,
std::as_bytes(std::span<const char>{content.data(), content.size()}),
durable_sync, mode);
}
Void::Result::Result<void, Void::Result::Error>
fsync_directory(const std::filesystem::path &dir_path) {
#if defined(_WIN32)
// Windows has no directory fsync; MoveFileEx visibility is the durability guarantee.
(void)dir_path;
return {};
#else
const int fd = ::open(dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
return std::unexpected{
sys_err(err, std::format("fsync_directory: open failed for '{}'", dir_path.string()))};
}
Void::System::OwnedFd guard{fd};
for (;;) {
if (::fsync(fd) == 0) {
return {};
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EINVAL || err == EROFS) {
return {};
}
return std::unexpected{
sys_err(err, std::format("fsync_directory: fsync failed for '{}'", dir_path.string()))};
}
#endif
}
Void::Result::Result<void, Void::Result::Error>
atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target) {
std::error_code ec;
const auto parent =
link_path.has_parent_path() ? link_path.parent_path() : std::filesystem::path{"."};
std::filesystem::create_directories(parent, ec);
if (ec) {
return std::unexpected{sys_err(
ec.value(), std::format("atomic_swap_symlink: create_directories failed for '{}'",
parent.string()))};
}
return Void::FileSystem::atomic_symlink_swap(link_path, target,
Void::FileSystem::ReplaceDurability::durable_sync);
}
bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) {
const auto norm_root = root.lexically_normal();
const auto norm_path = path.lexically_normal();
auto r_it = norm_root.begin();
auto p_it = norm_path.begin();
for (; r_it != norm_root.end(); ++r_it, ++p_it) {
if (r_it->empty() || *r_it == ".") {
continue;
}
if (p_it == norm_path.end() || *r_it != *p_it) {
return false;
}
}
return true;
}
Void::Result::Result<std::filesystem::path, Void::Result::Error>
resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate,
const std::vector<std::filesystem::path> &allowed_external_roots) {
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(root, ec);
if (ec) {
return std::unexpected{
sys_err(ec.value(), std::format("resolve_confined_path: cannot canonicalize root '{}'",
root.string()))};
}
std::vector<std::filesystem::path> allowed{canonical_root};
for (const auto &ext : allowed_external_roots) {
const auto ce = std::filesystem::weakly_canonical(ext, ec);
if (!ec) {
allowed.push_back(ce);
}
}
std::filesystem::path current =
candidate.is_absolute() ? candidate : (canonical_root / candidate);
current = current.lexically_normal();
constexpr int kMaxSymlinkHops = 40;
int hops = 0;
std::set<std::filesystem::path> seen;
for (;;) {
std::filesystem::path acc;
bool followed_symlink = false;
auto it = current.begin();
for (; it != current.end(); ++it) {
if (*it == ".") {
continue;
}
if (*it == "..") {
acc = acc.parent_path();
continue;
}
acc /= *it;
auto meta = stat_lstat(acc);
if (!meta) {
return std::unexpected{meta.error()};
}
if (!meta->exists) {
++it;
for (; it != current.end(); ++it) {
acc /= *it;
}
current = acc.lexically_normal();
break;
}
if (meta->is_symlink) {
if (++hops > kMaxSymlinkHops || !seen.insert(acc).second) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("resolve_confined_path: symlink loop detected at '{}'",
acc.string()),
ELOOP)};
}
std::filesystem::path target_path{meta->symlink_target};
std::filesystem::path rebuilt =
target_path.is_absolute() ? target_path : (acc.parent_path() / target_path);
++it;
for (; it != current.end(); ++it) {
rebuilt /= *it;
}
current = rebuilt.lexically_normal();
followed_symlink = true;
break;
}
}
if (!followed_symlink) {
break;
}
}
for (const auto &allowed_root : allowed) {
if (path_is_within(allowed_root, current)) {
return current;
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::permission_denied,
std::format("resolve_confined_path: '{}' escapes declared roots (root='{}')",
candidate.string(), canonical_root.string()),
EACCES)};
}
Void::Result::Result<std::filesystem::path, Void::Result::Error> current_executable_path() {
#if defined(_WIN32)
std::wstring buffer(32768, L'\0');
const DWORD length =
::GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
if (length == 0 || length >= buffer.size()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error,
std::format("current_executable_path: GetModuleFileNameW failed ({})",
::GetLastError()))};
}
buffer.resize(length);
return std::filesystem::path{buffer};
#else
std::error_code ec;
const auto path = std::filesystem::read_symlink("/proc/self/exe", ec);
if (ec || path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::io_error,
std::format("current_executable_path: cannot resolve /proc/self/exe: {}",
ec ? ec.message() : "empty path"),
ec.value())};
}
return path;
#endif
}
} // namespace Void::Build::Platform