Enables compositing support for webview.
[chromium-blink-merge.git] / base / files / file_path_watcher_linux.cc
blob9e550227dfc9b82ac08ac7cc852254c7d4bf3ac2
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.h"
7 #include <errno.h>
8 #include <string.h>
9 #include <sys/inotify.h>
10 #include <sys/ioctl.h>
11 #include <sys/select.h>
12 #include <unistd.h>
14 #include <algorithm>
15 #include <set>
16 #include <utility>
17 #include <vector>
19 #include "base/bind.h"
20 #include "base/file_path.h"
21 #include "base/file_util.h"
22 #include "base/hash_tables.h"
23 #include "base/lazy_instance.h"
24 #include "base/location.h"
25 #include "base/logging.h"
26 #include "base/memory/scoped_ptr.h"
27 #include "base/message_loop.h"
28 #include "base/message_loop_proxy.h"
29 #include "base/posix/eintr_wrapper.h"
30 #include "base/synchronization/lock.h"
31 #include "base/threading/thread.h"
33 namespace base {
34 namespace files {
36 namespace {
38 class FilePathWatcherImpl;
40 // Singleton to manage all inotify watches.
41 // TODO(tony): It would be nice if this wasn't a singleton.
42 // http://crbug.com/38174
43 class InotifyReader {
44 public:
45 typedef int Watch; // Watch descriptor used by AddWatch and RemoveWatch.
46 static const Watch kInvalidWatch = -1;
48 // Watch directory |path| for changes. |watcher| will be notified on each
49 // change. Returns kInvalidWatch on failure.
50 Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher);
52 // Remove |watch|. Returns true on success.
53 bool RemoveWatch(Watch watch, FilePathWatcherImpl* watcher);
55 // Callback for InotifyReaderTask.
56 void OnInotifyEvent(const inotify_event* event);
58 private:
59 friend struct ::base::DefaultLazyInstanceTraits<InotifyReader>;
61 typedef std::set<FilePathWatcherImpl*> WatcherSet;
63 InotifyReader();
64 ~InotifyReader();
66 // We keep track of which delegates want to be notified on which watches.
67 base::hash_map<Watch, WatcherSet> watchers_;
69 // Lock to protect watchers_.
70 base::Lock lock_;
72 // Separate thread on which we run blocking read for inotify events.
73 base::Thread thread_;
75 // File descriptor returned by inotify_init.
76 const int inotify_fd_;
78 // Use self-pipe trick to unblock select during shutdown.
79 int shutdown_pipe_[2];
81 // Flag set to true when startup was successful.
82 bool valid_;
84 DISALLOW_COPY_AND_ASSIGN(InotifyReader);
87 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
88 public MessageLoop::DestructionObserver {
89 public:
90 FilePathWatcherImpl();
92 // Called for each event coming from the watch. |fired_watch| identifies the
93 // watch that fired, |child| indicates what has changed, and is relative to
94 // the currently watched path for |fired_watch|. The flag |created| is true if
95 // the object appears.
96 void OnFilePathChanged(InotifyReader::Watch fired_watch,
97 const FilePath::StringType& child,
98 bool created);
100 // Start watching |path| for changes and notify |delegate| on each change.
101 // Returns true if watch for |path| has been added successfully.
102 virtual bool Watch(const FilePath& path,
103 bool recursive,
104 FilePathWatcher::Delegate* delegate) OVERRIDE;
106 // Cancel the watch. This unregisters the instance with InotifyReader.
107 virtual void Cancel() OVERRIDE;
109 // Deletion of the FilePathWatcher will call Cancel() to dispose of this
110 // object in the right thread. This also observes destruction of the required
111 // cleanup thread, in case it quits before Cancel() is called.
112 virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
114 protected:
115 virtual ~FilePathWatcherImpl() {}
117 private:
118 // Cleans up and stops observing the |message_loop_| thread.
119 virtual void CancelOnMessageLoopThread() OVERRIDE;
121 // Inotify watches are installed for all directory components of |target_|. A
122 // WatchEntry instance holds the watch descriptor for a component and the
123 // subdirectory for that identifies the next component. If a symbolic link
124 // is being watched, the target of the link is also kept.
125 struct WatchEntry {
126 WatchEntry(InotifyReader::Watch watch, const FilePath::StringType& subdir)
127 : watch_(watch),
128 subdir_(subdir) {}
130 InotifyReader::Watch watch_;
131 FilePath::StringType subdir_;
132 FilePath::StringType linkname_;
134 typedef std::vector<WatchEntry> WatchVector;
136 // Reconfigure to watch for the most specific parent directory of |target_|
137 // that exists. Updates |watched_path_|. Returns true on success.
138 bool UpdateWatches() WARN_UNUSED_RESULT;
140 // Delegate to notify upon changes.
141 scoped_refptr<FilePathWatcher::Delegate> delegate_;
143 // The file or directory we're supposed to watch.
144 FilePath target_;
146 // The vector of watches and next component names for all path components,
147 // starting at the root directory. The last entry corresponds to the watch for
148 // |target_| and always stores an empty next component name in |subdir_|.
149 WatchVector watches_;
151 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
154 void InotifyReaderCallback(InotifyReader* reader, int inotify_fd,
155 int shutdown_fd) {
156 // Make sure the file descriptors are good for use with select().
157 CHECK_LE(0, inotify_fd);
158 CHECK_GT(FD_SETSIZE, inotify_fd);
159 CHECK_LE(0, shutdown_fd);
160 CHECK_GT(FD_SETSIZE, shutdown_fd);
162 while (true) {
163 fd_set rfds;
164 FD_ZERO(&rfds);
165 FD_SET(inotify_fd, &rfds);
166 FD_SET(shutdown_fd, &rfds);
168 // Wait until some inotify events are available.
169 int select_result =
170 HANDLE_EINTR(select(std::max(inotify_fd, shutdown_fd) + 1,
171 &rfds, NULL, NULL, NULL));
172 if (select_result < 0) {
173 DPLOG(WARNING) << "select failed";
174 return;
177 if (FD_ISSET(shutdown_fd, &rfds))
178 return;
180 // Adjust buffer size to current event queue size.
181 int buffer_size;
182 int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd, FIONREAD,
183 &buffer_size));
185 if (ioctl_result != 0) {
186 DPLOG(WARNING) << "ioctl failed";
187 return;
190 std::vector<char> buffer(buffer_size);
192 ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd, &buffer[0],
193 buffer_size));
195 if (bytes_read < 0) {
196 DPLOG(WARNING) << "read from inotify fd failed";
197 return;
200 ssize_t i = 0;
201 while (i < bytes_read) {
202 inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
203 size_t event_size = sizeof(inotify_event) + event->len;
204 DCHECK(i + event_size <= static_cast<size_t>(bytes_read));
205 reader->OnInotifyEvent(event);
206 i += event_size;
211 static base::LazyInstance<InotifyReader>::Leaky g_inotify_reader =
212 LAZY_INSTANCE_INITIALIZER;
214 InotifyReader::InotifyReader()
215 : thread_("inotify_reader"),
216 inotify_fd_(inotify_init()),
217 valid_(false) {
218 shutdown_pipe_[0] = -1;
219 shutdown_pipe_[1] = -1;
220 if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) {
221 thread_.message_loop()->PostTask(
222 FROM_HERE, base::Bind(&InotifyReaderCallback, this, inotify_fd_,
223 shutdown_pipe_[0]));
224 valid_ = true;
228 InotifyReader::~InotifyReader() {
229 if (valid_) {
230 // Write to the self-pipe so that the select call in InotifyReaderTask
231 // returns.
232 ssize_t ret = HANDLE_EINTR(write(shutdown_pipe_[1], "", 1));
233 DPCHECK(ret > 0);
234 DCHECK_EQ(ret, 1);
235 thread_.Stop();
237 if (inotify_fd_ >= 0)
238 close(inotify_fd_);
239 if (shutdown_pipe_[0] >= 0)
240 close(shutdown_pipe_[0]);
241 if (shutdown_pipe_[1] >= 0)
242 close(shutdown_pipe_[1]);
245 InotifyReader::Watch InotifyReader::AddWatch(
246 const FilePath& path, FilePathWatcherImpl* watcher) {
247 if (!valid_)
248 return kInvalidWatch;
250 base::AutoLock auto_lock(lock_);
252 Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),
253 IN_CREATE | IN_DELETE |
254 IN_CLOSE_WRITE | IN_MOVE |
255 IN_ONLYDIR);
257 if (watch == kInvalidWatch)
258 return kInvalidWatch;
260 watchers_[watch].insert(watcher);
262 return watch;
265 bool InotifyReader::RemoveWatch(Watch watch,
266 FilePathWatcherImpl* watcher) {
267 if (!valid_)
268 return false;
270 base::AutoLock auto_lock(lock_);
272 watchers_[watch].erase(watcher);
274 if (watchers_[watch].empty()) {
275 watchers_.erase(watch);
276 return (inotify_rm_watch(inotify_fd_, watch) == 0);
279 return true;
282 void InotifyReader::OnInotifyEvent(const inotify_event* event) {
283 if (event->mask & IN_IGNORED)
284 return;
286 FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
287 base::AutoLock auto_lock(lock_);
289 for (WatcherSet::iterator watcher = watchers_[event->wd].begin();
290 watcher != watchers_[event->wd].end();
291 ++watcher) {
292 (*watcher)->OnFilePathChanged(event->wd,
293 child,
294 event->mask & (IN_CREATE | IN_MOVED_TO));
298 FilePathWatcherImpl::FilePathWatcherImpl()
299 : delegate_(NULL) {
302 void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch,
303 const FilePath::StringType& child,
304 bool created) {
305 if (!message_loop()->BelongsToCurrentThread()) {
306 // Switch to message_loop_ to access watches_ safely.
307 message_loop()->PostTask(FROM_HERE,
308 base::Bind(&FilePathWatcherImpl::OnFilePathChanged,
309 this,
310 fired_watch,
311 child,
312 created));
313 return;
316 DCHECK(MessageLoopForIO::current());
318 // Find the entry in |watches_| that corresponds to |fired_watch|.
319 WatchVector::const_iterator watch_entry(watches_.begin());
320 for ( ; watch_entry != watches_.end(); ++watch_entry) {
321 if (fired_watch == watch_entry->watch_) {
322 // Check whether a path component of |target_| changed.
323 bool change_on_target_path = child.empty() ||
324 ((child == watch_entry->subdir_) && watch_entry->linkname_.empty()) ||
325 (child == watch_entry->linkname_);
327 // Check whether the change references |target_| or a direct child.
328 DCHECK(watch_entry->subdir_.empty() ||
329 (watch_entry + 1) != watches_.end());
330 bool target_changed =
331 (watch_entry->subdir_.empty() && (child == watch_entry->linkname_)) ||
332 (watch_entry->subdir_.empty() && watch_entry->linkname_.empty()) ||
333 (watch_entry->subdir_ == child && (watch_entry + 1)->subdir_.empty());
335 // Update watches if a directory component of the |target_| path
336 // (dis)appears. Note that we don't add the additional restriction
337 // of checking the event mask to see if it is for a directory here
338 // as changes to symlinks on the target path will not have
339 // IN_ISDIR set in the event masks. As a result we may sometimes
340 // call UpdateWatches() unnecessarily.
341 if (change_on_target_path && !UpdateWatches()) {
342 delegate_->OnFilePathError(target_);
343 return;
346 // Report the following events:
347 // - The target or a direct child of the target got changed (in case the
348 // watched path refers to a directory).
349 // - One of the parent directories got moved or deleted, since the target
350 // disappears in this case.
351 // - One of the parent directories appears. The event corresponding to
352 // the target appearing might have been missed in this case, so
353 // recheck.
354 if (target_changed ||
355 (change_on_target_path && !created) ||
356 (change_on_target_path && file_util::PathExists(target_))) {
357 delegate_->OnFilePathChanged(target_);
358 return;
364 bool FilePathWatcherImpl::Watch(const FilePath& path,
365 bool recursive,
366 FilePathWatcher::Delegate* delegate) {
367 DCHECK(target_.empty());
368 DCHECK(MessageLoopForIO::current());
369 if (recursive) {
370 // Recursive watch is not supported on this platform.
371 NOTIMPLEMENTED();
372 return false;
375 set_message_loop(base::MessageLoopProxy::current());
376 delegate_ = delegate;
377 target_ = path;
378 MessageLoop::current()->AddDestructionObserver(this);
380 std::vector<FilePath::StringType> comps;
381 target_.GetComponents(&comps);
382 DCHECK(!comps.empty());
383 std::vector<FilePath::StringType>::const_iterator comp = comps.begin();
384 for (++comp; comp != comps.end(); ++comp)
385 watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, *comp));
387 watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch,
388 FilePath::StringType()));
389 return UpdateWatches();
392 void FilePathWatcherImpl::Cancel() {
393 if (!delegate_) {
394 // Watch was never called, or the |message_loop_| thread is already gone.
395 set_cancelled();
396 return;
399 // Switch to the message_loop_ if necessary so we can access |watches_|.
400 if (!message_loop()->BelongsToCurrentThread()) {
401 message_loop()->PostTask(FROM_HERE,
402 base::Bind(&FilePathWatcher::CancelWatch,
403 make_scoped_refptr(this)));
404 } else {
405 CancelOnMessageLoopThread();
409 void FilePathWatcherImpl::CancelOnMessageLoopThread() {
410 if (!is_cancelled())
411 set_cancelled();
413 if (delegate_) {
414 MessageLoop::current()->RemoveDestructionObserver(this);
415 delegate_ = NULL;
418 for (WatchVector::iterator watch_entry(watches_.begin());
419 watch_entry != watches_.end(); ++watch_entry) {
420 if (watch_entry->watch_ != InotifyReader::kInvalidWatch)
421 g_inotify_reader.Get().RemoveWatch(watch_entry->watch_, this);
423 watches_.clear();
424 target_.clear();
427 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
428 CancelOnMessageLoopThread();
431 bool FilePathWatcherImpl::UpdateWatches() {
432 // Ensure this runs on the |message_loop_| exclusively in order to avoid
433 // concurrency issues.
434 DCHECK(message_loop()->BelongsToCurrentThread());
436 // Walk the list of watches and update them as we go.
437 FilePath path(FILE_PATH_LITERAL("/"));
438 bool path_valid = true;
439 for (WatchVector::iterator watch_entry(watches_.begin());
440 watch_entry != watches_.end(); ++watch_entry) {
441 InotifyReader::Watch old_watch = watch_entry->watch_;
442 if (path_valid) {
443 watch_entry->watch_ = g_inotify_reader.Get().AddWatch(path, this);
444 if ((watch_entry->watch_ == InotifyReader::kInvalidWatch) &&
445 file_util::IsLink(path)) {
446 FilePath link;
447 if (file_util::ReadSymbolicLink(path, &link)) {
448 if (!link.IsAbsolute())
449 link = path.DirName().Append(link);
450 // Try watching symlink target directory. If the link target is "/",
451 // then we shouldn't get here in normal situations and if we do, we'd
452 // watch "/" for changes to a component "/" which is harmless so no
453 // special treatment of this case is required.
454 watch_entry->watch_ =
455 g_inotify_reader.Get().AddWatch(link.DirName(), this);
456 if (watch_entry->watch_ != InotifyReader::kInvalidWatch) {
457 watch_entry->linkname_ = link.BaseName().value();
458 } else {
459 DPLOG(WARNING) << "Watch failed for " << link.DirName().value();
460 // TODO(craig) Symlinks only work if the parent directory
461 // for the target exist. Ideally we should make sure we've
462 // watched all the components of the symlink path for
463 // changes. See crbug.com/91561 for details.
467 if (watch_entry->watch_ == InotifyReader::kInvalidWatch) {
468 path_valid = false;
470 } else {
471 watch_entry->watch_ = InotifyReader::kInvalidWatch;
473 if (old_watch != InotifyReader::kInvalidWatch &&
474 old_watch != watch_entry->watch_) {
475 g_inotify_reader.Get().RemoveWatch(old_watch, this);
477 path = path.Append(watch_entry->subdir_);
480 return true;
483 } // namespace
485 FilePathWatcher::FilePathWatcher() {
486 impl_ = new FilePathWatcherImpl();
489 } // namespace files
490 } // namespace base