]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
chore: Improve util::FileLock
authorJoel Rosdahl <joel@rosdahl.net>
Sun, 5 Oct 2025 17:29:36 +0000 (19:29 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Sun, 5 Oct 2025 19:03:46 +0000 (21:03 +0200)
- 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
src/ccache/util/filelock.hpp

index 6c35b115f54717a864cc1fb62d3614552dd212b7..479195e020f486d3dedbd2c264cc71321ca58adf 100644 (file)
@@ -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<HANDLE>(_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<HANDLE>(_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;
index 6c1b9a2e8e64b4f7cf6c7f49e43552931063ceee..9be1e6999936ca18efdfd5c4eff1a4cd2650abef 100644 (file)
@@ -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;