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

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