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

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