From dcfde7f51d09c18e1eaa4f0757c90db0d5e796d6 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sun, 6 Dec 2026 01:45:06 +0300 Subject: [PATCH] System: implement FileLock, symlink swap, reflink copy and timestamps on Windows - FileLock: _wopen + LockFileEx/UnlockFileEx byte-range locks (shared and exclusive, blocking and non-blocking). - atomic_symlink_swap: CreateSymbolicLinkW to a temp name, then MoveFileExW replace (write-through for durable_sync). - reflink_copy_file: staged copy with an FSCTL_DUPLICATE_EXTENTS_TO_FILE block-clone attempt and a streaming private-copy fallback, no-overwrite publish, attribute preservation and optional parent flush. - set_timestamps_nofollow: FILE_WRITE_ATTRIBUTES handle opened with FILE_FLAG_OPEN_REPARSE_POINT and SetFileTime. - OwnedFd now actually closes its descriptor on Windows. The combined filesystem test runs on both platforms now. Verified under Wine 11 (x86_64-w64-mingw32 GCC 16.2): full suite passes (1337 tests, 1326 passed, 11 skipped, 0 failed). Linux System+Testing suite unchanged (477 tests, 474 passed). --- include/Void/System/Path.hpp | 450 +++++++++++++++++++++++++++++-- include/Void/System/Types.hpp | 12 +- tests/standalone/System/Path.cpp | 22 +- 3 files changed, 453 insertions(+), 31 deletions(-) diff --git a/include/Void/System/Path.hpp b/include/Void/System/Path.hpp index b092315..e319383 100644 --- a/include/Void/System/Path.hpp +++ b/include/Void/System/Path.hpp @@ -44,6 +44,10 @@ #define NOMINMAX #endif #include +#include +#include +#include +#include #endif namespace Void::FileSystem @@ -1129,6 +1133,17 @@ public: } fd_.reset(); } +#else + if (fd_.valid()) { + const HANDLE handle = + reinterpret_cast(::_get_osfhandle(fd_.get())); + if (handle != INVALID_HANDLE_VALUE) { + OVERLAPPED overlapped{}; + (void)::UnlockFileEx(handle, 0, MAXDWORD, MAXDWORD, + &overlapped); + } + fd_.reset(); + } #endif } @@ -1210,12 +1225,51 @@ private: err)}; } #else - (void)path; - (void)mode; - (void)nonblocking; - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::FileLock: unsupported platform")}; + if (path.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::FileLock: empty path")}; + } + const int raw = ::_wopen(path.c_str(), _O_CREAT | _O_RDWR | _O_BINARY, + _S_IREAD | _S_IWRITE); + if (raw < 0) { + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::FileLock: cannot open '{}'", + path.string()), + err)}; + } + Void::System::OwnedFd fd{raw}; + const HANDLE handle = + reinterpret_cast(::_get_osfhandle(fd.get())); + if (handle == INVALID_HANDLE_VALUE) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::io_error, + std::format("FileSystem::FileLock: invalid handle for '{}'", + path.string()))}; + } + OVERLAPPED overlapped{}; + DWORD flags = 0; + if (mode == LockMode::Exclusive) { + flags |= LOCKFILE_EXCLUSIVE_LOCK; + } + if (nonblocking) { + flags |= LOCKFILE_FAIL_IMMEDIATELY; + } + if (::LockFileEx(handle, flags, 0, MAXDWORD, MAXDWORD, &overlapped) == 0) { + const DWORD error = ::GetLastError(); + if (nonblocking && + (error == ERROR_LOCK_VIOLATION || error == ERROR_IO_PENDING)) { + return std::optional{std::nullopt}; + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::io_error, + std::format("FileSystem::FileLock: LockFileEx failed for '{}' " + "({})", + path.string(), error))}; + } + return std::optional{FileLock{std::move(fd), mode}}; #endif } @@ -1323,12 +1377,69 @@ private: } return {}; #else - (void)link_path; - (void)target; - (void)durability; - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::atomic_symlink_swap: unsupported platform")}; + if (link_path.empty() || !link_path.has_filename() || target.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::atomic_symlink_swap: empty link or target path")}; + } + const std::string target_name = link_path.filename().string(); + if (target_name == "." || target_name == "..") { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::atomic_symlink_swap: invalid link filename")}; + } + const std::filesystem::path parent = + link_path.parent_path().empty() ? std::filesystem::path{"."} + : link_path.parent_path(); + + std::error_code ec; + const bool target_is_directory = std::filesystem::is_directory(target, ec); + DWORD flags = target_is_directory ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0; +#ifdef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE + flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; +#endif + + std::filesystem::path temp_path; + bool created = false; + DWORD last_error = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + temp_path = parent / std::format(".{}.void_lnk_{:016x}", target_name, + detail::next_temp_entropy()); + if (::CreateSymbolicLinkW(temp_path.c_str(), target.c_str(), flags) != 0) { + created = true; + break; + } + last_error = ::GetLastError(); + if (last_error != ERROR_ALREADY_EXISTS && + last_error != ERROR_FILE_EXISTS) { + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(last_error), + std::format( + "FileSystem::atomic_symlink_swap: symlink failed in '{}'", + parent.string()), + last_error)}; + } + } + if (!created) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "FileSystem::atomic_symlink_swap: exhausted temporary link names")}; + } + + DWORD move_flags = MOVEFILE_REPLACE_EXISTING; + if (durability == ReplaceDurability::durable_sync) { + move_flags |= MOVEFILE_WRITE_THROUGH; + } + if (::MoveFileExW(temp_path.c_str(), link_path.c_str(), move_flags) == 0) { + const DWORD error = ::GetLastError(); + (void)::DeleteFileW(temp_path.c_str()); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format("FileSystem::atomic_symlink_swap: rename failed for '{}'", + link_path.string()), + error)}; + } + return {}; #endif } @@ -1593,12 +1704,247 @@ struct CopyOptions { return result; #else - (void)src; - (void)dst; - (void)options; - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::reflink_copy_file: unsupported platform")}; + if (src.empty() || dst.empty() || !dst.has_filename()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::reflink_copy_file: invalid source or destination path")}; + } + const std::string dst_name = dst.filename().string(); + if (dst_name == "." || dst_name == "..") { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::reflink_copy_file: invalid destination filename")}; + } + + const HANDLE raw_src = ::CreateFileW( + src.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + if (raw_src == INVALID_HANDLE_VALUE) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format("FileSystem::reflink_copy_file: cannot open '{}'", + src.string()), + error)}; + } + detail::OwnedHandle src_handle{raw_src}; + + BY_HANDLE_FILE_INFORMATION src_info{}; + if (::GetFileInformationByHandle(src_handle.get(), &src_info) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format("FileSystem::reflink_copy_file: fstat failed on '{}'", + src.string()), + error)}; + } + if ((src_info.dwFileAttributes & + (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + std::format( + "FileSystem::reflink_copy_file: '{}' is not a regular file", + src.string()))}; + } + LARGE_INTEGER src_size{}; + if (::GetFileSizeEx(src_handle.get(), &src_size) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format("FileSystem::reflink_copy_file: size failed on '{}'", + src.string()), + error)}; + } + + const std::filesystem::path parent = + dst.parent_path().empty() ? std::filesystem::path{"."} + : dst.parent_path(); + + std::filesystem::path temp_path; + detail::OwnedHandle temp_handle; + DWORD last_error = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + temp_path = parent / std::format(".{}.void_cp_{:016x}", dst_name, + detail::next_temp_entropy()); + const HANDLE raw = ::CreateFileW( + temp_path.c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (raw != INVALID_HANDLE_VALUE) { + temp_handle.reset(raw); + break; + } + last_error = ::GetLastError(); + if (last_error != ERROR_FILE_EXISTS && + last_error != ERROR_ALREADY_EXISTS) { + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(last_error), + std::format( + "FileSystem::reflink_copy_file: create temp in '{}'", + parent.string()), + last_error)}; + } + } + if (!temp_handle.valid()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "FileSystem::reflink_copy_file: exhausted temp names")}; + } + + bool cleanup_temp = true; + struct TempGuard { + const std::filesystem::path* path{nullptr}; + bool* active{nullptr}; + ~TempGuard() noexcept + { + if (active != nullptr && *active && path != nullptr) { + (void)::DeleteFileW(path->c_str()); + } + } + } temp_guard{&temp_path, &cleanup_temp}; + + CopyResult result; + result.bytes = static_cast(src_size.QuadPart); + bool cloned = false; + + // Block cloning is available on ReFS and some SMB3 shares. The target + // must already be large enough for the cloned range. + if (src_size.QuadPart > 0) { + LARGE_INTEGER end{}; + end.QuadPart = src_size.QuadPart; + if (::SetFilePointerEx(temp_handle.get(), end, nullptr, FILE_BEGIN) != 0 && + ::SetEndOfFile(temp_handle.get()) != 0) { + DUPLICATE_EXTENTS_DATA extents{}; + extents.FileHandle = src_handle.get(); + extents.SourceFileOffset.QuadPart = 0; + extents.TargetFileOffset.QuadPart = 0; + extents.ByteCount.QuadPart = src_size.QuadPart; + DWORD returned = 0; + if (::DeviceIoControl(temp_handle.get(), + FSCTL_DUPLICATE_EXTENTS_TO_FILE, &extents, + sizeof(extents), nullptr, 0, &returned, + nullptr) != 0) { + cloned = true; + result.method = CopyMethod::Reflink; + } + } + } + + if (!cloned) { + result.method = CopyMethod::PrivateCopy; + LARGE_INTEGER zero{}; + zero.QuadPart = 0; + (void)::SetFilePointerEx(src_handle.get(), zero, nullptr, FILE_BEGIN); + (void)::SetFilePointerEx(temp_handle.get(), zero, nullptr, FILE_BEGIN); + std::vector buffer(64ULL * 1024ULL); + std::uint64_t copied = 0; + for (;;) { + DWORD got = 0; + if (::ReadFile(src_handle.get(), buffer.data(), + static_cast(buffer.size()), &got, + nullptr) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format( + "FileSystem::reflink_copy_file: read failed on '{}'", + src.string()), + error)}; + } + if (got == 0) { + break; + } + DWORD offset = 0; + while (offset < got) { + DWORD wrote = 0; + if (::WriteFile(temp_handle.get(), buffer.data() + offset, + got - offset, &wrote, nullptr) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format( + "FileSystem::reflink_copy_file: write failed for '{}'", + dst.string()), + error)}; + } + offset += wrote; + } + copied += got; + } + result.bytes = copied; + LARGE_INTEGER end{}; + end.QuadPart = static_cast(copied); + (void)::SetFilePointerEx(temp_handle.get(), end, nullptr, FILE_BEGIN); + (void)::SetEndOfFile(temp_handle.get()); + } + + if (options.preserve_permissions) { + (void)::SetFileAttributesW( + temp_path.c_str(), + src_info.dwFileAttributes & + ~(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)); + } + + if (options.durability == ReplaceDurability::durable_sync) { + if (::FlushFileBuffers(temp_handle.get()) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + Void::System::SystemErrorCode::sync_failed, + std::format( + "FileSystem::reflink_copy_file: fsync failed for '{}'", + dst.string()), + error)}; + } + } + + if (!temp_handle.close()) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format("FileSystem::reflink_copy_file: close failed for '{}'", + dst.string()), + error)}; + } + + DWORD move_flags = options.overwrite ? MOVEFILE_REPLACE_EXISTING : 0; + if (options.durability == ReplaceDurability::durable_sync) { + move_flags |= MOVEFILE_WRITE_THROUGH; + } + if (::MoveFileExW(temp_path.c_str(), dst.c_str(), move_flags) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format("FileSystem::reflink_copy_file: rename failed for '{}'", + dst.string()), + error)}; + } + cleanup_temp = false; + + if (options.durability == ReplaceDurability::durable_sync) { + const HANDLE dir_raw = ::CreateFileW( + parent.c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (dir_raw == INVALID_HANDLE_VALUE || + ::FlushFileBuffers(dir_raw) == 0) { + const DWORD error = + dir_raw == INVALID_HANDLE_VALUE ? ::GetLastError() + : ::GetLastError(); + if (dir_raw != INVALID_HANDLE_VALUE) { + (void)::CloseHandle(dir_raw); + } + return std::unexpected{detail::make_win32_error( + Void::System::SystemErrorCode::durability_unknown, + std::format( + "FileSystem::reflink_copy_file: parent fsync failed for '{}'", + dst.string()), + error)}; + } + (void)::CloseHandle(dir_raw); + } + + return result; #endif } @@ -1640,14 +1986,66 @@ struct CopyOptions { } return {}; #else - (void)path; - (void)atime_sec; - (void)atime_nsec; - (void)mtime_sec; - (void)mtime_nsec; - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::set_timestamps_nofollow: unsupported platform")}; + if (path.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::set_timestamps_nofollow: empty path")}; + } + // UTIME_NOW/UTIME_OMIT do not exist on Windows; only real values are + // supported. + if (atime_nsec < 0 || atime_nsec >= 1'000'000'000 || mtime_nsec < 0 || + mtime_nsec >= 1'000'000'000) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::set_timestamps_nofollow: nanoseconds out of range")}; + } + constexpr std::int64_t kFileTimeEpochOffset = 11'644'473'600LL; + if (atime_sec < -kFileTimeEpochOffset || + mtime_sec < -kFileTimeEpochOffset) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::set_timestamps_nofollow: timestamp out of range")}; + } + + const HANDLE raw = ::CreateFileW( + path.c_str(), FILE_WRITE_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + if (raw == INVALID_HANDLE_VALUE) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format( + "FileSystem::set_timestamps_nofollow: open failed for '{}'", + path.string()), + error)}; + } + detail::OwnedHandle handle{raw}; + const auto to_file_time = [](std::int64_t seconds, + std::int32_t nanoseconds) { + LARGE_INTEGER value{}; + value.QuadPart = (seconds + kFileTimeEpochOffset) * 10'000'000LL + + nanoseconds / 100; + FILETIME time{}; + time.dwLowDateTime = static_cast(value.QuadPart & 0xFFFFFFFFLL); + time.dwHighDateTime = + static_cast((value.QuadPart >> 32) & 0xFFFFFFFFLL); + return time; + }; + const FILETIME access_time = to_file_time(atime_sec, atime_nsec); + const FILETIME modify_time = to_file_time(mtime_sec, mtime_nsec); + if (::SetFileTime(handle.get(), nullptr, &access_time, &modify_time) == 0) { + const DWORD error = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(error), + std::format( + "FileSystem::set_timestamps_nofollow: SetFileTime failed for " + "'{}'", + path.string()), + error)}; + } + return {}; #endif } diff --git a/include/Void/System/Types.hpp b/include/Void/System/Types.hpp index 0f2505b..cef6fea 100644 --- a/include/Void/System/Types.hpp +++ b/include/Void/System/Types.hpp @@ -14,6 +14,8 @@ #ifndef _WIN32 #include +#else +#include #endif namespace Void::System @@ -180,7 +182,9 @@ public: (void)::close(old); } #else - (void)old; + if (old >= 0) { + (void)::_close(old); + } #endif } @@ -196,6 +200,12 @@ public: return std::unexpected{make_system_error( map_errno_to_system_code(err), "OwnedFd::close failed", err)}; } +#else + if (::_close(old) != 0) { + const int err = errno; + return std::unexpected{make_system_error( + map_errno_to_system_code(err), "OwnedFd::close failed", err)}; + } #endif return {}; } diff --git a/tests/standalone/System/Path.cpp b/tests/standalone/System/Path.cpp index bb52a65..f00702e 100644 --- a/tests/standalone/System/Path.cpp +++ b/tests/standalone/System/Path.cpp @@ -108,9 +108,6 @@ Void::Testing::Test remove_path_handles_missing_and_recursive() Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() { -#ifdef _WIN32 - Void::Testing::skip("POSIX-only filesystem semantics"); -#else Void::FileSystem::TempDir tmp{"void_fs_vl010_"}; // 1. RAII advisory FileLock (shared & exclusive, blocking & try_lock) @@ -148,16 +145,30 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() Void::Testing::require( Void::FileSystem::atomic_symlink_swap(link_path, "v1") .has_value()); +#ifdef _WIN32 + // MinGW's libstdc++ does not implement read_symlink; a symlink is a + // reparse point. + const DWORD attrs_v1 = ::GetFileAttributesW(link_path.c_str()); + Void::Testing::expect(attrs_v1 != INVALID_FILE_ATTRIBUTES && + (attrs_v1 & FILE_ATTRIBUTE_REPARSE_POINT) != 0); +#else Void::Testing::expect_eq( std::filesystem::read_symlink(link_path).string(), std::string{"v1"}); +#endif Void::Testing::require( Void::FileSystem::atomic_symlink_swap(link_path, "v2") .has_value()); +#ifdef _WIN32 + const DWORD attrs_v2 = ::GetFileAttributesW(link_path.c_str()); + Void::Testing::expect(attrs_v2 != INVALID_FILE_ATTRIBUTES && + (attrs_v2 & FILE_ATTRIBUTE_REPARSE_POINT) != 0); +#else Void::Testing::expect_eq( std::filesystem::read_symlink(link_path).string(), std::string{"v2"}); +#endif } // 3. reflink_copy_file isolates copied file (never hardlinked) @@ -174,6 +185,7 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() Void::Testing::expect_eq( Void::FileSystem::read_file(dst).value(), payload); +#ifndef _WIN32 struct stat st_src {}; struct stat st_dst {}; Void::Testing::require(::lstat(src.c_str(), &st_src) == 0); @@ -181,6 +193,7 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() Void::Testing::expect(st_src.st_ino != st_dst.st_ino); Void::Testing::expect_eq(st_src.st_nlink, nlink_t{1}); Void::Testing::expect_eq(st_dst.st_nlink, nlink_t{1}); +#endif // overwrite == false must fail cleanly when dst already exists Void::FileSystem::CopyOptions no_overwrite; @@ -214,6 +227,7 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() Void::FileSystem::set_canonical_mtime(link, kLinkMtime) .has_value()); +#ifndef _WIN32 struct stat st_target {}; struct stat st_link {}; Void::Testing::require(::lstat(target.c_str(), &st_target) == 0); @@ -222,8 +236,8 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() kTargetMtime); Void::Testing::expect_eq(static_cast(st_link.st_mtim.tv_sec), kLinkMtime); - } #endif + } } namespace