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