1 //===-- LockFileBase.cpp ----------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Host/LockFileBase.h" 10 11 using namespace lldb; 12 using namespace lldb_private; 13 14 namespace { 15 16 Status AlreadyLocked() { return Status("Already locked"); } 17 18 Status NotLocked() { return Status("Not locked"); } 19 } 20 21 LockFileBase::LockFileBase(int fd) 22 : m_fd(fd), m_locked(false), m_start(0), m_len(0) {} 23 24 bool LockFileBase::IsLocked() const { return m_locked; } 25 26 Status LockFileBase::WriteLock(const uint64_t start, const uint64_t len) { 27 return DoLock([&](const uint64_t start, 28 const uint64_t len) { return DoWriteLock(start, len); }, 29 start, len); 30 } 31 32 Status LockFileBase::TryWriteLock(const uint64_t start, const uint64_t len) { 33 return DoLock([&](const uint64_t start, 34 const uint64_t len) { return DoTryWriteLock(start, len); }, 35 start, len); 36 } 37 38 Status LockFileBase::ReadLock(const uint64_t start, const uint64_t len) { 39 return DoLock([&](const uint64_t start, 40 const uint64_t len) { return DoReadLock(start, len); }, 41 start, len); 42 } 43 44 Status LockFileBase::TryReadLock(const uint64_t start, const uint64_t len) { 45 return DoLock([&](const uint64_t start, 46 const uint64_t len) { return DoTryReadLock(start, len); }, 47 start, len); 48 } 49 50 Status LockFileBase::Unlock() { 51 if (!IsLocked()) 52 return NotLocked(); 53 54 const auto error = DoUnlock(); 55 if (error.Success()) { 56 m_locked = false; 57 m_start = 0; 58 m_len = 0; 59 } 60 return error; 61 } 62 63 bool LockFileBase::IsValidFile() const { return m_fd != -1; } 64 65 Status LockFileBase::DoLock(const Locker &locker, const uint64_t start, 66 const uint64_t len) { 67 if (!IsValidFile()) 68 return Status("File is invalid"); 69 70 if (IsLocked()) 71 return AlreadyLocked(); 72 73 const auto error = locker(start, len); 74 if (error.Success()) { 75 m_locked = true; 76 m_start = start; 77 m_len = len; 78 } 79 80 return error; 81 } 82