Skip to content

Commit 67898f8

Browse files
Rollup merge of #154526 - asder8215:no_threads_read_overflow, r=Mark-Simulacrum
Panic/return false on overflow in no_threads read/try_read impl As per discussion with Mark in #153555, it's possible for `no_threads` impl of `RwLock` to trigger a silent overflow on `RwLock::read`/`RwLock::try_read` if we try to acquire more than `isize::MAX` read locks. This PR adds an explicit panic/return false when our read lock counter is at `isize::MAX` for `RwLock::read`/`RwLock::try_read`; the message is similar to that of sys/sync/rwlock/futex.rs [here](https://github.com/rust-lang/rust/blob/fb27476aaf1012f1f6ace6306f9b990e0d989c31/library/std/src/sys/sync/rwlock/futex.rs#L143).
2 parents a660f77 + 1d7d435 commit 67898f8

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

library/std/src/sys/sync/rwlock/no_threads.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ impl RwLock {
1818
pub fn read(&self) {
1919
let m = self.mode.get();
2020
if m >= 0 {
21-
self.mode.set(m + 1);
21+
self.mode.set(m.checked_add(1).expect("rwlock overflowed read locks"));
2222
} else {
2323
rtabort!("rwlock locked for writing");
2424
}
@@ -28,6 +28,9 @@ impl RwLock {
2828
pub fn try_read(&self) -> bool {
2929
let m = self.mode.get();
3030
if m >= 0 {
31+
if m == isize::MAX {
32+
return false;
33+
}
3134
self.mode.set(m + 1);
3235
true
3336
} else {
@@ -56,16 +59,19 @@ impl RwLock {
5659

5760
#[inline]
5861
pub unsafe fn read_unlock(&self) {
59-
self.mode.set(self.mode.get() - 1);
62+
assert!(
63+
self.mode.replace(self.mode.get() - 1) > 0,
64+
"rwlock has not been locked for reading"
65+
);
6066
}
6167

6268
#[inline]
6369
pub unsafe fn write_unlock(&self) {
64-
assert_eq!(self.mode.replace(0), -1);
70+
assert_eq!(self.mode.replace(0), -1, "rwlock has not been locked for writing");
6571
}
6672

6773
#[inline]
6874
pub unsafe fn downgrade(&self) {
69-
assert_eq!(self.mode.replace(1), -1);
75+
assert_eq!(self.mode.replace(1), -1, "rwlock has not been locked for writing");
7076
}
7177
}

0 commit comments

Comments
 (0)