Bug 58423 - Race condition of metadata.c (mono_metadata_get_canonical_generic_inst)
Summary: Race condition of metadata.c (mono_metadata_get_canonical_generic_inst)
Alias: None
Product: Runtime
Classification: Mono
Component: General (show other bugs)
Version: unspecified
Hardware: PC Linux
: --- normal
Target Milestone: ---
Assignee: Armin
Depends on:
Reported: 2017-07-26 22:51 UTC by Armin
Modified: 2017-09-07 12:38 UTC (History)
4 users (show)

See Also:
Is this bug a regression?: ---
Last known good build:

Stack trace (23.28 KB, text/plain)
2017-07-26 22:51 UTC, Armin

Description Armin 2017-07-26 22:51:02 UTC
Created attachment 23830 [details]
Stack trace

If I understand this TSan report correctly, different threads execute `++next_generic_inst_id` (3 ops) "without" mutexes. Yes, there are mutexes but, as it seems, different ones are used. Shouldn't a global lock be used here instead of `mono_image_set_lock (set)` which is dependent on `set`?

I found this with commit 5d9d139e0ac4ecbf02c70cbce5d9a0c65a43faa4, highlighted the affected row with "!" and attached the corresponding stack trace with all the details.

static int next_generic_inst_id = 0;

MonoGenericInst * mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate) {
  // ...
  mono_image_set_lock (set);
  // ...
! ginst->id = ++next_generic_inst_id;
  // ...
  mono_image_set_unlock (set);
  // ...
Comment 1 Ludovic Henry 2017-07-28 17:42:30 UTC
Aleksey, does it matter if this `next_generic_inst_id` is not automatically incremented? If it does matter, should we replace `++next_generic_inst_id` with `InterlockedIncrement(&next_generic_inst_id)`?
Comment 2 Aleksey Kliger 2017-07-28 18:08:07 UTC
It looks to me like the id field in a MonoGenericInst is used in mono_generic_inst_equal_full as a way to short-circuit comparisons.

So yea in principle you could end up with two instantiations of the same class that are instantiated into two separate image sets at the same time but end up with the same id.  This will later cause mono_metadata_type_equal to return the wrong answer.
Comment 3 Armin 2017-07-29 11:59:01 UTC
Should I add `InterlockedIncrement` with a quick PR?
Comment 4 Ludovic Henry 2017-07-31 14:22:07 UTC
Armin, a fix for that wouldn't hurt IMO, so feel free to submit a PR, and add Aleksey and I as reviewers please. Thank you.
Comment 5 Ludovic Henry 2017-09-07 12:38:31 UTC
Fixed with 47535f557d18cf771436ac55578dfb165da0e399

Note You need to log in before you can comment on or make changes to this bug.