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