Line data Source code
1 : // Copyright (c) 2015-2020 The Bitcoin Core developers 2 : // Distributed under the MIT software license, see the accompanying 3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 : 5 : #include <sync.h> 6 : #include <test/util/setup_common.h> 7 : 8 : #include <boost/test/unit_test.hpp> 9 : 10 89 : BOOST_FIXTURE_TEST_SUITE(reverselock_tests, BasicTestingSetup) 11 : 12 95 : BOOST_AUTO_TEST_CASE(reverselock_basics) 13 : { 14 1 : Mutex mutex; 15 1 : WAIT_LOCK(mutex, lock); 16 : 17 1 : BOOST_CHECK(lock.owns_lock()); 18 : { 19 1 : REVERSE_LOCK(lock); 20 1 : BOOST_CHECK(!lock.owns_lock()); 21 1 : } 22 1 : BOOST_CHECK(lock.owns_lock()); 23 1 : } 24 : 25 95 : BOOST_AUTO_TEST_CASE(reverselock_multiple) 26 : { 27 1 : Mutex mutex2; 28 1 : Mutex mutex; 29 1 : WAIT_LOCK(mutex2, lock2); 30 1 : WAIT_LOCK(mutex, lock); 31 : 32 : // Make sure undoing two locks succeeds 33 : { 34 1 : REVERSE_LOCK(lock); 35 1 : BOOST_CHECK(!lock.owns_lock()); 36 1 : REVERSE_LOCK(lock2); 37 1 : BOOST_CHECK(!lock2.owns_lock()); 38 1 : } 39 1 : BOOST_CHECK(lock.owns_lock()); 40 1 : BOOST_CHECK(lock2.owns_lock()); 41 1 : } 42 : 43 95 : BOOST_AUTO_TEST_CASE(reverselock_errors) 44 : { 45 1 : Mutex mutex2; 46 1 : Mutex mutex; 47 1 : WAIT_LOCK(mutex2, lock2); 48 1 : WAIT_LOCK(mutex, lock); 49 : 50 : #ifdef DEBUG_LOCKORDER 51 : // Make sure trying to reverse lock a previous lock fails 52 : try { 53 : REVERSE_LOCK(lock2); 54 : BOOST_CHECK(false); // REVERSE_LOCK(lock2) succeeded 55 : } catch(...) { } 56 : BOOST_CHECK(lock2.owns_lock()); 57 : #endif 58 : 59 : // Make sure trying to reverse lock an unlocked lock fails 60 1 : lock.unlock(); 61 : 62 1 : BOOST_CHECK(!lock.owns_lock()); 63 : 64 : bool failed = false; 65 : try { 66 1 : REVERSE_LOCK(lock); 67 1 : } catch(...) { 68 : failed = true; 69 1 : } 70 : 71 1 : BOOST_CHECK(failed); 72 1 : BOOST_CHECK(!lock.owns_lock()); 73 : 74 : // Locking the original lock after it has been taken by a reverse lock 75 : // makes no sense. Ensure that the original lock no longer owns the lock 76 : // after giving it to a reverse one. 77 : 78 1 : lock.lock(); 79 1 : BOOST_CHECK(lock.owns_lock()); 80 : { 81 1 : REVERSE_LOCK(lock); 82 1 : BOOST_CHECK(!lock.owns_lock()); 83 1 : } 84 : 85 1 : BOOST_CHECK(failed); 86 1 : BOOST_CHECK(lock.owns_lock()); 87 2 : } 88 : 89 89 : BOOST_AUTO_TEST_SUITE_END()