From 0aa05d37ebcc6ac4919c9b2cdf96a09053dc4473 Mon Sep 17 00:00:00 2001 From: Joel Rosdahl Date: Sun, 5 Oct 2025 19:29:36 +0200 Subject: [PATCH] chore: Improve util::FileLock - Release current lock on move. - Check for invalid file descriptor in acquire/release. - Use UnlockFileEx on Windows for symmetry with LockFileEx. - Added noexcept where applicable. --- src/ccache/util/filelock.cpp | 14 ++++++++++---- src/ccache/util/filelock.hpp | 4 ++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/ccache/util/filelock.cpp b/src/ccache/util/filelock.cpp index 6c35b115..479195e0 100644 --- a/src/ccache/util/filelock.cpp +++ b/src/ccache/util/filelock.cpp @@ -49,6 +49,7 @@ FileLock& FileLock::operator=(FileLock&& other) noexcept { if (&other != this) { + release(); m_fd = other.m_fd; m_acquired = other.m_acquired; other.m_fd = -1; @@ -58,8 +59,12 @@ FileLock::operator=(FileLock&& other) noexcept } bool -FileLock::acquire() +FileLock::acquire() noexcept { + if (m_fd == -1) { + return false; + } + #ifdef _WIN32 HANDLE handle = reinterpret_cast(_get_osfhandle(m_fd)); if (handle == INVALID_HANDLE_VALUE) { @@ -85,16 +90,17 @@ FileLock::acquire() } void -FileLock::release() +FileLock::release() noexcept { - if (!acquired()) { + if (!acquired() || m_fd == -1) { return; } #ifdef _WIN32 HANDLE handle = reinterpret_cast(_get_osfhandle(m_fd)); if (handle != INVALID_HANDLE_VALUE) { - UnlockFile(handle, 0, 0, MAXDWORD, MAXDWORD); + OVERLAPPED overlapped{}; + UnlockFileEx(handle, 0, MAXDWORD, MAXDWORD, &overlapped); } #else struct flock lock; diff --git a/src/ccache/util/filelock.hpp b/src/ccache/util/filelock.hpp index 6c1b9a2e..9be1e699 100644 --- a/src/ccache/util/filelock.hpp +++ b/src/ccache/util/filelock.hpp @@ -34,10 +34,10 @@ public: ~FileLock(); // Acquire lock, blocking. Returns true if acquired, otherwise false. - [[nodiscard]] bool acquire(); + [[nodiscard]] bool acquire() noexcept; // Release lock early. If not previously acquired, nothing happens. - void release(); + void release() noexcept; // Return whether the lock is acquired successfully. bool acquired() const; -- 2.47.3