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

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