Evaluate declarativeContent API rules on add/remove
[chromium-blink-merge.git] / base / files / file_path_watcher_kqueue.cc
blobe15cba7d34151f10816e17f08bbff09b55a5dd61
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/files/file_path_watcher_kqueue.h"
7 #include <fcntl.h>
8 #include <sys/param.h>
10 #include "base/bind.h"
11 #include "base/files/file_util.h"
12 #include "base/logging.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/thread_task_runner_handle.h"
16 // On some platforms these are not defined.
17 #if !defined(EV_RECEIPT)
18 #define EV_RECEIPT 0
19 #endif
20 #if !defined(O_EVTONLY)
21 #define O_EVTONLY O_RDONLY
22 #endif
24 namespace base {
26 FilePathWatcherKQueue::FilePathWatcherKQueue() : kqueue_(-1) {}
28 FilePathWatcherKQueue::~FilePathWatcherKQueue() {}
30 void FilePathWatcherKQueue::ReleaseEvent(struct kevent& event) {
31 CloseFileDescriptor(&event.ident);
32 EventData* entry = EventDataForKevent(event);
33 delete entry;
34 event.udata = NULL;
37 int FilePathWatcherKQueue::EventsForPath(FilePath path, EventVector* events) {
38 DCHECK(MessageLoopForIO::current());
39 // Make sure that we are working with a clean slate.
40 DCHECK(events->empty());
42 std::vector<FilePath::StringType> components;
43 path.GetComponents(&components);
45 if (components.size() < 1) {
46 return -1;
49 int last_existing_entry = 0;
50 FilePath built_path;
51 bool path_still_exists = true;
52 for (std::vector<FilePath::StringType>::iterator i = components.begin();
53 i != components.end(); ++i) {
54 if (i == components.begin()) {
55 built_path = FilePath(*i);
56 } else {
57 built_path = built_path.Append(*i);
59 uintptr_t fd = kNoFileDescriptor;
60 if (path_still_exists) {
61 fd = FileDescriptorForPath(built_path);
62 if (fd == kNoFileDescriptor) {
63 path_still_exists = false;
64 } else {
65 ++last_existing_entry;
68 FilePath::StringType subdir = (i != (components.end() - 1)) ? *(i + 1) : "";
69 EventData* data = new EventData(built_path, subdir);
70 struct kevent event;
71 EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT),
72 (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB |
73 NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data);
74 events->push_back(event);
76 return last_existing_entry;
79 uintptr_t FilePathWatcherKQueue::FileDescriptorForPath(const FilePath& path) {
80 int fd = HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY));
81 if (fd == -1)
82 return kNoFileDescriptor;
83 return fd;
86 void FilePathWatcherKQueue::CloseFileDescriptor(uintptr_t* fd) {
87 if (*fd == kNoFileDescriptor) {
88 return;
91 if (IGNORE_EINTR(close(*fd)) != 0) {
92 DPLOG(ERROR) << "close";
94 *fd = kNoFileDescriptor;
97 bool FilePathWatcherKQueue::AreKeventValuesValid(struct kevent* kevents,
98 int count) {
99 if (count < 0) {
100 DPLOG(ERROR) << "kevent";
101 return false;
103 bool valid = true;
104 for (int i = 0; i < count; ++i) {
105 if (kevents[i].flags & EV_ERROR && kevents[i].data) {
106 // Find the kevent in |events_| that matches the kevent with the error.
107 EventVector::iterator event = events_.begin();
108 for (; event != events_.end(); ++event) {
109 if (event->ident == kevents[i].ident) {
110 break;
113 std::string path_name;
114 if (event != events_.end()) {
115 EventData* event_data = EventDataForKevent(*event);
116 if (event_data != NULL) {
117 path_name = event_data->path_.value();
120 if (path_name.empty()) {
121 path_name = base::StringPrintf(
122 "fd %ld", reinterpret_cast<long>(&kevents[i].ident));
124 DLOG(ERROR) << "Error: " << kevents[i].data << " for " << path_name;
125 valid = false;
128 return valid;
131 void FilePathWatcherKQueue::HandleAttributesChange(
132 const EventVector::iterator& event,
133 bool* target_file_affected,
134 bool* update_watches) {
135 EventVector::iterator next_event = event + 1;
136 EventData* next_event_data = EventDataForKevent(*next_event);
137 // Check to see if the next item in path is still accessible.
138 uintptr_t have_access = FileDescriptorForPath(next_event_data->path_);
139 if (have_access == kNoFileDescriptor) {
140 *target_file_affected = true;
141 *update_watches = true;
142 EventVector::iterator local_event(event);
143 for (; local_event != events_.end(); ++local_event) {
144 // Close all nodes from the event down. This has the side effect of
145 // potentially rendering other events in |updates| invalid.
146 // There is no need to remove the events from |kqueue_| because this
147 // happens as a side effect of closing the file descriptor.
148 CloseFileDescriptor(&local_event->ident);
150 } else {
151 CloseFileDescriptor(&have_access);
155 void FilePathWatcherKQueue::HandleDeleteOrMoveChange(
156 const EventVector::iterator& event,
157 bool* target_file_affected,
158 bool* update_watches) {
159 *target_file_affected = true;
160 *update_watches = true;
161 EventVector::iterator local_event(event);
162 for (; local_event != events_.end(); ++local_event) {
163 // Close all nodes from the event down. This has the side effect of
164 // potentially rendering other events in |updates| invalid.
165 // There is no need to remove the events from |kqueue_| because this
166 // happens as a side effect of closing the file descriptor.
167 CloseFileDescriptor(&local_event->ident);
171 void FilePathWatcherKQueue::HandleCreateItemChange(
172 const EventVector::iterator& event,
173 bool* target_file_affected,
174 bool* update_watches) {
175 // Get the next item in the path.
176 EventVector::iterator next_event = event + 1;
177 // Check to see if it already has a valid file descriptor.
178 if (!IsKeventFileDescriptorOpen(*next_event)) {
179 EventData* next_event_data = EventDataForKevent(*next_event);
180 // If not, attempt to open a file descriptor for it.
181 next_event->ident = FileDescriptorForPath(next_event_data->path_);
182 if (IsKeventFileDescriptorOpen(*next_event)) {
183 *update_watches = true;
184 if (next_event_data->subdir_.empty()) {
185 *target_file_affected = true;
191 bool FilePathWatcherKQueue::UpdateWatches(bool* target_file_affected) {
192 // Iterate over events adding kevents for items that exist to the kqueue.
193 // Then check to see if new components in the path have been created.
194 // Repeat until no new components in the path are detected.
195 // This is to get around races in directory creation in a watched path.
196 bool update_watches = true;
197 while (update_watches) {
198 size_t valid;
199 for (valid = 0; valid < events_.size(); ++valid) {
200 if (!IsKeventFileDescriptorOpen(events_[valid])) {
201 break;
204 if (valid == 0) {
205 // The root of the file path is inaccessible?
206 return false;
209 EventVector updates(valid);
210 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], valid, &updates[0],
211 valid, NULL));
212 if (!AreKeventValuesValid(&updates[0], count)) {
213 return false;
215 update_watches = false;
216 for (; valid < events_.size(); ++valid) {
217 EventData* event_data = EventDataForKevent(events_[valid]);
218 events_[valid].ident = FileDescriptorForPath(event_data->path_);
219 if (IsKeventFileDescriptorOpen(events_[valid])) {
220 update_watches = true;
221 if (event_data->subdir_.empty()) {
222 *target_file_affected = true;
224 } else {
225 break;
229 return true;
232 void FilePathWatcherKQueue::OnFileCanReadWithoutBlocking(int fd) {
233 DCHECK(MessageLoopForIO::current());
234 DCHECK_EQ(fd, kqueue_);
235 DCHECK(events_.size());
237 // Request the file system update notifications that have occurred and return
238 // them in |updates|. |count| will contain the number of updates that have
239 // occurred.
240 EventVector updates(events_.size());
241 struct timespec timeout = {0, 0};
242 int count = HANDLE_EINTR(kevent(kqueue_, NULL, 0, &updates[0], updates.size(),
243 &timeout));
245 // Error values are stored within updates, so check to make sure that no
246 // errors occurred.
247 if (!AreKeventValuesValid(&updates[0], count)) {
248 callback_.Run(target_, true /* error */);
249 Cancel();
250 return;
253 bool update_watches = false;
254 bool send_notification = false;
256 // Iterate through each of the updates and react to them.
257 for (int i = 0; i < count; ++i) {
258 // Find our kevent record that matches the update notification.
259 EventVector::iterator event = events_.begin();
260 for (; event != events_.end(); ++event) {
261 if (!IsKeventFileDescriptorOpen(*event) ||
262 event->ident == updates[i].ident) {
263 break;
266 if (event == events_.end() || !IsKeventFileDescriptorOpen(*event)) {
267 // The event may no longer exist in |events_| because another event
268 // modified |events_| in such a way to make it invalid. For example if
269 // the path is /foo/bar/bam and foo is deleted, NOTE_DELETE events for
270 // foo, bar and bam will be sent. If foo is processed first, then
271 // the file descriptors for bar and bam will already be closed and set
272 // to -1 before they get a chance to be processed.
273 continue;
276 EventData* event_data = EventDataForKevent(*event);
278 // If the subdir is empty, this is the last item on the path and is the
279 // target file.
280 bool target_file_affected = event_data->subdir_.empty();
281 if ((updates[i].fflags & NOTE_ATTRIB) && !target_file_affected) {
282 HandleAttributesChange(event, &target_file_affected, &update_watches);
284 if (updates[i].fflags & (NOTE_DELETE | NOTE_REVOKE | NOTE_RENAME)) {
285 HandleDeleteOrMoveChange(event, &target_file_affected, &update_watches);
287 if ((updates[i].fflags & NOTE_WRITE) && !target_file_affected) {
288 HandleCreateItemChange(event, &target_file_affected, &update_watches);
290 send_notification |= target_file_affected;
293 if (update_watches) {
294 if (!UpdateWatches(&send_notification)) {
295 callback_.Run(target_, true /* error */);
296 Cancel();
300 if (send_notification) {
301 callback_.Run(target_, false);
305 void FilePathWatcherKQueue::OnFileCanWriteWithoutBlocking(int fd) {
306 NOTREACHED();
309 void FilePathWatcherKQueue::WillDestroyCurrentMessageLoop() {
310 CancelOnMessageLoopThread();
313 bool FilePathWatcherKQueue::Watch(const FilePath& path,
314 bool recursive,
315 const FilePathWatcher::Callback& callback) {
316 DCHECK(MessageLoopForIO::current());
317 DCHECK(target_.value().empty()); // Can only watch one path.
318 DCHECK(!callback.is_null());
319 DCHECK_EQ(kqueue_, -1);
321 if (recursive) {
322 // Recursive watch is not supported using kqueue.
323 NOTIMPLEMENTED();
324 return false;
327 callback_ = callback;
328 target_ = path;
330 MessageLoop::current()->AddDestructionObserver(this);
331 io_task_runner_ = ThreadTaskRunnerHandle::Get();
333 kqueue_ = kqueue();
334 if (kqueue_ == -1) {
335 DPLOG(ERROR) << "kqueue";
336 return false;
339 int last_entry = EventsForPath(target_, &events_);
340 DCHECK_NE(last_entry, 0);
342 EventVector responses(last_entry);
344 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], last_entry,
345 &responses[0], last_entry, NULL));
346 if (!AreKeventValuesValid(&responses[0], count)) {
347 // Calling Cancel() here to close any file descriptors that were opened.
348 // This would happen in the destructor anyways, but FilePathWatchers tend to
349 // be long lived, and if an error has occurred, there is no reason to waste
350 // the file descriptors.
351 Cancel();
352 return false;
355 return MessageLoopForIO::current()->WatchFileDescriptor(
356 kqueue_, true, MessageLoopForIO::WATCH_READ, &kqueue_watcher_, this);
359 void FilePathWatcherKQueue::Cancel() {
360 SingleThreadTaskRunner* task_runner = io_task_runner_.get();
361 if (!task_runner) {
362 set_cancelled();
363 return;
365 if (!task_runner->BelongsToCurrentThread()) {
366 task_runner->PostTask(FROM_HERE,
367 base::Bind(&FilePathWatcherKQueue::Cancel, this));
368 return;
370 CancelOnMessageLoopThread();
373 void FilePathWatcherKQueue::CancelOnMessageLoopThread() {
374 DCHECK(MessageLoopForIO::current());
375 if (!is_cancelled()) {
376 set_cancelled();
377 kqueue_watcher_.StopWatchingFileDescriptor();
378 if (IGNORE_EINTR(close(kqueue_)) != 0) {
379 DPLOG(ERROR) << "close kqueue";
381 kqueue_ = -1;
382 std::for_each(events_.begin(), events_.end(), ReleaseEvent);
383 events_.clear();
384 io_task_runner_ = NULL;
385 MessageLoop::current()->RemoveDestructionObserver(this);
386 callback_.Reset();
390 } // namespace base