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_nsec;
159 public bool IsDirectory;
163 class KqueueMonitor : IDisposable
165 static bool initialized;
167 public int Connection
172 public KqueueMonitor (FileSystemWatcher fsw)
179 var maxenv = Environment.GetEnvironmentVariable ("MONO_DARWIN_WATCHER_MAXFDS");
180 if (maxenv != null && Int32.TryParse (maxenv, out t))
185 public void Dispose ()
199 throw new IOException (String.Format (
200 "kqueue() error at init, error code = '{0}'", Marshal.GetLastWin32Error ()));
202 thread = new Thread (() => DoMonitor ());
203 thread.IsBackground = true;
206 startedEvent.WaitOne ();
228 // This will break the wait in Monitor ()
235 if (!thread.Join (2000))
254 foreach (int fd in fdsDict.Keys)
265 } catch (Exception e) {
272 fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
278 } catch (Exception e) {
282 if (!requestStop) { // failure
285 fsw.EnableRaisingEvents = false;
288 fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
295 var initialFds = new List<int> ();
297 // fsw.FullPath may end in '/', see https://bugzilla.xamarin.com/show_bug.cgi?id=5747
298 if (fsw.FullPath != "/" && fsw.FullPath.EndsWith ("/", StringComparison.Ordinal))
299 fullPathNoLastSlash = fsw.FullPath.Substring (0, fsw.FullPath.Length - 1);
301 fullPathNoLastSlash = fsw.FullPath;
303 // GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
304 // If so, introduce a fixup step.
305 int fd = open (fullPathNoLastSlash, O_EVTONLY, 0);
306 var resolvedFullPath = GetFilenameFromFd (fd);
309 if (resolvedFullPath != fullPathNoLastSlash)
310 fixupPath = resolvedFullPath;
314 Scan (fullPathNoLastSlash, false, ref initialFds);
316 var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_nsec = (IntPtr)0 };
317 var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
318 var changes = CreateChangeList (ref initialFds);
323 numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
324 if (numEvents == -1) {
325 errno = Marshal.GetLastWin32Error ();
327 } while (numEvents == -1 && errno == EINTR);
329 if (numEvents == -1) {
330 var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", errno);
331 throw new IOException (errMsg);
335 kevent[] CreateChangeList (ref List<int> FdList)
337 if (FdList.Count == 0)
338 return emptyEventList;
340 var changes = new List<kevent> ();
341 foreach (int fd in FdList) {
342 var change = new kevent {
345 filter = EventFilter.Vnode,
346 flags = EventFlags.Add | EventFlags.Enable | EventFlags.Clear,
347 fflags = FilterFlags.VNodeDelete | FilterFlags.VNodeExtend |
348 FilterFlags.VNodeRename | FilterFlags.VNodeAttrib |
349 FilterFlags.VNodeLink | FilterFlags.VNodeRevoke |
350 FilterFlags.VNodeWrite,
355 changes.Add (change);
359 return changes.ToArray ();
364 var eventBuffer = new kevent[32];
365 var newFds = new List<int> ();
366 List<PathData> removeQueue = new List<PathData> ();
367 List<string> rescanQueue = new List<string> ();
371 while (!requestStop) {
372 var changes = CreateChangeList (ref newFds);
374 // We are calling an icall, so have to marshal manually
376 int ksize = Marshal.SizeOf<kevent> ();
377 var changesNative = Marshal.AllocHGlobal (ksize * changes.Length);
378 for (int i = 0; i < changes.Length; ++i)
379 Marshal.StructureToPtr (changes [i], changesNative + (i * ksize), false);
380 var eventBufferNative = Marshal.AllocHGlobal (ksize * eventBuffer.Length);
382 int numEvents = kevent_notimeout (ref conn, changesNative, changes.Length, eventBufferNative, eventBuffer.Length);
385 Marshal.FreeHGlobal (changesNative);
386 for (int i = 0; i < numEvents; ++i)
387 eventBuffer [i] = Marshal.PtrToStructure<kevent> (eventBufferNative + (i * ksize));
388 Marshal.FreeHGlobal (eventBufferNative);
390 if (numEvents == -1) {
391 // Stop () signals us to stop by closing the connection
394 int errno = Marshal.GetLastWin32Error ();
395 if (errno != EINTR && ++retries == 3)
396 throw new IOException (String.Format (
397 "persistent kevent() error, error code = '{0}'", errno));
403 for (var i = 0; i < numEvents; i++) {
404 var kevt = eventBuffer [i];
406 if (!fdsDict.ContainsKey ((int)kevt.ident))
407 // The event is for a file that was removed
410 var pathData = fdsDict [(int)kevt.ident];
412 if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
413 var errMsg = String.Format ("kevent() error watching path '{0}', error code = '{1}'", pathData.Path, kevt.data);
414 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (errMsg)));
418 if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke) {
419 if (pathData.Path == fullPathNoLastSlash)
420 // The root path is deleted; exit silently
423 removeQueue.Add (pathData);
427 if ((kevt.fflags & FilterFlags.VNodeRename) == FilterFlags.VNodeRename) {
428 UpdatePath (pathData);
431 if ((kevt.fflags & FilterFlags.VNodeWrite) == FilterFlags.VNodeWrite) {
432 if (pathData.IsDirectory) //TODO: Check if dirs trigger Changed events on .NET
433 rescanQueue.Add (pathData.Path);
435 PostEvent (FileAction.Modified, pathData.Path);
438 if ((kevt.fflags & FilterFlags.VNodeAttrib) == FilterFlags.VNodeAttrib || (kevt.fflags & FilterFlags.VNodeExtend) == FilterFlags.VNodeExtend)
439 PostEvent (FileAction.Modified, pathData.Path);
442 removeQueue.ForEach (Remove);
443 removeQueue.Clear ();
445 rescanQueue.ForEach (path => {
446 Scan (path, true, ref newFds);
448 rescanQueue.Clear ();
452 PathData Add (string path, bool postEvents, ref List<int> fds)
455 pathsDict.TryGetValue (path, out pathData);
457 if (pathData != null)
460 if (fdsDict.Count >= maxFds)
461 throw new IOException ("kqueue() FileSystemWatcher has reached the maximum number of files to watch.");
463 var fd = open (path, O_EVTONLY, 0);
466 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
467 "open() error while attempting to process path '{0}', error code = '{1}'", path, Marshal.GetLastWin32Error ()))));
474 var attrs = File.GetAttributes (path);
476 pathData = new PathData {
479 IsDirectory = (attrs & FileAttributes.Directory) == FileAttributes.Directory
482 pathsDict.Add (path, pathData);
483 fdsDict.Add (fd, pathData);
486 PostEvent (FileAction.Added, path);
489 } catch (Exception e) {
491 fsw.DispatchErrorEvents (new ErrorEventArgs (e));
497 void Remove (PathData pathData)
499 fdsDict.Remove (pathData.Fd);
500 pathsDict.Remove (pathData.Path);
502 PostEvent (FileAction.Removed, pathData.Path);
505 void RemoveTree (PathData pathData)
507 var toRemove = new List<PathData> ();
509 toRemove.Add (pathData);
511 if (pathData.IsDirectory) {
512 var prefix = pathData.Path + Path.DirectorySeparatorChar;
513 foreach (var path in pathsDict.Keys)
514 if (path.StartsWith (prefix)) {
515 toRemove.Add (pathsDict [path]);
518 toRemove.ForEach (Remove);
521 void UpdatePath (PathData pathData)
523 var newRoot = GetFilenameFromFd (pathData.Fd);
524 if (!newRoot.StartsWith (fullPathNoLastSlash)) { // moved outside of our watched path (so stop observing it)
525 RemoveTree (pathData);
529 var toRename = new List<PathData> ();
530 var oldRoot = pathData.Path;
532 toRename.Add (pathData);
534 if (pathData.IsDirectory) { // anything under the directory must have their paths updated
535 var prefix = oldRoot + Path.DirectorySeparatorChar;
536 foreach (var path in pathsDict.Keys)
537 if (path.StartsWith (prefix))
538 toRename.Add (pathsDict [path]);
541 foreach (var renaming in toRename) {
542 var oldPath = renaming.Path;
543 var newPath = newRoot + oldPath.Substring (oldRoot.Length);
545 renaming.Path = newPath;
546 pathsDict.Remove (oldPath);
548 // destination may exist in our records from a Created event, take care of it
549 if (pathsDict.ContainsKey (newPath)) {
550 var conflict = pathsDict [newPath];
551 if (GetFilenameFromFd (renaming.Fd) == GetFilenameFromFd (conflict.Fd))
554 UpdatePath (conflict);
557 pathsDict.Add (newPath, renaming);
560 PostEvent (FileAction.RenamedNewName, oldRoot, newRoot);
563 void Scan (string path, bool postEvents, ref List<int> fds)
568 var pathData = Add (path, postEvents, ref fds);
570 if (pathData == null)
573 if (!pathData.IsDirectory)
576 var dirsToProcess = new List<string> ();
577 dirsToProcess.Add (path);
579 while (dirsToProcess.Count > 0) {
580 var tmp = dirsToProcess [0];
581 dirsToProcess.RemoveAt (0);
583 var info = new DirectoryInfo (tmp);
584 FileSystemInfo[] fsInfos = null;
586 fsInfos = info.GetFileSystemInfos ();
588 } catch (IOException) {
589 // this can happen if the directory has been deleted already.
590 // that's okay, just keep processing the other dirs.
591 fsInfos = new FileSystemInfo[0];
594 foreach (var fsi in fsInfos) {
595 if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory && !fsw.IncludeSubdirectories)
598 if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && !fsw.Pattern.IsMatch (fsi.FullName))
601 var currentPathData = Add (fsi.FullName, postEvents, ref fds);
603 if (currentPathData != null && currentPathData.IsDirectory)
604 dirsToProcess.Add (fsi.FullName);
609 void PostEvent (FileAction action, string path, string newPath = null)
611 RenamedEventArgs renamed = null;
613 if (requestStop || action == 0)
617 string name = path.Substring (fullPathNoLastSlash.Length + 1);
619 // only post events that match filter pattern. check both old and new paths for renames
620 if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath)))
623 if (action == FileAction.RenamedNewName) {
624 string newName = newPath.Substring (fullPathNoLastSlash.Length + 1);
625 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, fsw.Path, newName, name);
628 fsw.DispatchEvents (action, name, ref renamed);
633 System.Threading.Monitor.PulseAll (fsw);
638 private string GetFilenameFromFd (int fd)
640 var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
642 if (fcntl (fd, F_GETPATH, sb) != -1) {
643 if (fixupPath != null)
644 sb.Replace (fixupPath, fullPathNoLastSlash, 0, fixupPath.Length); // see Setup()
646 return sb.ToString ();
648 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
649 "fcntl() error while attempting to get path for fd '{0}', error code = '{1}'", fd, Marshal.GetLastWin32Error ()))));
654 const int O_EVTONLY = 0x8000;
655 const int F_GETPATH = 50;
656 const int __DARWIN_MAXPATHLEN = 1024;
658 static readonly kevent[] emptyEventList = new System.IO.kevent[0];
659 int maxFds = Int32.MaxValue;
661 FileSystemWatcher fsw;
664 volatile bool requestStop = false;
665 AutoResetEvent startedEvent = new AutoResetEvent (false);
666 bool started = false;
667 bool inDispatch = false;
668 Exception exc = null;
669 object stateLock = new object ();
670 object connLock = new object ();
672 readonly Dictionary<string, PathData> pathsDict = new Dictionary<string, PathData> ();
673 readonly Dictionary<int, PathData> fdsDict = new Dictionary<int, PathData> ();
674 string fixupPath = null;
675 string fullPathNoLastSlash = null;
677 [DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
678 static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);
680 [DllImport ("libc", SetLastError=true)]
681 extern static int open (string path, int flags, int mode_t);
684 extern static int close (int fd);
686 [DllImport ("libc", SetLastError=true)]
687 extern static int kqueue ();
689 [DllImport ("libc", SetLastError=true)]
690 extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);
692 [MethodImplAttribute(MethodImplOptions.InternalCall)]
693 extern static int kevent_notimeout (ref int kq, IntPtr ev, int nchanges, IntPtr evtlist, int nevents);
696 class KeventWatcher : IFileWatcher
699 static KeventWatcher instance;
700 static Hashtable watches; // <FileSystemWatcher, KqueueMonitor>
702 private KeventWatcher ()
707 public static bool GetInstance (out IFileWatcher watcher)
709 if (failed == true) {
714 if (instance != null) {
719 watches = Hashtable.Synchronized (new Hashtable ());
728 instance = new KeventWatcher ();
733 public void StartDispatching (FileSystemWatcher fsw)
735 KqueueMonitor monitor;
737 if (watches.ContainsKey (fsw)) {
738 monitor = (KqueueMonitor)watches [fsw];
740 monitor = new KqueueMonitor (fsw);
741 watches.Add (fsw, monitor);
747 public void StopDispatching (FileSystemWatcher fsw)
749 KqueueMonitor monitor = (KqueueMonitor)watches [fsw];
757 extern static int close (int fd);
760 extern static int kqueue ();