Skip to content

Commit 620544e

Browse files
committed
issue-108706-fix
1 parent 5f4e73c commit 620544e

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

library/alloc/src/sync.rs

+17-3
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,16 @@ mod tests;
5151
///
5252
/// Going above this limit will abort your program (although not
5353
/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
54+
/// Trying to go above it might call a `panic` (if not actually going above it).
55+
///
56+
/// This is a global invariant, and also applies when using a compare-exchange loop.
57+
///
58+
/// See comment in `Arc::clone`.
5459
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
5560

61+
/// The error in case either counter reaches above `MAX_REFCOUNT`, and we can `panic` safely.
62+
const INTERNAL_OVERFLOW_ERROR: &str = "Arc counter overflow";
63+
5664
#[cfg(not(sanitize = "thread"))]
5765
macro_rules! acquire {
5866
($x:expr) => {
@@ -950,6 +958,9 @@ impl<T: ?Sized> Arc<T> {
950958
continue;
951959
}
952960

961+
// We can't allow the refcount to increase much past `MAX_REFCOUNT`.
962+
assert!(cur <= MAX_REFCOUNT, "{}", INTERNAL_OVERFLOW_ERROR);
963+
953964
// NOTE: this code currently ignores the possibility of overflow
954965
// into usize::MAX; in general both Rc and Arc need to be adjusted
955966
// to deal with overflow.
@@ -1373,6 +1384,11 @@ impl<T: ?Sized> Clone for Arc<T> {
13731384
// the worst already happened and we actually do overflow the `usize` counter. However, that
13741385
// requires the counter to grow from `isize::MAX` to `usize::MAX` between the increment
13751386
// above and the `abort` below, which seems exceedingly unlikely.
1387+
//
1388+
// This is a global invariant, and also applies when using a compare-exchange loop to increment
1389+
// counters in other methods.
1390+
// Otherwise, the counter could be brought to an almost-overflow using a compare-exchange loop,
1391+
// and then overflow using a few `fetch_add`s.
13761392
if old_size > MAX_REFCOUNT {
13771393
abort();
13781394
}
@@ -2001,9 +2017,7 @@ impl<T: ?Sized> Weak<T> {
20012017
return None;
20022018
}
20032019
// See comments in `Arc::clone` for why we do this (for `mem::forget`).
2004-
if n > MAX_REFCOUNT {
2005-
abort();
2006-
}
2020+
assert!(n <= MAX_REFCOUNT, "{}", INTERNAL_OVERFLOW_ERROR);
20072021
Some(n + 1)
20082022
})
20092023
.ok()

0 commit comments

Comments
 (0)