Merge pull request #2803 from BrzVlad/feature-conc-pinned-scan
[mono.git] / mcs / class / System / System.IO / KeventWatcher.cs
index 7ead35f82e26fef53a04061def19ab708b158b5b..7570bd68915a6bae106f07711448e995918d1d32 100644 (file)
@@ -150,7 +150,7 @@ namespace System.IO {
        [StructLayout(LayoutKind.Sequential)]
        struct timespec {
                public IntPtr tv_sec;
-               public IntPtr tv_usec;
+               public IntPtr tv_nsec;
        }
 
        class PathData
@@ -162,6 +162,8 @@ namespace System.IO {
 
        class KqueueMonitor : IDisposable
        {
+               static bool initialized;
+               
                public int Connection
                {
                        get { return conn; }
@@ -171,6 +173,13 @@ namespace System.IO {
                {
                        this.fsw = fsw;
                        this.conn = -1;
+                       if (!initialized){
+                               int t;
+                               initialized = true;
+                               var maxenv = Environment.GetEnvironmentVariable ("MONO_DARWIN_WATCHER_MAXFDS");
+                               if (maxenv != null && Int32.TryParse (maxenv, out t))
+                                       maxFds = t;
+                       }
                }
 
                public void Dispose ()
@@ -274,7 +283,6 @@ namespace System.IO {
                                        started = false;
                                        inDispatch = false;
                                        fsw.EnableRaisingEvents = false;
-                                       throw exc;
                                }
                                if (exc != null)
                                        fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
@@ -292,11 +300,14 @@ namespace System.IO {
                        else
                                fullPathNoLastSlash = fsw.FullPath;
                                
-                       // GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
+                       // realpath() returns the *realpath* which can be different than fsw.FullPath because symlinks.
                        // If so, introduce a fixup step.
-                       int fd = open (fullPathNoLastSlash, O_EVTONLY, 0);
-                       var resolvedFullPath = GetFilenameFromFd (fd);
-                       close (fd);
+                       var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
+                       if (realpath(fsw.FullPath, sb) == IntPtr.Zero) {
+                               var errMsg = String.Format ("realpath({0}) failed, error code = '{1}'", fsw.FullPath, Marshal.GetLastWin32Error ());
+                               throw new IOException (errMsg);
+                       }
+                       var resolvedFullPath = sb.ToString();
 
                        if (resolvedFullPath != fullPathNoLastSlash)
                                fixupPath = resolvedFullPath;
@@ -305,14 +316,21 @@ namespace System.IO {
 
                        Scan (fullPathNoLastSlash, false, ref initialFds);
 
-                       var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_usec = (IntPtr)0 };
+                       var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_nsec = (IntPtr)0 };
                        var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
                        var changes = CreateChangeList (ref initialFds);
 
-                       int numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
+                       int numEvents;
+                       int errno = 0;
+                       do {
+                               numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
+                               if (numEvents == -1) {
+                                       errno = Marshal.GetLastWin32Error ();
+                               }
+                       } while (numEvents == -1 && errno == EINTR);
 
                        if (numEvents == -1) {
-                               var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", Marshal.GetLastWin32Error ());
+                               var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", errno);
                                throw new IOException (errMsg);
                        }
                }
@@ -356,23 +374,42 @@ namespace System.IO {
                        while (!requestStop) {
                                var changes = CreateChangeList (ref newFds);
 
-                               int numEvents = kevent_notimeout (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, IntPtr.Zero);
+                               // We are calling an icall, so have to marshal manually
+                               // Marshal in
+                               int ksize = Marshal.SizeOf<kevent> ();
+                               var changesNative = Marshal.AllocHGlobal (ksize * changes.Length);
+                               for (int i = 0; i < changes.Length; ++i)
+                                       Marshal.StructureToPtr (changes [i], changesNative + (i * ksize), false);
+                               var eventBufferNative = Marshal.AllocHGlobal (ksize * eventBuffer.Length);
+
+                               int numEvents = kevent_notimeout (ref conn, changesNative, changes.Length, eventBufferNative, eventBuffer.Length);
+
+                               // Marshal out
+                               Marshal.FreeHGlobal (changesNative);
+                               for (int i = 0; i < numEvents; ++i)
+                                       eventBuffer [i] = Marshal.PtrToStructure<kevent> (eventBufferNative + (i * ksize));
+                               Marshal.FreeHGlobal (eventBufferNative);
 
                                if (numEvents == -1) {
                                        // Stop () signals us to stop by closing the connection
                                        if (requestStop)
                                                break;
-                                       if (++retries == 3)
+                                       int errno = Marshal.GetLastWin32Error ();
+                                       if (errno != EINTR && ++retries == 3)
                                                throw new IOException (String.Format (
-                                                       "persistent kevent() error, error code = '{0}'", Marshal.GetLastWin32Error ()));
+                                                       "persistent kevent() error, error code = '{0}'", errno));
 
                                        continue;
                                }
-
                                retries = 0;
 
                                for (var i = 0; i < numEvents; i++) {
                                        var kevt = eventBuffer [i];
+
+                                       if (!fdsDict.ContainsKey ((int)kevt.ident))
+                                               // The event is for a file that was removed
+                                               continue;
+
                                        var pathData = fdsDict [(int)kevt.ident];
 
                                        if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
@@ -382,6 +419,10 @@ namespace System.IO {
                                        }
                                                
                                        if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke) {
+                                               if (pathData.Path == fullPathNoLastSlash)
+                                                       // The root path is deleted; exit silently
+                                                       return;
+                                                               
                                                removeQueue.Add (pathData);
                                                continue;
                                        }
@@ -420,7 +461,7 @@ namespace System.IO {
                                return pathData;
 
                        if (fdsDict.Count >= maxFds)
-                               throw new IOException ("kqueue() FileSystemWatcher has reached the maximum nunmber of files to watch."); 
+                               throw new IOException ("kqueue() FileSystemWatcher has reached the maximum number of files to watch."); 
 
                        var fd = open (path, O_EVTONLY, 0);
 
@@ -616,8 +657,9 @@ namespace System.IO {
                const int O_EVTONLY = 0x8000;
                const int F_GETPATH = 50;
                const int __DARWIN_MAXPATHLEN = 1024;
+               const int EINTR = 4;
                static readonly kevent[] emptyEventList = new System.IO.kevent[0];
-               const int maxFds = 200;
+               int maxFds = Int32.MaxValue;
 
                FileSystemWatcher fsw;
                int conn;
@@ -635,23 +677,26 @@ namespace System.IO {
                string fixupPath = null;
                string fullPathNoLastSlash = null;
 
-               [DllImport ("libc", EntryPoint="fcntl", CharSet=CharSet.Auto, SetLastError=true)]
+               [DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
                static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);
 
-               [DllImport ("libc")]
+               [DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
+               static extern IntPtr realpath (string pathname, StringBuilder sb);
+
+               [DllImport ("libc", SetLastError=true)]
                extern static int open (string path, int flags, int mode_t);
 
                [DllImport ("libc")]
                extern static int close (int fd);
 
-               [DllImport ("libc")]
+               [DllImport ("libc", SetLastError=true)]
                extern static int kqueue ();
 
-               [DllImport ("libc")]
+               [DllImport ("libc", SetLastError=true)]
                extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);
 
-               [DllImport ("libc", EntryPoint="kevent")]
-               extern static int kevent_notimeout (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, IntPtr ptr);
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               extern static int kevent_notimeout (ref int kq, IntPtr ev, int nchanges, IntPtr evtlist, int nevents);
        }
 
        class KeventWatcher : IFileWatcher