jbevain / cecil

Cecil is a library to inspect, modify and create .NET programs and libraries.
MIT License
2.76k stars 627 forks source link

Is this locking correct in ModuleDefinition? #951

Open omajid opened 5 months ago

omajid commented 5 months ago

https://github.com/jbevain/cecil/blob/8e1ae7b4ea67ccc38cb8db3ded6802643109ffd7/Mono.Cecil/ModuleDefinition.cs#L387-L393

It seems like this sequence of events might be possible, resulting in creation of an DefaultAssemblyResolver instance that's never disposed:

  1. Thread 1 sees assembly_resolver.value == null
  2. Thread 2 sees assembly_resolver.value == null
  3. Thread 1 enters the lock block and sets assembly_resolver to a new instance
  4. Thread 2 enters the lock block and re-sets assembly_resolver to a new instance

The instance in step 3 is now lost and was never disposed.

ltrzesniewski commented 5 months ago

I agree, using if/lock/if would be appropriate as it's a standard pattern, or just changing = to ??= in this case.