Blame SOURCES/roslyn-57003-mono-named-mutex.patch

31d075
Index: tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs
31d075
===================================================================
31d075
--- tarball.6.0.1-rc2-6.0.100-rc2.orig/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs
31d075
+++ tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs
31d075
@@ -31,5 +31,24 @@ namespace Roslyn.Utilities
31d075
                 }
31d075
             }
31d075
         }
31d075
+        /// <summary>
31d075
+        /// Are we running on .NET 5 or later using the Mono runtime?
31d075
+        /// Will also return true when running on Mono itself; if necessary
31d075
+        /// we can use IsRunningOnMono to distinguish.
31d075
+        /// </summary>
31d075
+        public static bool IsUsingMonoRuntime
31d075
+        {
31d075
+            get
31d075
+            {
31d075
+                try
31d075
+                {
31d075
+                    return !(Type.GetType("Mono.RuntimeStructs", throwOnError: false) is null);
31d075
+                }
31d075
+                catch
31d075
+                {
31d075
+                    return false;
31d075
+                }
31d075
+            }
31d075
+        }
31d075
     }
31d075
 }
31d075
Index: tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs
31d075
===================================================================
31d075
--- tarball.6.0.1-rc2-6.0.100-rc2.orig/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs
31d075
+++ tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs
31d075
@@ -79,7 +79,7 @@ namespace Microsoft.CodeAnalysis.Compile
31d075
                 // to connect. When it fails it should fall back to in-proc
31d075
                 // compilation.
31d075
                 bool holdsMutex;
31d075
-                using (var serverMutex = new Mutex(initiallyOwned: true,
31d075
+                using (var serverMutex = BuildServerConnection.OpenOrCreateMutex(
31d075
                                                    name: BuildServerConnection.GetServerMutexName(_pipeName),
31d075
                                                    createdNew: out holdsMutex))
31d075
                 {
31d075
Index: tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs
31d075
===================================================================
31d075
--- tarball.6.0.1-rc2-6.0.100-rc2.orig/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs
31d075
+++ tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs
31d075
@@ -103,7 +103,7 @@ class Hello
31d075
             var mutexName = BuildServerConnection.GetServerMutexName(pipeName);
31d075
 
31d075
             bool holdsMutex;
31d075
-            using (var mutex = new Mutex(initiallyOwned: true,
31d075
+            using (var mutex = BuildServerConnection.OpenOrCreateMutex(
31d075
                                          name: mutexName,
31d075
                                          createdNew: out holdsMutex))
31d075
             {
31d075
@@ -119,7 +119,7 @@ class Hello
31d075
                 }
31d075
                 finally
31d075
                 {
31d075
-                    mutex.ReleaseMutex();
31d075
+                    mutex.Dispose();
31d075
                 }
31d075
             }
31d075
         }
31d075
Index: tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs
31d075
===================================================================
31d075
--- tarball.6.0.1-rc2-6.0.100-rc2.orig/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs
31d075
+++ tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs
31d075
@@ -304,7 +304,7 @@ End Module")
31d075
             var newTempDir = _tempDirectory.CreateDirectory(new string('a', 100 - _tempDirectory.Path.Length));
31d075
             await ApplyEnvironmentVariables(
31d075
                 new[] { new KeyValuePair<string, string>("TMPDIR", newTempDir.Path) },
31d075
-                async () =>
31d075
+                async () => await Task.Run(async () =>
31d075
             {
31d075
                 using var serverData = await ServerUtil.CreateServer(_logger);
31d075
                 var result = RunCommandLineCompiler(
31d075
@@ -317,7 +317,7 @@ End Module")
31d075
 
31d075
                 var listener = await serverData.Complete();
31d075
                 Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
31d075
-            });
31d075
+            }));
31d075
         }
31d075
 
31d075
         [Fact]
31d075
Index: tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs
31d075
===================================================================
31d075
--- tarball.6.0.1-rc2-6.0.100-rc2.orig/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs
31d075
+++ tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs
31d075
@@ -101,7 +101,7 @@ namespace Microsoft.CodeAnalysis.Compile
31d075
 
31d075
                     var thread = new Thread(() =>
31d075
                     {
31d075
-                        using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created))
31d075
+                        using (var mutex = BuildServerConnection.OpenOrCreateMutex(name: mutexName, createdNew: out created))
31d075
                         using (var stream = NamedPipeUtil.CreateServer(pipeName))
31d075
                         {
31d075
                             readyMre.Set();
31d075
@@ -112,7 +112,7 @@ namespace Microsoft.CodeAnalysis.Compile
31d075
                             stream.Close();
31d075
 
31d075
                             doneMre.WaitOne();
31d075
-                            mutex.ReleaseMutex();
31d075
+                            mutex.Dispose();
31d075
                         }
31d075
                     });
31d075
 
31d075
@@ -153,7 +153,7 @@ namespace Microsoft.CodeAnalysis.Compile
31d075
                     {
31d075
                         using (var stream = NamedPipeUtil.CreateServer(pipeName))
31d075
                         {
31d075
-                            var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created);
31d075
+                            var mutex = BuildServerConnection.OpenOrCreateMutex(name: mutexName, createdNew: out created);
31d075
                             readyMre.Set();
31d075
 
31d075
                             stream.WaitForConnection();
31d075
@@ -161,7 +161,6 @@ namespace Microsoft.CodeAnalysis.Compile
31d075
 
31d075
                             // Client is waiting for a response.  Close the mutex now.  Then close the connection 
31d075
                             // so the client gets an error.
31d075
-                            mutex.ReleaseMutex();
31d075
                             mutex.Dispose();
31d075
                             stream.Close();
31d075
 
31d075
Index: tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Shared/BuildServerConnection.cs
31d075
===================================================================
31d075
--- tarball.6.0.1-rc2-6.0.100-rc2.orig/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Shared/BuildServerConnection.cs
31d075
+++ tarball.6.0.1-rc2-6.0.100-rc2/src/roslyn.8e1779e16298415843e85029d8b52a1ae9bb4c30/src/Compilers/Shared/BuildServerConnection.cs
31d075
@@ -543,19 +543,10 @@ namespace Microsoft.CodeAnalysis.Command
31d075
         {
31d075
             try
31d075
             {
31d075
-                if (PlatformInformation.IsRunningOnMono)
31d075
+                if (PlatformInformation.IsUsingMonoRuntime)
31d075
                 {
31d075
-                    IServerMutex? mutex = null;
31d075
-                    bool createdNew = false;
31d075
-                    try
31d075
-                    {
31d075
-                        mutex = new ServerFileMutexPair(mutexName, false, out createdNew);
31d075
-                        return !createdNew;
31d075
-                    }
31d075
-                    finally
31d075
-                    {
31d075
-                        mutex?.Dispose();
31d075
-                    }
31d075
+                    using var mutex = new ServerFileMutex(mutexName);
31d075
+                    return !mutex.CouldLock();
31d075
                 }
31d075
                 else
31d075
                 {
31d075
@@ -572,9 +563,11 @@ namespace Microsoft.CodeAnalysis.Command
31d075
 
31d075
         internal static IServerMutex OpenOrCreateMutex(string name, out bool createdNew)
31d075
         {
31d075
-            if (PlatformInformation.IsRunningOnMono)
31d075
+            if (PlatformInformation.IsUsingMonoRuntime)
31d075
             {
31d075
-                return new ServerFileMutexPair(name, initiallyOwned: true, out createdNew);
31d075
+                var mutex = new ServerFileMutex(name);
31d075
+                createdNew = mutex.TryLock(0);
31d075
+                return mutex;
31d075
             }
31d075
             else
31d075
             {
31d075
@@ -648,19 +641,22 @@ namespace Microsoft.CodeAnalysis.Command
31d075
     }
31d075
 
31d075
     /// <summary>
31d075
-    /// An interprocess mutex abstraction based on OS advisory locking (FileStream.Lock/Unlock).
31d075
+    /// An interprocess mutex abstraction based on file sharing permission (FileShare.None).
31d075
     /// If multiple processes running as the same user create FileMutex instances with the same name,
31d075
     ///  those instances will all point to the same file somewhere in a selected temporary directory.
31d075
-    /// The TryLock method can be used to attempt to acquire the mutex, with Unlock or Dispose used to release.
31d075
+    /// The TryLock method can be used to attempt to acquire the mutex, with Dispose used to release.
31d075
+    /// The CouldLock method can be used to check whether an attempt to acquire the mutex would have
31d075
+    ///  succeeded at the current time, without actually acquiring it.
31d075
     /// Unlike Win32 named mutexes, there is no mechanism for detecting an abandoned mutex. The file
31d075
     ///  will simply revert to being unlocked but remain where it is.
31d075
     /// </summary>
31d075
-    internal sealed class FileMutex : IDisposable
31d075
+    internal sealed class ServerFileMutex : IServerMutex
31d075
     {
31d075
-        public readonly FileStream Stream;
31d075
+        public FileStream? Stream;
31d075
         public readonly string FilePath;
31d075
+        public readonly string GuardPath;
31d075
 
31d075
-        public bool IsLocked { get; private set; }
31d075
+        public bool IsDisposed { get; private set; }
31d075
 
31d075
         internal static string GetMutexDirectory()
31d075
         {
31d075
@@ -670,61 +666,176 @@ namespace Microsoft.CodeAnalysis.Command
31d075
             return result;
31d075
         }
31d075
 
31d075
-        public FileMutex(string name)
31d075
+        public ServerFileMutex(string name)
31d075
         {
31d075
-            FilePath = Path.Combine(GetMutexDirectory(), name);
31d075
-            Stream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
31d075
+            var mutexDirectory = GetMutexDirectory();
31d075
+            FilePath = Path.Combine(mutexDirectory, name);
31d075
+            GuardPath = Path.Combine(mutexDirectory, ".guard");
31d075
         }
31d075
 
31d075
-        public bool TryLock(int timeoutMs)
31d075
+        /// <summary>
31d075
+        /// Acquire the guard by opening the guard file with FileShare.None.  The guard must only ever
31d075
+        /// be held for very brief amounts of time, so we can simply spin until it is acquired.  The
31d075
+        /// guard must be released by disposing the FileStream returned from this routine.  Note the
31d075
+        /// guard file is never deleted; this is a leak, but only of a single file.
31d075
+        /// </summary>
31d075
+        internal FileStream LockGuard()
31d075
         {
31d075
-            if (IsLocked)
31d075
-                throw new InvalidOperationException("Lock already held");
31d075
-
31d075
-            var sw = Stopwatch.StartNew();
31d075
-            do
31d075
+            // We should be able to acquire the guard quickly.  Limit the number of retries anyway
31d075
+            // by some arbitrary bound to avoid getting hung up in a possibly infinite loop.
31d075
+            for (var i = 0; i < 100; i++)
31d075
             {
31d075
                 try
31d075
                 {
31d075
-                    Stream.Lock(0, 0);
31d075
-                    IsLocked = true;
31d075
-                    return true;
31d075
+                    return new FileStream(GuardPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
31d075
                 }
31d075
                 catch (IOException)
31d075
                 {
31d075
-                    // Lock currently held by someone else.
31d075
+                    // Guard currently held by someone else.
31d075
                     // We want to sleep for a short period of time to ensure that other processes
31d075
                     //  have an opportunity to finish their work and relinquish the lock.
31d075
                     // Spinning here (via Yield) would work but risks creating a priority
31d075
                     //  inversion if the lock is held by a lower-priority process.
31d075
                     Thread.Sleep(1);
31d075
                 }
31d075
+            }
31d075
+            // Handle unexpected failure to acquire guard as error.
31d075
+            throw new InvalidOperationException("Unable to acquire guard");
31d075
+        }
31d075
+
31d075
+        /// <summary>
31d075
+        /// Attempt to acquire the lock by opening the lock file with FileShare.None.  Sets "Stream"
31d075
+        /// and returns true if successful, returns false if the lock is already held by another
31d075
+        /// thread or process.  Guard must be held when calling this routine.
31d075
+        /// </summary>
31d075
+        internal bool TryLockFile()
31d075
+        {
31d075
+            Debug.Assert(Stream is null);
31d075
+            FileStream? stream = null;
31d075
+            try
31d075
+            {
31d075
+                stream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
31d075
+                // On some targets, the file locking used to implement FileShare.None may not be
31d075
+                // atomic with opening/creating the file.   This creates a race window when another
31d075
+                // thread holds the lock and is just about to unlock: we may be able to open the
31d075
+                // file here, then the other thread unlocks and deletes the file, and then we
31d075
+                // acquire the lock on our file handle - but the actual file is already deleted.
31d075
+                // To close this race, we verify that the file does in fact still exist now that
31d075
+                // we have successfull acquired the locked FileStream.   (Note that this check is
31d075
+                // safe because we cannot race with an other attempt to create the file since we
31d075
+                // hold the guard, and after the FileStream constructor returned we can no race
31d075
+                // with file deletion because we hold the lock.)
31d075
+                if (!File.Exists(FilePath))
31d075
+                {
31d075
+                    // To simplify the logic, we treat this case as "unable to acquire the lock"
31d075
+                    // because it we caught another process while it owned the lock and was just
31d075
+                    // giving it up.  If the caller retries, we'll likely acquire the lock then.
31d075
+                    stream.Dispose();
31d075
+                    return false;
31d075
+                }
31d075
+            }
31d075
+            catch (Exception)
31d075
+            {
31d075
+                stream?.Dispose();
31d075
+                return false;
31d075
+            }
31d075
+            Stream = stream;
31d075
+            return true;
31d075
+        }
31d075
+
31d075
+        /// <summary>
31d075
+        /// Release the lock by deleting the lock file and disposing "Stream".
31d075
+        /// </summary>
31d075
+        internal void UnlockFile()
31d075
+        {
31d075
+            Debug.Assert(Stream is not null);
31d075
+            try
31d075
+            {
31d075
+                // Delete the lock file while the stream is not yet disposed
31d075
+                // and we therefore still hold the FileShare.None exclusion.
31d075
+                // There may still be a race with another thread attempting a
31d075
+                // TryLockFile in parallel, but that is safely handled there.
31d075
+                File.Delete(FilePath);
31d075
+            }
31d075
+            finally
31d075
+            {
31d075
+                Stream.Dispose();
31d075
+                Stream = null;
31d075
+            }
31d075
+        }
31d075
+
31d075
+        public bool TryLock(int timeoutMs)
31d075
+        {
31d075
+            if (IsDisposed)
31d075
+                throw new ObjectDisposedException("Mutex");
31d075
+            if (Stream is not null)
31d075
+                throw new InvalidOperationException("Lock already held");
31d075
+
31d075
+            var sw = Stopwatch.StartNew();
31d075
+            do
31d075
+            {
31d075
+                try
31d075
+                {
31d075
+                    // Attempt to acquire lock while holding guard.
31d075
+                    using var guard = LockGuard();
31d075
+                    if (TryLockFile())
31d075
+                        return true;
31d075
+                }
31d075
                 catch (Exception)
31d075
                 {
31d075
-                    // Something else went wrong.
31d075
                     return false;
31d075
                 }
31d075
+
31d075
+                // See comment in LockGuard.
31d075
+                Thread.Sleep(1);
31d075
             } while (sw.ElapsedMilliseconds < timeoutMs);
31d075
 
31d075
             return false;
31d075
         }
31d075
 
31d075
-        public void Unlock()
31d075
+        public bool CouldLock()
31d075
         {
31d075
-            if (!IsLocked)
31d075
-                return;
31d075
-            Stream.Unlock(0, 0);
31d075
-            IsLocked = false;
31d075
+            if (IsDisposed)
31d075
+                return false;
31d075
+            if (Stream is not null)
31d075
+                return false;
31d075
+
31d075
+            try
31d075
+            {
31d075
+                // Attempt to acquire lock while holding guard, and if successful
31d075
+                // immediately unlock again while still holding guard.  This ensures
31d075
+                // no other thread will spuriously observe the lock as held due to
31d075
+                // the lock attempt here.
31d075
+                using var guard = LockGuard();
31d075
+                if (TryLockFile())
31d075
+                {
31d075
+                    UnlockFile();
31d075
+                    return true;
31d075
+                }
31d075
+            }
31d075
+            catch (Exception)
31d075
+            {
31d075
+                return false;
31d075
+            }
31d075
+
31d075
+            return false;
31d075
         }
31d075
 
31d075
         public void Dispose()
31d075
         {
31d075
-            var wasLocked = IsLocked;
31d075
-            if (wasLocked)
31d075
-                Unlock();
31d075
-            Stream.Dispose();
31d075
-            // We do not delete the lock file here because there is no reliable way to perform a
31d075
-            //  'delete if no one has the file open' operation atomically on *nix. This is a leak.
31d075
+            if (IsDisposed)
31d075
+                return;
31d075
+            IsDisposed = true;
31d075
+            if (Stream is not null)
31d075
+            {
31d075
+                try
31d075
+                {
31d075
+                    UnlockFile();
31d075
+                }
31d075
+                catch (Exception)
31d075
+                {
31d075
+                }
31d075
+            }
31d075
         }
31d075
     }
31d075
 
31d075
@@ -792,56 +903,4 @@ namespace Microsoft.CodeAnalysis.Command
31d075
             }
31d075
         }
31d075
     }
31d075
-
31d075
-    /// <summary>
31d075
-    /// Approximates a named mutex with 'locked', 'unlocked' and 'abandoned' states.
31d075
-    /// There is no reliable way to detect whether a mutex has been abandoned on some target platforms,
31d075
-    ///  so we use the AliveMutex to manually track whether the creator of a mutex is still running,
31d075
-    ///  while the HeldMutex represents the actual lock state of the mutex.
31d075
-    /// </summary>
31d075
-    internal sealed class ServerFileMutexPair : IServerMutex
31d075
-    {
31d075
-        public readonly FileMutex AliveMutex;
31d075
-        public readonly FileMutex HeldMutex;
31d075
-
31d075
-        public bool IsDisposed { get; private set; }
31d075
-
31d075
-        public ServerFileMutexPair(string mutexName, bool initiallyOwned, out bool createdNew)
31d075
-        {
31d075
-            AliveMutex = new FileMutex(mutexName + "-alive");
31d075
-            HeldMutex = new FileMutex(mutexName + "-held");
31d075
-            createdNew = AliveMutex.TryLock(0);
31d075
-            if (initiallyOwned && createdNew)
31d075
-            {
31d075
-                if (!TryLock(0))
31d075
-                    throw new Exception("Failed to lock mutex after creating it");
31d075
-            }
31d075
-        }
31d075
-
31d075
-        public bool TryLock(int timeoutMs)
31d075
-        {
31d075
-            if (IsDisposed)
31d075
-                throw new ObjectDisposedException("Mutex");
31d075
-            return HeldMutex.TryLock(timeoutMs);
31d075
-        }
31d075
-
31d075
-        public void Dispose()
31d075
-        {
31d075
-            if (IsDisposed)
31d075
-                return;
31d075
-            IsDisposed = true;
31d075
-
31d075
-            try
31d075
-            {
31d075
-                HeldMutex.Unlock();
31d075
-                AliveMutex.Unlock();
31d075
-            }
31d075
-            finally
31d075
-            {
31d075
-                AliveMutex.Dispose();
31d075
-                HeldMutex.Dispose();
31d075
-            }
31d075
-        }
31d075
-    }
31d075
-
31d075
 }