Skip to content

Commit

Permalink
Fixed: SymWriter COM object is not released on exception (#955)
Browse files Browse the repository at this point in the history
* Fixed: SymWriter COM object is not released on exception

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.

* Code style

---------

Co-authored-by: Jb Evain <jb@evain.net>
  • Loading branch information
OskiKervinen-MF and jbevain authored Sep 25, 2024
1 parent 608fac6 commit 50292e7
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 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
5 changes: 5 additions & 0 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,6 +79,10 @@ public void DefineConstant2 (string name, object value, int sigToken)

public void Close ()
{
if (closed)
return;

closed = true;
writer.Close ();
Marshal.ReleaseComObject (writer);

Expand Down

0 comments on commit 50292e7

Please sign in to comment.