@@ -51,8 +51,16 @@ mod tests;
51
51
///
52
52
/// Going above this limit will abort your program (although not
53
53
/// 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`.
54
59
const MAX_REFCOUNT : usize = ( isize:: MAX ) as usize ;
55
60
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
+
56
64
#[ cfg( not( sanitize = "thread" ) ) ]
57
65
macro_rules! acquire {
58
66
( $x: expr) => {
@@ -950,6 +958,9 @@ impl<T: ?Sized> Arc<T> {
950
958
continue ;
951
959
}
952
960
961
+ // We can't allow the refcount to increase much past `MAX_REFCOUNT`.
962
+ assert ! ( cur <= MAX_REFCOUNT , "{}" , INTERNAL_OVERFLOW_ERROR ) ;
963
+
953
964
// NOTE: this code currently ignores the possibility of overflow
954
965
// into usize::MAX; in general both Rc and Arc need to be adjusted
955
966
// to deal with overflow.
@@ -1373,6 +1384,11 @@ impl<T: ?Sized> Clone for Arc<T> {
1373
1384
// the worst already happened and we actually do overflow the `usize` counter. However, that
1374
1385
// requires the counter to grow from `isize::MAX` to `usize::MAX` between the increment
1375
1386
// 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.
1376
1392
if old_size > MAX_REFCOUNT {
1377
1393
abort ( ) ;
1378
1394
}
@@ -2001,9 +2017,7 @@ impl<T: ?Sized> Weak<T> {
2001
2017
return None ;
2002
2018
}
2003
2019
// 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 ) ;
2007
2021
Some ( n + 1 )
2008
2022
} )
2009
2023
. ok ( )
0 commit comments