2 // System.IO.KeventWatcher.cs: interface with osx kevent
5 // Geoff Norton (gnorton@customerdna.com)
6 // Cody Russell (cody@xamarin.com)
7 // Alexis Christoforides (lexas@xamarin.com)
9 // (c) 2004 Geoff Norton
10 // Copyright 2014 Xamarin Inc
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.ComponentModel;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
39 using System.Threading;
40 using System.Reflection;
45 enum EventFlags : ushort {
57 SystemFlags = unchecked (0xf000),
64 enum EventFilter : short {
79 enum FilterFlags : uint {
80 ReadPoll = EventFlags.Flag0,
81 ReadOutOfBand = EventFlags.Flag1,
82 ReadLowWaterMark = 0x00000001,
84 WriteLowWaterMark = ReadLowWaterMark,
86 NoteTrigger = 0x01000000,
87 NoteFFNop = 0x00000000,
88 NoteFFAnd = 0x40000000,
89 NoteFFOr = 0x80000000,
90 NoteFFCopy = 0xc0000000,
91 NoteFFCtrlMask = 0xc0000000,
92 NoteFFlagsMask = 0x00ffffff,
94 VNodeDelete = 0x00000001,
95 VNodeWrite = 0x00000002,
96 VNodeExtend = 0x00000004,
97 VNodeAttrib = 0x00000008,
98 VNodeLink = 0x00000010,
99 VNodeRename = 0x00000020,
100 VNodeRevoke = 0x00000040,
101 VNodeNone = 0x00000080,
103 ProcExit = 0x80000000,
104 ProcFork = 0x40000000,
105 ProcExec = 0x20000000,
106 ProcReap = 0x10000000,
107 ProcSignal = 0x08000000,
108 ProcExitStatus = 0x04000000,
109 ProcResourceEnd = 0x02000000,
112 ProcAppactive = 0x00800000,
113 ProcAppBackground = 0x00400000,
114 ProcAppNonUI = 0x00200000,
115 ProcAppInactive = 0x00100000,
116 ProcAppAllStates = 0x00f00000,
119 ProcPDataMask = 0x000fffff,
120 ProcControlMask = 0xfff00000,
122 VMPressure = 0x80000000,
123 VMPressureTerminate = 0x40000000,
124 VMPressureSuddenTerminate = 0x20000000,
125 VMError = 0x10000000,
126 TimerSeconds = 0x00000001,
127 TimerMicroSeconds = 0x00000002,
128 TimerNanoSeconds = 0x00000004,
129 TimerAbsolute = 0x00000008,
132 [StructLayout(LayoutKind.Sequential)]
133 struct kevent : IDisposable {
134 public UIntPtr ident;
135 public EventFilter filter;
136 public EventFlags flags;
137 public FilterFlags fflags;
141 public void Dispose ()
143 if (udata != IntPtr.Zero)
144 Marshal.FreeHGlobal (udata);
150 [StructLayout(LayoutKind.Sequential)]
152 public IntPtr tv_sec;
153 public IntPtr tv_usec;
159 public bool IsDirectory;
163 class KqueueMonitor : IDisposable
165 public int Connection
170 public KqueueMonitor (FileSystemWatcher fsw)
176 public void Dispose ()
190 throw new IOException (String.Format (
191 "kqueue() error at init, error code = '{0}'", Marshal.GetLastWin32Error ()));
193 thread = new Thread (() => DoMonitor ());
194 thread.IsBackground = true;
197 startedEvent.WaitOne ();
219 // This will break the wait in Monitor ()
226 if (!thread.Join (2000))
245 foreach (int fd in fdsDict.Keys)
256 } catch (Exception e) {
263 fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
269 } catch (Exception e) {
273 if (!requestStop) { // failure
276 fsw.EnableRaisingEvents = false;
279 fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
286 var initialFds = new List<int> ();
288 // fsw.FullPath may end in '/', see https://bugzilla.xamarin.com/show_bug.cgi?id=5747
289 if (fsw.FullPath != "/" && fsw.FullPath.EndsWith ("/", StringComparison.Ordinal))
290 fullPathNoLastSlash = fsw.FullPath.Substring (0, fsw.FullPath.Length - 1);
292 fullPathNoLastSlash = fsw.FullPath;
294 // GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
295 // If so, introduce a fixup step.
296 int fd = open (fullPathNoLastSlash, O_EVTONLY, 0);
297 var resolvedFullPath = GetFilenameFromFd (fd);
300 if (resolvedFullPath != fullPathNoLastSlash)
301 fixupPath = resolvedFullPath;
305 Scan (fullPathNoLastSlash, false, ref initialFds);
307 var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_usec = (IntPtr)0 };
308 var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
309 var changes = CreateChangeList (ref initialFds);
311 int numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
313 if (numEvents == -1) {
314 var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", Marshal.GetLastWin32Error ());
315 throw new IOException (errMsg);
319 kevent[] CreateChangeList (ref List<int> FdList)
321 if (FdList.Count == 0)
322 return emptyEventList;
324 var changes = new List<kevent> ();
325 foreach (int fd in FdList) {
326 var change = new kevent {
329 filter = EventFilter.Vnode,
330 flags = EventFlags.Add | EventFlags.Enable | EventFlags.Clear,
331 fflags = FilterFlags.VNodeDelete | FilterFlags.VNodeExtend |
332 FilterFlags.VNodeRename | FilterFlags.VNodeAttrib |
333 FilterFlags.VNodeLink | FilterFlags.VNodeRevoke |
334 FilterFlags.VNodeWrite,
339 changes.Add (change);
343 return changes.ToArray ();
348 var eventBuffer = new kevent[32];
349 var newFds = new List<int> ();
350 List<PathData> removeQueue = new List<PathData> ();
351 List<string> rescanQueue = new List<string> ();
355 while (!requestStop) {
356 var changes = CreateChangeList (ref newFds);
358 int numEvents = kevent_notimeout (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, IntPtr.Zero);
360 if (numEvents == -1) {
361 // Stop () signals us to stop by closing the connection
365 throw new IOException (String.Format (
366 "persistent kevent() error, error code = '{0}'", Marshal.GetLastWin32Error ()));
373 for (var i = 0; i < numEvents; i++) {
374 var kevt = eventBuffer [i];
375 var pathData = fdsDict [(int)kevt.ident];
377 if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
378 var errMsg = String.Format ("kevent() error watching path '{0}', error code = '{1}'", pathData.Path, kevt.data);
379 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (errMsg)));
383 if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke) {
384 if (pathData.Path == fullPathNoLastSlash)
385 //The root path is deleted; exit silently
388 removeQueue.Add (pathData);
392 if ((kevt.fflags & FilterFlags.VNodeRename) == FilterFlags.VNodeRename) {
393 UpdatePath (pathData);
396 if ((kevt.fflags & FilterFlags.VNodeWrite) == FilterFlags.VNodeWrite) {
397 if (pathData.IsDirectory) //TODO: Check if dirs trigger Changed events on .NET
398 rescanQueue.Add (pathData.Path);
400 PostEvent (FileAction.Modified, pathData.Path);
403 if ((kevt.fflags & FilterFlags.VNodeAttrib) == FilterFlags.VNodeAttrib || (kevt.fflags & FilterFlags.VNodeExtend) == FilterFlags.VNodeExtend)
404 PostEvent (FileAction.Modified, pathData.Path);
407 removeQueue.ForEach (Remove);
408 removeQueue.Clear ();
410 rescanQueue.ForEach (path => {
411 Scan (path, true, ref newFds);
413 rescanQueue.Clear ();
417 PathData Add (string path, bool postEvents, ref List<int> fds)
420 pathsDict.TryGetValue (path, out pathData);
422 if (pathData != null)
425 if (fdsDict.Count >= maxFds)
426 throw new IOException ("kqueue() FileSystemWatcher has reached the maximum number of files to watch.");
428 var fd = open (path, O_EVTONLY, 0);
431 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
432 "open() error while attempting to process path '{0}', error code = '{1}'", path, Marshal.GetLastWin32Error ()))));
439 var attrs = File.GetAttributes (path);
441 pathData = new PathData {
444 IsDirectory = (attrs & FileAttributes.Directory) == FileAttributes.Directory
447 pathsDict.Add (path, pathData);
448 fdsDict.Add (fd, pathData);
451 PostEvent (FileAction.Added, path);
454 } catch (Exception e) {
456 fsw.DispatchErrorEvents (new ErrorEventArgs (e));
462 void Remove (PathData pathData)
464 fdsDict.Remove (pathData.Fd);
465 pathsDict.Remove (pathData.Path);
467 PostEvent (FileAction.Removed, pathData.Path);
470 void RemoveTree (PathData pathData)
472 var toRemove = new List<PathData> ();
474 toRemove.Add (pathData);
476 if (pathData.IsDirectory) {
477 var prefix = pathData.Path + Path.DirectorySeparatorChar;
478 foreach (var path in pathsDict.Keys)
479 if (path.StartsWith (prefix)) {
480 toRemove.Add (pathsDict [path]);
483 toRemove.ForEach (Remove);
486 void UpdatePath (PathData pathData)
488 var newRoot = GetFilenameFromFd (pathData.Fd);
489 if (!newRoot.StartsWith (fullPathNoLastSlash)) { // moved outside of our watched path (so stop observing it)
490 RemoveTree (pathData);
494 var toRename = new List<PathData> ();
495 var oldRoot = pathData.Path;
497 toRename.Add (pathData);
499 if (pathData.IsDirectory) { // anything under the directory must have their paths updated
500 var prefix = oldRoot + Path.DirectorySeparatorChar;
501 foreach (var path in pathsDict.Keys)
502 if (path.StartsWith (prefix))
503 toRename.Add (pathsDict [path]);
506 foreach (var renaming in toRename) {
507 var oldPath = renaming.Path;
508 var newPath = newRoot + oldPath.Substring (oldRoot.Length);
510 renaming.Path = newPath;
511 pathsDict.Remove (oldPath);
513 // destination may exist in our records from a Created event, take care of it
514 if (pathsDict.ContainsKey (newPath)) {
515 var conflict = pathsDict [newPath];
516 if (GetFilenameFromFd (renaming.Fd) == GetFilenameFromFd (conflict.Fd))
519 UpdatePath (conflict);
522 pathsDict.Add (newPath, renaming);
525 PostEvent (FileAction.RenamedNewName, oldRoot, newRoot);
528 void Scan (string path, bool postEvents, ref List<int> fds)
533 var pathData = Add (path, postEvents, ref fds);
535 if (pathData == null)
538 if (!pathData.IsDirectory)
541 var dirsToProcess = new List<string> ();
542 dirsToProcess.Add (path);
544 while (dirsToProcess.Count > 0) {
545 var tmp = dirsToProcess [0];
546 dirsToProcess.RemoveAt (0);
548 var info = new DirectoryInfo (tmp);
549 FileSystemInfo[] fsInfos = null;
551 fsInfos = info.GetFileSystemInfos ();
553 } catch (IOException) {
554 // this can happen if the directory has been deleted already.
555 // that's okay, just keep processing the other dirs.
556 fsInfos = new FileSystemInfo[0];
559 foreach (var fsi in fsInfos) {
560 if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory && !fsw.IncludeSubdirectories)
563 if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && !fsw.Pattern.IsMatch (fsi.FullName))
566 var currentPathData = Add (fsi.FullName, postEvents, ref fds);
568 if (currentPathData != null && currentPathData.IsDirectory)
569 dirsToProcess.Add (fsi.FullName);
574 void PostEvent (FileAction action, string path, string newPath = null)
576 RenamedEventArgs renamed = null;
578 if (requestStop || action == 0)
582 string name = path.Substring (fullPathNoLastSlash.Length + 1);
584 // only post events that match filter pattern. check both old and new paths for renames
585 if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath)))
588 if (action == FileAction.RenamedNewName) {
589 string newName = newPath.Substring (fullPathNoLastSlash.Length + 1);
590 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, fsw.Path, newName, name);
593 fsw.DispatchEvents (action, name, ref renamed);
598 System.Threading.Monitor.PulseAll (fsw);
603 private string GetFilenameFromFd (int fd)
605 var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
607 if (fcntl (fd, F_GETPATH, sb) != -1) {
608 if (fixupPath != null)
609 sb.Replace (fixupPath, fullPathNoLastSlash, 0, fixupPath.Length); // see Setup()
611 return sb.ToString ();
613 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
614 "fcntl() error while attempting to get path for fd '{0}', error code = '{1}'", fd, Marshal.GetLastWin32Error ()))));
619 const int O_EVTONLY = 0x8000;
620 const int F_GETPATH = 50;
621 const int __DARWIN_MAXPATHLEN = 1024;
622 static readonly kevent[] emptyEventList = new System.IO.kevent[0];
623 const int maxFds = 200;
625 FileSystemWatcher fsw;
628 volatile bool requestStop = false;
629 AutoResetEvent startedEvent = new AutoResetEvent (false);
630 bool started = false;
631 bool inDispatch = false;
632 Exception exc = null;
633 object stateLock = new object ();
634 object connLock = new object ();
636 readonly Dictionary<string, PathData> pathsDict = new Dictionary<string, PathData> ();
637 readonly Dictionary<int, PathData> fdsDict = new Dictionary<int, PathData> ();
638 string fixupPath = null;
639 string fullPathNoLastSlash = null;
641 [DllImport ("libc", EntryPoint="fcntl", CharSet=CharSet.Auto, SetLastError=true)]
642 static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);
645 extern static int open (string path, int flags, int mode_t);
648 extern static int close (int fd);
651 extern static int kqueue ();
654 extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);
656 [DllImport ("libc", EntryPoint="kevent")]
657 extern static int kevent_notimeout (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, IntPtr ptr);
660 class KeventWatcher : IFileWatcher
663 static KeventWatcher instance;
664 static Hashtable watches; // <FileSystemWatcher, KqueueMonitor>
666 private KeventWatcher ()
671 public static bool GetInstance (out IFileWatcher watcher)
673 if (failed == true) {
678 if (instance != null) {
683 watches = Hashtable.Synchronized (new Hashtable ());
692 instance = new KeventWatcher ();
697 public void StartDispatching (FileSystemWatcher fsw)
699 KqueueMonitor monitor;
701 if (watches.ContainsKey (fsw)) {
702 monitor = (KqueueMonitor)watches [fsw];
704 monitor = new KqueueMonitor (fsw);
705 watches.Add (fsw, monitor);
711 public void StopDispatching (FileSystemWatcher fsw)
713 KqueueMonitor monitor = (KqueueMonitor)watches [fsw];
721 extern static int close (int fd);
724 extern static int kqueue ();