Modernize doc comments for SourceMgr.
[oota-llvm.git] / lib / Support / LockFileManager.cpp
1 //===--- LockFileManager.cpp - File-level Locking Utility------------------===//
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 #include "llvm/Support/LockFileManager.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/Support/Errc.h"
13 #include "llvm/Support/FileSystem.h"
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include <sys/stat.h>
18 #include <sys/types.h>
19 #if LLVM_ON_WIN32
20 #include <windows.h>
21 #endif
22 #if LLVM_ON_UNIX
23 #include <unistd.h>
24 #endif
25 using namespace llvm;
26
27 /// \brief Attempt to read the lock file with the given name, if it exists.
28 ///
29 /// \param LockFileName The name of the lock file to read.
30 ///
31 /// \returns The process ID of the process that owns this lock file
32 Optional<std::pair<std::string, int> >
33 LockFileManager::readLockFile(StringRef LockFileName) {
34   // Read the owning host and PID out of the lock file. If it appears that the
35   // owning process is dead, the lock file is invalid.
36   std::unique_ptr<MemoryBuffer> MB;
37   if (MemoryBuffer::getFile(LockFileName, MB)) {
38     sys::fs::remove(LockFileName);
39     return None;
40   }
41
42   StringRef Hostname;
43   StringRef PIDStr;
44   std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
45   PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
46   int PID;
47   if (!PIDStr.getAsInteger(10, PID)) {
48     auto Owner = std::make_pair(std::string(Hostname), PID);
49     if (processStillExecuting(Owner.first, Owner.second))
50       return Owner;
51   }
52
53   // Delete the lock file. It's invalid anyway.
54   sys::fs::remove(LockFileName);
55   return None;
56 }
57
58 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
59 #if LLVM_ON_UNIX && !defined(__ANDROID__)
60   char MyHostname[256];
61   MyHostname[255] = 0;
62   MyHostname[0] = 0;
63   gethostname(MyHostname, 255);
64   // Check whether the process is dead. If so, we're done.
65   if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
66     return false;
67 #endif
68
69   return true;
70 }
71
72 LockFileManager::LockFileManager(StringRef FileName)
73 {
74   this->FileName = FileName;
75   if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
76     Error = EC;
77     return;
78   }
79   LockFileName = this->FileName;
80   LockFileName += ".lock";
81
82   // If the lock file already exists, don't bother to try to create our own
83   // lock file; it won't work anyway. Just figure out who owns this lock file.
84   if ((Owner = readLockFile(LockFileName)))
85     return;
86
87   // Create a lock file that is unique to this instance.
88   UniqueLockFileName = LockFileName;
89   UniqueLockFileName += "-%%%%%%%%";
90   int UniqueLockFileID;
91   if (std::error_code EC = sys::fs::createUniqueFile(
92           UniqueLockFileName.str(), UniqueLockFileID, UniqueLockFileName)) {
93     Error = EC;
94     return;
95   }
96
97   // Write our process ID to our unique lock file.
98   {
99     raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
100
101 #if LLVM_ON_UNIX
102     // FIXME: move getpid() call into LLVM
103     char hostname[256];
104     hostname[255] = 0;
105     hostname[0] = 0;
106     gethostname(hostname, 255);
107     Out << hostname << ' ' << getpid();
108 #else
109     Out << "localhost 1";
110 #endif
111     Out.close();
112
113     if (Out.has_error()) {
114       // We failed to write out PID, so make up an excuse, remove the
115       // unique lock file, and fail.
116       Error = make_error_code(errc::no_space_on_device);
117       sys::fs::remove(UniqueLockFileName.c_str());
118       return;
119     }
120   }
121
122   while (1) {
123     // Create a link from the lock file name. If this succeeds, we're done.
124     std::error_code EC =
125         sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
126     if (!EC)
127       return;
128
129     if (EC != errc::file_exists) {
130       Error = EC;
131       return;
132     }
133
134     // Someone else managed to create the lock file first. Read the process ID
135     // from the lock file.
136     if ((Owner = readLockFile(LockFileName))) {
137       // Wipe out our unique lock file (it's useless now)
138       sys::fs::remove(UniqueLockFileName.str());
139       return;
140     }
141
142     if (!sys::fs::exists(LockFileName.str())) {
143       // The previous owner released the lock file before we could read it.
144       // Try to get ownership again.
145       continue;
146     }
147
148     // There is a lock file that nobody owns; try to clean it up and get
149     // ownership.
150     if ((EC = sys::fs::remove(LockFileName.str()))) {
151       Error = EC;
152       return;
153     }
154   }
155 }
156
157 LockFileManager::LockFileState LockFileManager::getState() const {
158   if (Owner)
159     return LFS_Shared;
160
161   if (Error)
162     return LFS_Error;
163
164   return LFS_Owned;
165 }
166
167 LockFileManager::~LockFileManager() {
168   if (getState() != LFS_Owned)
169     return;
170
171   // Since we own the lock, remove the lock file and our own unique lock file.
172   sys::fs::remove(LockFileName.str());
173   sys::fs::remove(UniqueLockFileName.str());
174 }
175
176 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
177   if (getState() != LFS_Shared)
178     return Res_Success;
179
180 #if LLVM_ON_WIN32
181   unsigned long Interval = 1;
182 #else
183   struct timespec Interval;
184   Interval.tv_sec = 0;
185   Interval.tv_nsec = 1000000;
186 #endif
187   // Don't wait more than five minutes for the file to appear.
188   unsigned MaxSeconds = 300;
189   bool LockFileGone = false;
190   do {
191     // Sleep for the designated interval, to allow the owning process time to
192     // finish up and remove the lock file.
193     // FIXME: Should we hook in to system APIs to get a notification when the
194     // lock file is deleted?
195 #if LLVM_ON_WIN32
196     Sleep(Interval);
197 #else
198     nanosleep(&Interval, nullptr);
199 #endif
200     bool LockFileJustDisappeared = false;
201
202     // If the lock file is still expected to be there, check whether it still
203     // is.
204     if (!LockFileGone) {
205       bool Exists;
206       if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
207         LockFileGone = true;
208         LockFileJustDisappeared = true;
209       }
210     }
211
212     // If the lock file is no longer there, check if the original file is
213     // available now.
214     if (LockFileGone) {
215       if (sys::fs::exists(FileName.str())) {
216         return Res_Success;
217       }
218
219       // The lock file is gone, so now we're waiting for the original file to
220       // show up. If this just happened, reset our waiting intervals and keep
221       // waiting.
222       if (LockFileJustDisappeared) {
223         MaxSeconds = 5;
224
225 #if LLVM_ON_WIN32
226         Interval = 1;
227 #else
228         Interval.tv_sec = 0;
229         Interval.tv_nsec = 1000000;
230 #endif
231         continue;
232       }
233     }
234
235     // If we're looking for the lock file to disappear, but the process
236     // owning the lock died without cleaning up, just bail out.
237     if (!LockFileGone &&
238         !processStillExecuting((*Owner).first, (*Owner).second)) {
239       return Res_OwnerDied;
240     }
241
242     // Exponentially increase the time we wait for the lock to be removed.
243 #if LLVM_ON_WIN32
244     Interval *= 2;
245 #else
246     Interval.tv_sec *= 2;
247     Interval.tv_nsec *= 2;
248     if (Interval.tv_nsec >= 1000000000) {
249       ++Interval.tv_sec;
250       Interval.tv_nsec -= 1000000000;
251     }
252 #endif
253   } while (
254 #if LLVM_ON_WIN32
255            Interval < MaxSeconds * 1000
256 #else
257            Interval.tv_sec < (time_t)MaxSeconds
258 #endif
259            );
260
261   // Give up.
262   return Res_Timeout;
263 }