DirectoryWatcher-linux.cpp 11 KB

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