Luca Bacci <[email protected]> wrote:

> destroy() can run concurrently with unlock() as soon as unlock()
> sets the mutex state to UNLOCKED. In particular, destroy() doesn't
> have to wait for unlock() to return.
>
>   unlock()
>   {
>     PART A
>     SET STATE TO UNLOCKED
>     PART B    <----------- this can run in parallel with destroy()
>   }
>
> In the current implementation unlock() does two things:
>
>  1. Exchanges the mutex state with UNLOCKED.
>  2. If previous state was CONTENDED, signals the internal event.
>
> 2) can run concurrently with destroy(), so we have a potential
> use-after-free. To overcome that, make destroy() wait on the event.
>
> References:
>
>  1. https://lkml.org/lkml/2014/11/27/472
>  2. https://lwn.net/Articles/575460/
>  3. https://austingroupbugs.net/view.php?id=811

FYI, there is the exact same race condition in spinlock.c as well. TBH, this 
was one of my concerns with those changes.

If you look at other files, e.g. barrier.c, you'll see that they use global 
`spinlock_t` when accessing _any_ object. IMO, this is unacceptable as this 
slows down the entire implementation.

>    if (event != NULL) {
> +    /**
> +     * `Destroy` can run concurrently with `Unlock`. Wait on the event
> +     * to ensure that `Unlock` has finished working [1].
> +     */
> +    WaitForSingleObject (event, INFINITE);
>      CloseHandle (event);
>    }

Please use `_pthread_wait_for_single_object` (renamed to 
`winpthreads_wait_for_single_object` in time-related changes I just sent). Yes, 
it makes zero difference, but this would be consistent with the rest of the 
library.

> @@ -767,11 +782,22 @@ static int WinpthreadsNormalMutexTryLock 
> (WinpthreadsMutex *wMutex, BOOL exclusi
>  static int WinpthreadsNormalMutexUnlock (WinpthreadsMutex *wMutex) {
>    WinpthreadsNormalMutex *mutex = &wMutex->NormalMutex;
>
> +  LONG previousState;
> +
> +  previousState = InterlockedExchange (&mutex->LockState, Unlocked);
> +
>    /**
> -   * If `mutex->LockState` is `LockedWithBlocking`, then some other thread is
> +   * Please, note that code below can run concurrently with `Destroy` [1].
> +   */
> +
> +  /**
> +   * If `mutex->LockState` was `LockedWithBlocking`, then some other thread 
> is
>     * waiting for `mutex->Event` to become signaled.
>     */
> -  if (InterlockedExchange (&mutex->LockState, Unlocked) == 
> LockedWithBlocking) {
> +  if (previousState == LockedWithBlocking) {
> +    /**
> +     * This is safe because `Destroy` first waits on `mutex->Event`.
> +     */
>      if (!SetEvent (mutex->Event)) {
>        return EINVAL;
>      }

This and other changes to `*Unlock` seem to only document the fact that it can 
run concurrently with `*Destroy*. Can we simply adjust the comment above "if 
(InterlockedExchange ...)"?

- Kirill Makurin

_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to