9#include "DirectoryScanner.h"
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/Error.h"
17#include "llvm/Support/Path.h"
19#include <condition_variable>
30#include <sys/inotify.h>
47 SemaphorePipe(
int pipefd[2])
48 : FDRead(pipefd[0]), FDWrite(pipefd[1]), OwnsFDs(
true) {}
49 SemaphorePipe(
const SemaphorePipe &) =
delete;
50 void operator=(
const SemaphorePipe &) =
delete;
51 SemaphorePipe(SemaphorePipe &&other)
52 : FDRead(other.FDRead), FDWrite(other.FDWrite),
53 OwnsFDs(other.OwnsFDs)
56 other.OwnsFDs =
false;
63 llvm::sys::RetryAfterSignal(-1, write, FDWrite,
"A", 1);
76 static std::optional<SemaphorePipe>
create() {
77 int InotifyPollingStopperFDs[2];
78 if (pipe2(InotifyPollingStopperFDs, O_CLOEXEC) == -1)
80 return SemaphorePipe(InotifyPollingStopperFDs);
87 std::condition_variable NonEmpty;
88 std::queue<DirectoryWatcher::Event> Events;
94 std::unique_lock<std::mutex> L(Mtx);
97 NonEmpty.notify_one();
103 std::unique_lock<std::mutex> L(Mtx);
107 if (!Events.empty()) {
112 NonEmpty.wait(L, [
this]() {
return !Events.empty(); });
119 DirectoryWatcherLinux(
120 llvm::StringRef WatchedDirPath,
122 bool WaitForInitialSync,
int InotifyFD,
int InotifyWD,
123 SemaphorePipe &&InotifyPollingStopSignal);
125 ~DirectoryWatcherLinux()
override {
127 InotifyPollingThread.join();
128 EventsReceivingThread.join();
129 inotify_rm_watch(InotifyFD, InotifyWD);
130 llvm::sys::RetryAfterSignal(-1, close, InotifyFD);
134 const std::string WatchedDirPath;
147 void InotifyPollingLoop();
148 std::thread InotifyPollingThread;
151 SemaphorePipe InotifyPollingStopSignal;
162 std::thread EventsReceivingThread;
166 void EventReceivingLoop();
170 Queue.push_back(DirectoryWatcher::Event::EventKind::WatcherGotInvalidated,
172 InotifyPollingStopSignal.signal();
176void DirectoryWatcherLinux::InotifyPollingLoop() {
179 constexpr size_t EventBufferLength =
180 30 * (
sizeof(
struct inotify_event) + NAME_MAX + 1);
189 alignas(
struct inotify_event) char buffer[EventBufferLength];
191 auto ManagedBuffer = std::make_unique<Buffer>();
192 char *
const Buf = ManagedBuffer->buffer;
194 const int EpollFD = epoll_create1(EPOLL_CLOEXEC);
199 auto EpollFDGuard = llvm::make_scope_exit([EpollFD]() { close(EpollFD); });
201 struct epoll_event EventSpec;
202 EventSpec.events = EPOLLIN;
203 EventSpec.data.fd = InotifyFD;
204 if (epoll_ctl(EpollFD, EPOLL_CTL_ADD, InotifyFD, &EventSpec) == -1) {
209 EventSpec.data.fd = InotifyPollingStopSignal.FDRead;
210 if (epoll_ctl(EpollFD, EPOLL_CTL_ADD, InotifyPollingStopSignal.FDRead,
216 std::array<struct epoll_event, 2> EpollEventBuffer;
219 const int EpollWaitResult = llvm::sys::RetryAfterSignal(
220 -1, epoll_wait, EpollFD, EpollEventBuffer.data(),
221 EpollEventBuffer.size(), -1 );
222 if (EpollWaitResult == -1) {
229 for (
int i = 0; i < EpollWaitResult; ++i) {
230 if (EpollEventBuffer[i].data.fd == InotifyPollingStopSignal.FDRead) {
238 ssize_t NumRead = llvm::sys::RetryAfterSignal(-1, read, InotifyFD, Buf,
240 for (
char *
P = Buf;
P < Buf + NumRead;) {
241 if (
P +
sizeof(
struct inotify_event) > Buf + NumRead) {
243 llvm_unreachable(
"an incomplete inotify_event was read");
247 struct inotify_event *Event =
reinterpret_cast<struct inotify_event *
>(
P);
248 P +=
sizeof(
struct inotify_event) + Event->len;
250 if (Event->mask & (IN_CREATE | IN_MODIFY | IN_MOVED_TO | IN_DELETE) &&
253 llvm_unreachable(
"expected a filename from inotify");
257 if (Event->mask & (IN_CREATE | IN_MOVED_TO | IN_MODIFY)) {
258 Queue.push_back(DirectoryWatcher::Event::EventKind::Modified,
260 }
else if (Event->mask & (IN_DELETE | IN_MOVED_FROM)) {
261 Queue.push_back(DirectoryWatcher::Event::EventKind::Removed,
263 }
else if (Event->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) {
264 Queue.push_back(DirectoryWatcher::Event::EventKind::WatchedDirRemoved,
268 }
else if (Event->mask & IN_IGNORED) {
273 llvm_unreachable(
"Unknown event type.");
280void DirectoryWatcherLinux::InitialScan() {
285void DirectoryWatcherLinux::EventReceivingLoop() {
288 this->Receiver(Event,
false);
290 DirectoryWatcher::Event::EventKind::WatcherGotInvalidated) {
297DirectoryWatcherLinux::DirectoryWatcherLinux(
298 StringRef WatchedDirPath,
300 bool WaitForInitialSync,
int InotifyFD,
int InotifyWD,
301 SemaphorePipe &&InotifyPollingStopSignal)
302 : WatchedDirPath(WatchedDirPath), InotifyFD(InotifyFD),
303 InotifyWD(InotifyWD), Receiver(Receiver),
304 InotifyPollingStopSignal(
std::move(InotifyPollingStopSignal)) {
306 InotifyPollingThread = std::thread([
this]() { InotifyPollingLoop(); });
310 if (WaitForInitialSync) {
312 EventsReceivingThread = std::thread([
this]() { EventReceivingLoop(); });
314 EventsReceivingThread = std::thread([
this]() {
318 EventReceivingLoop();
328 bool WaitForInitialSync) {
330 llvm::report_fatal_error(
331 "DirectoryWatcher::create can not accept an empty Path.");
333 const int InotifyFD = inotify_init1(IN_CLOEXEC);
335 return llvm::make_error<llvm::StringError>(
336 llvm::errnoAsErrorCode(), std::string(
": inotify_init1()"));
338 const int InotifyWD = inotify_add_watch(
339 InotifyFD,
Path.str().c_str(),
340 IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY |
341 IN_MOVED_FROM | IN_MOVE_SELF | IN_MOVED_TO | IN_ONLYDIR | IN_IGNORED
347 return llvm::make_error<llvm::StringError>(
348 llvm::errnoAsErrorCode(), std::string(
": inotify_add_watch()"));
350 auto InotifyPollingStopper = SemaphorePipe::create();
352 if (!InotifyPollingStopper)
353 return llvm::make_error<llvm::StringError>(
354 llvm::errnoAsErrorCode(), std::string(
": SemaphorePipe::create()"));
356 return std::make_unique<DirectoryWatcherLinux>(
357 Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD,
358 std::move(*InotifyPollingStopper));
Provides notifications for file changes in a directory.
static llvm::Expected< std::unique_ptr< DirectoryWatcher > > create(llvm::StringRef Path, std::function< void(llvm::ArrayRef< DirectoryWatcher::Event > Events, bool IsInitial)> Receiver, bool WaitForInitialSync)
llvm fatal_error if
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
The JSON file list parser is used to communicate input to InstallAPI.
std::vector< std::string > scanDirectory(StringRef Path)
std::vector< DirectoryWatcher::Event > getAsFileEvents(const std::vector< std::string > &Scan)
Create event with EventKind::Added for every element in Scan.
Diagnostic wrappers for TextAPI types for error reporting.