Skip to content

Commit

Permalink
Fixed: SymWriter COM object is not released on exception
Browse files Browse the repository at this point in the history
The Problem:

Problem observed when being used in coverlet:
coverlet-coverage/coverlet#1471
If an exception caused `NativePdbWriter.Write` to never be
called, it would not call `SymWriter.Close`,
which in turn meant `Marshal.ReleaseComObject` was left uncalled.

The garbage collector will eventually destroy the object
and thereby release the COM object, but that happens non-deterministically.
The COM object is holding to a file handle, which prevents
other operations on the written file until it is released.
The result was random file access issues.

The Solution:

Luckily NativePdbWriter is IDisposable. I added a call to
`writer.Close` there. But now it could be called twice,
so I had to add a boolean to SymWriter to avoid releasing
everything twice.
  • Loading branch information
OskiKervinen-MF committed Jul 19, 2024
1 parent 8e1ae7b commit cb94cd9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
1 change: 1 addition & 0 deletions symbols/pdb/Mono.Cecil.Pdb/NativePdbWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ public void Write ()

public void Dispose ()
{
writer.Close ();
}
}

Expand Down
12 changes: 8 additions & 4 deletions symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ static extern int CoCreateInstance (

readonly ISymUnmanagedWriter2 writer;
readonly Collection<ISymUnmanagedDocumentWriter> documents;
bool closed = false;

public SymWriter ()
{
Expand Down Expand Up @@ -78,11 +79,14 @@ public void DefineConstant2 (string name, object value, int sigToken)

public void Close ()
{
writer.Close ();
Marshal.ReleaseComObject (writer);
if( !closed ) {
closed = true;
writer.Close ();
Marshal.ReleaseComObject ( writer );

foreach (var document in documents)
Marshal.ReleaseComObject (document);
foreach( var document in documents )
Marshal.ReleaseComObject ( document );
}
}

public void CloseMethod ()
Expand Down

0 comments on commit cb94cd9

Please sign in to comment.