aboutsummaryrefslogtreecommitdiffstats
path: root/main/musl/0001-fix-race-condition-in-file-locking.patch
blob: c6ec9a5e6eac2c3995a9f8903653a0ce118f13c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
From b6b592d75f694958424b8a4fbd909b52317651f1 Mon Sep 17 00:00:00 2001
From: Kaarle Ritvanen <kaarle.ritvanen@datakunkku.fi>
Date: Tue, 18 Sep 2018 01:10:32 +0300
Subject: [PATCH v2] 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.
---
 src/stdio/__lockfile.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/stdio/__lockfile.c b/src/stdio/__lockfile.c
index 2ff75d8a..0dcb2a42 100644
--- a/src/stdio/__lockfile.c
+++ b/src/stdio/__lockfile.c
@@ -8,13 +8,13 @@ int __lockfile(FILE *f)
 	int owner = f->lock, tid = __pthread_self()->tid;
 	if ((owner & ~MAYBE_WAITERS) == tid)
 		return 0;
-	for (;;) {
-		owner = a_cas(&f->lock, 0, tid);
-		if (!owner) return 1;
-		if (a_cas(&f->lock, owner, owner|MAYBE_WAITERS)==owner) break;
+	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);
 	}
-	while ((owner = a_cas(&f->lock, 0, tid|MAYBE_WAITERS)))
-		__futexwait(&f->lock, owner, 1);
 	return 1;
 }
 
-- 
2.14.4