xref: /llvm-project/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp (revision d10f9863a5ac1cb681af07719650c44b48f289ce)
1 //===- DirectoryWatcher-linux.cpp - Linux-platform directory watching -----===//
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 "DirectoryScanner.h"
10 #include "clang/DirectoryWatcher/DirectoryWatcher.h"
11 
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/ScopeExit.h"
14 #include "llvm/Support/Errno.h"
15 #include "llvm/Support/Error.h"
16 #include "llvm/Support/Path.h"
17 #include <atomic>
18 #include <condition_variable>
19 #include <mutex>
20 #include <queue>
21 #include <string>
22 #include <thread>
23 #include <vector>
24 
25 #include <fcntl.h>
26 #include <sys/epoll.h>
27 #include <sys/inotify.h>
28 #include <unistd.h>
29 
30 namespace {
31 
32 using namespace llvm;
33 using namespace clang;
34 
35 /// Pipe for inter-thread synchronization - for epoll-ing on multiple
36 /// conditions. It is meant for uni-directional 1:1 signalling - specifically:
37 /// no multiple consumers, no data passing. Thread waiting for signal should
38 /// poll the FDRead. Signalling thread should call signal() which writes single
39 /// character to FDRead.
40 struct SemaphorePipe {
41   // Expects two file-descriptors opened as a pipe in the canonical POSIX
42   // order: pipefd[0] refers to the read end of the pipe. pipefd[1] refers to
43   // the write end of the pipe.
44   SemaphorePipe(int pipefd[2])
45       : FDRead(pipefd[0]), FDWrite(pipefd[1]), OwnsFDs(true) {}
46   SemaphorePipe(const SemaphorePipe &) = delete;
47   void operator=(const SemaphorePipe &) = delete;
48   SemaphorePipe(SemaphorePipe &&other)
49       : FDRead(other.FDRead), FDWrite(other.FDWrite),
50         OwnsFDs(other.OwnsFDs) // Someone could have moved from the other
51                                // instance before.
52   {
53     other.OwnsFDs = false;
54   };
55 
56   void signal() {
57 #ifndef NDEBUG
58     ssize_t Result =
59 #endif
60     llvm::sys::RetryAfterSignal(-1, write, FDWrite, "A", 1);
61     assert(Result != -1);
62   }
63   ~SemaphorePipe() {
64     if (OwnsFDs) {
65       close(FDWrite);
66       close(FDRead);
67     }
68   }
69   const int FDRead;
70   const int FDWrite;
71   bool OwnsFDs;
72 
73   static llvm::Optional<SemaphorePipe> create() {
74     int InotifyPollingStopperFDs[2];
75     if (pipe2(InotifyPollingStopperFDs, O_CLOEXEC) == -1)
76       return llvm::None;
77     return SemaphorePipe(InotifyPollingStopperFDs);
78   }
79 };
80 
81 /// Mutex-protected queue of Events.
82 class EventQueue {
83   std::mutex Mtx;
84   std::condition_variable NonEmpty;
85   std::queue<DirectoryWatcher::Event> Events;
86 
87 public:
88   void push_back(const DirectoryWatcher::Event::EventKind K,
89                  StringRef Filename) {
90     {
91       std::unique_lock<std::mutex> L(Mtx);
92       Events.emplace(K, Filename);
93     }
94     NonEmpty.notify_one();
95   }
96 
97   // Blocks on caller thread and uses codition_variable to wait until there's an
98   // event to return.
99   DirectoryWatcher::Event pop_front_blocking() {
100     std::unique_lock<std::mutex> L(Mtx);
101     while (true) {
102       // Since we might have missed all the prior notifications on NonEmpty we
103       // have to check the queue first (under lock).
104       if (!Events.empty()) {
105         DirectoryWatcher::Event Front = Events.front();
106         Events.pop();
107         return Front;
108       }
109       NonEmpty.wait(L, [this]() { return !Events.empty(); });
110     }
111   }
112 };
113 
114 class DirectoryWatcherLinux : public clang::DirectoryWatcher {
115 public:
116   DirectoryWatcherLinux(
117       llvm::StringRef WatchedDirPath,
118       std::function<void(llvm::ArrayRef<Event>, bool)> Receiver,
119       bool WaitForInitialSync, int InotifyFD, int InotifyWD,
120       SemaphorePipe &&InotifyPollingStopSignal);
121 
122   ~DirectoryWatcherLinux() override {
123     StopWork();
124     InotifyPollingThread.join();
125     EventsReceivingThread.join();
126     inotify_rm_watch(InotifyFD, InotifyWD);
127     llvm::sys::RetryAfterSignal(-1, close, InotifyFD);
128   }
129 
130 private:
131   const std::string WatchedDirPath;
132   // inotify file descriptor
133   int InotifyFD = -1;
134   // inotify watch descriptor
135   int InotifyWD = -1;
136 
137   EventQueue Queue;
138 
139   // Make sure lifetime of Receiver fully contains lifetime of
140   // EventsReceivingThread.
141   std::function<void(llvm::ArrayRef<Event>, bool)> Receiver;
142 
143   // Consumes inotify events and pushes directory watcher events to the Queue.
144   void InotifyPollingLoop();
145   std::thread InotifyPollingThread;
146   // Using pipe so we can epoll two file descriptors at once - inotify and
147   // stopping condition.
148   SemaphorePipe InotifyPollingStopSignal;
149 
150   // Does the initial scan of the directory - directly calling Receiver,
151   // bypassing the Queue. Both InitialScan and EventReceivingLoop use Receiver
152   // which isn't necessarily thread-safe.
153   void InitialScan();
154 
155   // Processing events from the Queue.
156   // In case client doesn't want to do the initial scan synchronously
157   // (WaitForInitialSync=false in ctor) we do the initial scan at the beginning
158   // of this thread.
159   std::thread EventsReceivingThread;
160   // Push event of WatcherGotInvalidated kind to the Queue to stop the loop.
161   // Both InitialScan and EventReceivingLoop use Receiver which isn't
162   // necessarily thread-safe.
163   void EventReceivingLoop();
164 
165   // Stops all the async work. Reentrant.
166   void StopWork() {
167     Queue.push_back(DirectoryWatcher::Event::EventKind::WatcherGotInvalidated,
168                     "");
169     InotifyPollingStopSignal.signal();
170   }
171 };
172 
173 void DirectoryWatcherLinux::InotifyPollingLoop() {
174   // We want to be able to read ~30 events at once even in the worst case
175   // (obscenely long filenames).
176   constexpr size_t EventBufferLength =
177       30 * (sizeof(struct inotify_event) + NAME_MAX + 1);
178   // http://man7.org/linux/man-pages/man7/inotify.7.html
179   // Some systems cannot read integer variables if they are not
180   // properly aligned. On other systems, incorrect alignment may
181   // decrease performance. Hence, the buffer used for reading from
182   // the inotify file descriptor should have the same alignment as
183   // struct inotify_event.
184 
185   struct Buffer {
186     alignas(struct inotify_event) char buffer[EventBufferLength];
187   };
188   auto ManagedBuffer = std::make_unique<Buffer>();
189   char *const Buf = ManagedBuffer->buffer;
190 
191   const int EpollFD = epoll_create1(EPOLL_CLOEXEC);
192   if (EpollFD == -1) {
193     StopWork();
194     return;
195   }
196   auto EpollFDGuard = llvm::make_scope_exit([EpollFD]() { close(EpollFD); });
197 
198   struct epoll_event EventSpec;
199   EventSpec.events = EPOLLIN;
200   EventSpec.data.fd = InotifyFD;
201   if (epoll_ctl(EpollFD, EPOLL_CTL_ADD, InotifyFD, &EventSpec) == -1) {
202     StopWork();
203     return;
204   }
205 
206   EventSpec.data.fd = InotifyPollingStopSignal.FDRead;
207   if (epoll_ctl(EpollFD, EPOLL_CTL_ADD, InotifyPollingStopSignal.FDRead,
208                 &EventSpec) == -1) {
209     StopWork();
210     return;
211   }
212 
213   std::array<struct epoll_event, 2> EpollEventBuffer;
214 
215   while (true) {
216     const int EpollWaitResult = llvm::sys::RetryAfterSignal(
217         -1, epoll_wait, EpollFD, EpollEventBuffer.data(),
218         EpollEventBuffer.size(), /*timeout=*/-1 /*== infinity*/);
219     if (EpollWaitResult == -1) {
220       StopWork();
221       return;
222     }
223 
224     // Multiple epoll_events can be received for a single file descriptor per
225     // epoll_wait call.
226     for (int i = 0; i < EpollWaitResult; ++i) {
227       if (EpollEventBuffer[i].data.fd == InotifyPollingStopSignal.FDRead) {
228         StopWork();
229         return;
230       }
231     }
232 
233     // epoll_wait() always return either error or >0 events. Since there was no
234     // event for stopping, it must be an inotify event ready for reading.
235     ssize_t NumRead = llvm::sys::RetryAfterSignal(-1, read, InotifyFD, Buf,
236                                                   EventBufferLength);
237     for (char *P = Buf; P < Buf + NumRead;) {
238       if (P + sizeof(struct inotify_event) > Buf + NumRead) {
239         StopWork();
240         llvm_unreachable("an incomplete inotify_event was read");
241         return;
242       }
243 
244       struct inotify_event *Event = reinterpret_cast<struct inotify_event *>(P);
245       P += sizeof(struct inotify_event) + Event->len;
246 
247       if (Event->mask & (IN_CREATE | IN_MODIFY | IN_MOVED_TO | IN_DELETE) &&
248           Event->len <= 0) {
249         StopWork();
250         llvm_unreachable("expected a filename from inotify");
251         return;
252       }
253 
254       if (Event->mask & (IN_CREATE | IN_MOVED_TO | IN_MODIFY)) {
255         Queue.push_back(DirectoryWatcher::Event::EventKind::Modified,
256                         Event->name);
257       } else if (Event->mask & (IN_DELETE | IN_MOVED_FROM)) {
258         Queue.push_back(DirectoryWatcher::Event::EventKind::Removed,
259                         Event->name);
260       } else if (Event->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) {
261         Queue.push_back(DirectoryWatcher::Event::EventKind::WatchedDirRemoved,
262                         "");
263         StopWork();
264         return;
265       } else if (Event->mask & IN_IGNORED) {
266         StopWork();
267         return;
268       } else {
269         StopWork();
270         llvm_unreachable("Unknown event type.");
271         return;
272       }
273     }
274   }
275 }
276 
277 void DirectoryWatcherLinux::InitialScan() {
278   this->Receiver(getAsFileEvents(scanDirectory(WatchedDirPath)),
279                  /*IsInitial=*/true);
280 }
281 
282 void DirectoryWatcherLinux::EventReceivingLoop() {
283   while (true) {
284     DirectoryWatcher::Event Event = this->Queue.pop_front_blocking();
285     this->Receiver(Event, false);
286     if (Event.Kind ==
287         DirectoryWatcher::Event::EventKind::WatcherGotInvalidated) {
288       StopWork();
289       return;
290     }
291   }
292 }
293 
294 DirectoryWatcherLinux::DirectoryWatcherLinux(
295     StringRef WatchedDirPath,
296     std::function<void(llvm::ArrayRef<Event>, bool)> Receiver,
297     bool WaitForInitialSync, int InotifyFD, int InotifyWD,
298     SemaphorePipe &&InotifyPollingStopSignal)
299     : WatchedDirPath(WatchedDirPath), InotifyFD(InotifyFD),
300       InotifyWD(InotifyWD), Receiver(Receiver),
301       InotifyPollingStopSignal(std::move(InotifyPollingStopSignal)) {
302 
303   InotifyPollingThread = std::thread([this]() { InotifyPollingLoop(); });
304   // We have no guarantees about thread safety of the Receiver which is being
305   // used in both InitialScan and EventReceivingLoop. We shouldn't run these
306   // only synchronously.
307   if (WaitForInitialSync) {
308     InitialScan();
309     EventsReceivingThread = std::thread([this]() { EventReceivingLoop(); });
310   } else {
311     EventsReceivingThread = std::thread([this]() {
312       // FIXME: We might want to terminate an async initial scan early in case
313       // of a failure in EventsReceivingThread.
314       InitialScan();
315       EventReceivingLoop();
316     });
317   }
318 }
319 
320 } // namespace
321 
322 llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::create(
323     StringRef Path,
324     std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,
325     bool WaitForInitialSync) {
326   if (Path.empty())
327     llvm::report_fatal_error(
328         "DirectoryWatcher::create can not accept an empty Path.");
329 
330   const int InotifyFD = inotify_init1(IN_CLOEXEC);
331   if (InotifyFD == -1)
332     return llvm::make_error<llvm::StringError>(
333         std::string("inotify_init1() error: ") + strerror(errno),
334         llvm::inconvertibleErrorCode());
335 
336   const int InotifyWD = inotify_add_watch(
337       InotifyFD, Path.str().c_str(),
338       IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY |
339       IN_MOVED_FROM | IN_MOVE_SELF | IN_MOVED_TO | IN_ONLYDIR | IN_IGNORED
340 #ifdef IN_EXCL_UNLINK
341       | IN_EXCL_UNLINK
342 #endif
343       );
344   if (InotifyWD == -1)
345     return llvm::make_error<llvm::StringError>(
346         std::string("inotify_add_watch() error: ") + strerror(errno),
347         llvm::inconvertibleErrorCode());
348 
349   auto InotifyPollingStopper = SemaphorePipe::create();
350 
351   if (!InotifyPollingStopper)
352     return llvm::make_error<llvm::StringError>(
353         std::string("SemaphorePipe::create() error: ") + strerror(errno),
354         llvm::inconvertibleErrorCode());
355 
356   return std::make_unique<DirectoryWatcherLinux>(
357       Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD,
358       std::move(*InotifyPollingStopper));
359 }
360