[mono] Fix race during mono_image_storage_open #55201
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
mono_image_storage_tryaddref may abort when racing against a
mono_image_storage_dtor that already decremented the refcount.
This race triggered in some cases when building aspnetcore using a Mono-based dotnet host SDK. The problem is that
mono_image_storage_close
runs outside themono_images_storage_lock
(and this may be unavoidable due to lock ordering concerns). Therefore, we can have a refcount that was already decremented to zero, but beforemono_image_storage_dtor
finishes removing the object fromimages_storage_hash
, a parallelmono_image_storage_trypublish
may have retrieved it from there. In that case, themono_refcount_inc
call will abort.Fixed by detecting that case via
mono_refcount_tryinc
instead, and simply treating the object as if it had already been removed. It will in time actually get removed, either by the parallelmono_image_storage_dtor
, or else by theg_hash_table_insert
inmono_image_storage_trypublish
(which will safely replace it with the new object, andmono_image_storage_dtor
will then detect that and skip removal).