]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Fix deadlock in debug iterator increment [PR108288]
authorJonathan Wakely <jwakely@redhat.com>
Thu, 5 Jan 2023 16:23:51 +0000 (16:23 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Fri, 6 Jan 2023 11:52:01 +0000 (11:52 +0000)
With -fno-elide-constructors the debug iterator post-increment and
post-decrement operators are susceptible to deadlock. They take a mutex
lock and then return a temporary, which also attempts to take a lock to
attach itself to the sequence. If the return value and *this happen to
collide and use the same mutex from the pool, then you get a deadlock
trying to lock a mutex that is already held by the current thread.

The solution is to construct the return value before taking the lock.
The copy constructor and pre-inc/pre-dec operators already manage locks
correctly, without deadlock, so just implement post-inc/post-dec in the
conventional way, taking a copy then modifying *this, then returning the
copy.

libstdc++-v3/ChangeLog:

PR libstdc++/108288
* include/debug/safe_iterator.h (_Safe_iterator::operator++(int))
(_Safe_iterator::operator--(int)): Do not hold lock around
construction of return value.

libstdc++-v3/include/debug/safe_iterator.h

index 117dc93de602e407c5fb573cffcc41774a5bb682..f9068eaf8d6e17c9d9a24cf3beb51c67a4097bd7 100644 (file)
@@ -761,12 +761,9 @@ namespace __gnu_debug
       _Safe_iterator
       operator++(int) _GLIBCXX_NOEXCEPT
       {
-       _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(),
-                             _M_message(__msg_bad_inc)
-                             ._M_iterator(*this, "this"));
-       __gnu_cxx::__scoped_lock __l(this->_M_get_mutex());
-       return _Safe_iterator(this->base()++, this->_M_sequence,
-                             _Attach_single());
+       _Safe_iterator __ret = *this;
+       ++*this;
+       return __ret;
       }
 
       // ------ Bidirectional iterator requirements ------
@@ -788,12 +785,9 @@ namespace __gnu_debug
       _Safe_iterator
       operator--(int) _GLIBCXX_NOEXCEPT
       {
-       _GLIBCXX_DEBUG_VERIFY(this->_M_decrementable(),
-                             _M_message(__msg_bad_dec)
-                             ._M_iterator(*this, "this"));
-       __gnu_cxx::__scoped_lock __l(this->_M_get_mutex());
-       return _Safe_iterator(this->base()--, this->_M_sequence,
-                             _Attach_single());
+       _Safe_iterator __ret = *this;
+       --*this;
+       return __ret;
       }
 
       // ------ Random access iterator requirements ------