Files
semi-libc/src/stdio/__lockfile.c
T
Kaarle RitvanenandRich Felker 0db393d3a7 fix race condition in file locking
The condition occurs when
- thread #1 is holding the lock
- thread #2 is waiting for it on __futexwait
- thread #1 is about to release the lock and performs a_swap
- thread #3 enters the __lockfile function and manages to grab the lock
  before thread #1 calls __wake, resetting the MAYBE_WAITERS flag
- thread #1 calls __wake
- thread #2 wakes up but goes again to __futexwait as the lock is
  held by thread #3
- thread #3 releases the lock but does not call __wake as the
  MAYBE_WAITERS flag is not set

This condition results in thread #2 not being woken up. This patch fixes
the problem by making the woken up thread ensure that the flag is
properly set before going to sleep again.

Mainainer's note: This fixes a regression introduced in commit
c21f750727.
2018-09-18 11:43:49 -04:00

26 lines
585 B
C

#include "stdio_impl.h"
#include "pthread_impl.h"
#define MAYBE_WAITERS 0x40000000
int __lockfile(FILE *f)
{
int owner = f->lock, tid = __pthread_self()->tid;
if ((owner & ~MAYBE_WAITERS) == tid)
return 0;
owner = a_cas(&f->lock, 0, tid);
if (!owner) return 1;
while ((owner = a_cas(&f->lock, 0, tid|MAYBE_WAITERS))) {
if ((owner & MAYBE_WAITERS) ||
a_cas(&f->lock, owner, owner|MAYBE_WAITERS)==owner)
__futexwait(&f->lock, owner|MAYBE_WAITERS, 1);
}
return 1;
}
void __unlockfile(FILE *f)
{
if (a_swap(&f->lock, 0) & MAYBE_WAITERS)
__wake(&f->lock, 1, 1);
}