DirectoryWatcher-linux.cpp 12 KB

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