Debian Codegraph @

node/@parcel/watcher/src/kqueue/KqueueBackend.cc

raw
1 #include <memory>
2 #include <poll.h>
3 #include <unistd.h>
4 #include <libgen.h>
5 #include <dirent.h>
6 #include <fcntl.h>
7 #include <sys/stat.h>
8 #include "KqueueBackend.hh"
9
10 #if __APPLE__
11 #define st_mtim st_mtimespec
12 #endif
13
14 #if !defined(O_EVTONLY)
15 #define O_EVTONLY O_RDONLY
16 #endif
17
18 #define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
19
20 void KqueueBackend::start() {
21 if ((mKqueue = kqueue()) < 0) {
22 throw std::runtime_error(std::string("Unable to open kqueue: ") + strerror(errno));
23 }
24
25 // Create a pipe that we will write to when we want to end the thread.
26 int err = pipe(mPipe);
27 if (err == -1) {
28 throw std::runtime_error(std::string("Unable to open pipe: ") + strerror(errno));
29 }
30
31 // Subscribe kqueue to this pipe.
32 struct kevent ev;
33 EV_SET(
34 &ev,
35 mPipe[0],
36 EVFILT_READ,
37 EV_ADD | EV_CLEAR,
38 0,
39 0,
40 0
41 );
42
43 if (kevent(mKqueue, &ev, 1, NULL, 0, 0)) {
44 close(mPipe[0]);
45 close(mPipe[1]);
46 throw std::runtime_error(std::string("Unable to watch pipe: ") + strerror(errno));
47 }
48
49 notifyStarted();
50
51 struct kevent events[128];
52
53 while (true) {
54 int event_count = kevent(mKqueue, NULL, 0, events, 128, 0);
55 if (event_count < 0 || events[0].flags == EV_ERROR) {
56 throw std::runtime_error(std::string("kevent error: ") + strerror(errno));
57 }
58
59 // Track all of the watchers that are touched so we can notify them at the end of the events.
60 std::unordered_set<WatcherRef> watchers;
61
62 for (int i = 0; i < event_count; i++) {
63 int flags = events[i].fflags;
64 int fd = events[i].ident;
65 if (fd == mPipe[0]) {
66 // pipe was written to. break out of the loop.
67 goto done;
68 }
69
70 auto it = mFdToEntry.find(fd);
71 if (it == mFdToEntry.end()) {
72 // If fd wasn't in our map, we may have already stopped watching it. Ignore the event.
73 continue;
74 }
75
76 DirEntry *entry = it->second;
77
78 if (flags & NOTE_WRITE && entry && entry->isDir) {
79 // If a write occurred on a directory, we have to diff the contents of that
80 // directory to determine what file was added/deleted.
81 compareDir(fd, entry->path, watchers);
82 } else {
83 std::vector<KqueueSubscription *> subs = findSubscriptions(entry->path);
84 for (auto it = subs.begin(); it != subs.end(); it++) {
85 KqueueSubscription *sub = *it;
86 watchers.insert(sub->watcher);
87 if (flags & (NOTE_DELETE | NOTE_RENAME | NOTE_REVOKE)) {
88 sub->watcher->mEvents.remove(sub->path);
89 sub->tree->remove(sub->path);
90 mFdToEntry.erase((int)(size_t)entry->state);
91 mSubscriptions.erase(sub->path);
92 } else if (flags & (NOTE_WRITE | NOTE_ATTRIB | NOTE_EXTEND)) {
93 struct stat st;
94 lstat(sub->path.c_str(), &st);
95 if (entry->mtime != CONVERT_TIME(st.st_mtim)) {
96 entry->mtime = CONVERT_TIME(st.st_mtim);
97 sub->watcher->mEvents.update(sub->path);
98 }
99 }
100 }
101 }
102 }
103
104 for (auto it = watchers.begin(); it != watchers.end(); it++) {
105 (*it)->notify();
106 }
107 }
108
109 done:
110 close(mPipe[0]);
111 close(mPipe[1]);
112 mEndedSignal.notify();
113 }
114
115 KqueueBackend::~KqueueBackend() {
116 write(mPipe[1], "X", 1);
117 mEndedSignal.wait();
118 }
119
120 void KqueueBackend::subscribe(WatcherRef watcher) {
121 // Build a full directory tree recursively, and watch each directory.
122 std::shared_ptr<DirTree> tree = getTree(watcher);
123
124 for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) {
125 bool success = watchDir(watcher, it->second.path, tree);
126 if (!success) {
127 throw WatcherError(std::string("error watching " + watcher->mDir + ": " + strerror(errno)), watcher);
128 }
129 }
130 }
131
132 bool KqueueBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree) {
133 if (watcher->isIgnored(path)) {
134 return false;
135 }
136
137 DirEntry *entry = tree->find(path);
138 if (!entry) {
139 return false;
140 }
141
142 KqueueSubscription sub = {
143 .watcher = watcher,
144 .path = path,
145 .tree = tree
146 };
147
148 if (!entry->state) {
149 int fd = open(path.c_str(), O_EVTONLY);
150 if (fd <= 0) {
151 return false;
152 }
153
154 struct kevent event;
155 EV_SET(
156 &event,
157 fd,
158 EVFILT_VNODE,
159 EV_ADD | EV_CLEAR | EV_ENABLE,
160 NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE,
161 0,
162 0
163 );
164
165 if (kevent(mKqueue, &event, 1, NULL, 0, 0)) {
166 close(fd);
167 return false;
168 }
169
170 entry->state = (void *)(size_t)fd;
171 mFdToEntry.emplace(fd, entry);
172 }
173
174 sub.fd = (int)(size_t)entry->state;
175 mSubscriptions.emplace(path, sub);
176 return true;
177 }
178
179 std::vector<KqueueSubscription *> KqueueBackend::findSubscriptions(std::string &path) {
180 // Find the subscriptions affected by this path.
181 // Copy pointers to them into a vector so that modifying mSubscriptions doesn't invalidate the iterator.
182 auto range = mSubscriptions.equal_range(path);
183 std::vector<KqueueSubscription *> subs;
184 for (auto it = range.first; it != range.second; it++) {
185 subs.push_back(&it->second);
186 }
187
188 return subs;
189 }
190
191 bool KqueueBackend::compareDir(int fd, std::string &path, std::unordered_set<WatcherRef> &watchers) {
192 // macOS doesn't support fdclosedir, so we have to duplicate the file descriptor
193 // to ensure the closedir doesn't also stop watching.
194 #if __APPLE__
195 fd = dup(fd);
196 #endif
197
198 DIR *dir = fdopendir(fd);
199 if (dir == NULL) {
200 return false;
201 }
202
203 // fdopendir doesn't rewind to the beginning.
204 rewinddir(dir);
205
206 std::vector<KqueueSubscription *> subs = findSubscriptions(path);
207 std::string dirStart = path + DIR_SEP;
208
209 std::unordered_set<std::shared_ptr<DirTree>> trees;
210 for (auto it = subs.begin(); it != subs.end(); it++) {
211 trees.emplace((*it)->tree);
212 }
213
214 std::unordered_set<std::string> entries;
215 struct dirent *entry;
216 while ((entry = readdir(dir))) {
217 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
218 continue;
219 }
220
221 std::string fullpath = dirStart + entry->d_name;
222 entries.emplace(fullpath);
223
224 for (auto it = trees.begin(); it != trees.end(); it++) {
225 std::shared_ptr<DirTree> tree = *it;
226 if (!tree->find(fullpath)) {
227 struct stat st;
228 fstatat(fd, entry->d_name, &st, AT_SYMLINK_NOFOLLOW);
229 tree->add(fullpath, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode));
230
231 // Notify all watchers with the same tree.
232 for (auto i = subs.begin(); i != subs.end(); i++) {
233 KqueueSubscription *sub = *i;
234 if (sub->tree == tree) {
235 if (sub->watcher->isIgnored(fullpath)) {
236 continue;
237 }
238
239 sub->watcher->mEvents.create(fullpath);
240 watchers.emplace(sub->watcher);
241
242 bool success = watchDir(sub->watcher, fullpath, sub->tree);
243 if (!success) {
244 sub->tree->remove(fullpath);
245 return false;
246 }
247 }
248 }
249 }
250 }
251 }
252
253 for (auto it = trees.begin(); it != trees.end(); it++) {
254 std::shared_ptr<DirTree> tree = *it;
255 for (auto entry = tree->entries.begin(); entry != tree->entries.end();) {
256
257 if (
258 entry->first.rfind(dirStart, 0) == 0 &&
259 entry->first.find(DIR_SEP, dirStart.length()) == std::string::npos &&
260 entries.count(entry->first) == 0
261 ) {
262 // Notify all watchers with the same tree.
263 for (auto i = subs.begin(); i != subs.end(); i++) {
264 if ((*i)->tree == tree) {
265 KqueueSubscription *sub = *i;
266 if (!sub->watcher->isIgnored(entry->first)) {
267 sub->watcher->mEvents.remove(entry->first);
268 watchers.emplace(sub->watcher);
269 }
270 }
271 }
272
273 mFdToEntry.erase((int)(size_t)entry->second.state);
274 mSubscriptions.erase(entry->first);
275 entry = tree->entries.erase(entry);
276 } else {
277 entry++;
278 }
279 }
280 }
281
282 #if __APPLE__
283 closedir(dir);
284 #else
285 fdclosedir(dir);
286 #endif
287
288 return true;
289 }
290
291 void KqueueBackend::unsubscribe(WatcherRef watcher) {
292 // Find any subscriptions pointing to this watcher, and remove them.
293 for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
294 if (it->second.watcher.get() == watcher.get()) {
295 if (mSubscriptions.count(it->first) == 1) {
296 // Closing the file descriptor automatically unwatches it in the kqueue.
297 close(it->second.fd);
298 mFdToEntry.erase(it->second.fd);
299 }
300
301 it = mSubscriptions.erase(it);
302 } else {
303 it++;
304 }
305 }
306 }