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