Skip to content

Commit 5e6dbfd

Browse files
committed
Merge bitcoin/bitcoin#32465: thread-safety: fix annotations with REVERSE_LOCK
a201a99 thread-safety: fix annotations with REVERSE_LOCK (Cory Fields) aeea5f0 thread-safety: add missing lock annotation (Cory Fields) 832c57a thread-safety: modernize thread safety macros (Cory Fields) Pull request description: This is one of several PRs to cleanup/modernize our threading primitives. While replacing the old critical section locks in the mining code with a `REVERSE_LOCK`, I noticed that our thread-safety annotations weren't hooked up to it. This PR gets `REVERSE_LOCK` working properly. Firstly it modernizes the attributes as-recommended by the [clang docs](https://clang.llvm.org/docs/ThreadSafetyAnalysis.html) (ctrl+f for `USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES`). There's a subtle difference between the old `unlock_function` and new `release_capability`, where our `reverse_lock` only works with the latter. I believe this is an upstream bug. I've [reported and attempted a fix here](llvm/llvm-project#139343), but either way it makes sense to me to modernize. The second adds a missing annotation pointed out by a fixed `REVERSE_LOCK`. Because clang's thread-safety annotations aren't passed through a reference to `UniqueLock` as one may assume (see [here](https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#no-alias-analysis) for more details), `cs_main` has to be listed explicitly as a requirement. The last commit actually fixes the `reverse_lock` by making it a `SCOPED_LOCK` and using the pattern [found in a clang test](https://github.com/llvm/llvm-project/blob/main/clang/test/SemaCXX/warn-thread-safety-analysis.cpp#L3126). Though the docs don't describe how to accomplish it, the functionality was added [in this commit](llvm/llvm-project@6a68efc). Due to aliasing issues (see link above), in order to work correctly, the original mutex has to be passed along with the lock, so all existing `REVERSE_LOCK`s have been updated. To ensure that the mutexes actually match, a runtime assertion is added. ACKs for top commit: fjahr: re-ACK a201a99 davidgumberg: reACK bitcoin/bitcoin@a201a99 theuni: Ok, done. Those last pushes can be ignored. ACKs on a201a99 are still fresh. ryanofsky: Code review ACK a201a99. Just dropping 0065b9673db5da2994b0b07c1d50ebfb19af39d0 and fixing incorrect `reverse_lock::lockname` initialization since last review. TheCharlatan: Re-ACK a201a99 Tree-SHA512: 2755fae0c41021976a1a633014a86d927f104ccbc8014c01c06dae89af363f92e5bc5d4276ad6d759302ac4679fe02a543758124d48318074db1c370989af7a7
2 parents 1be688f + a201a99 commit 5e6dbfd

File tree

6 files changed

+33
-23
lines changed

6 files changed

+33
-23
lines changed

src/node/interfaces.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ class NodeImpl : public Node
431431
};
432432

433433
// NOLINTNEXTLINE(misc-no-recursion)
434-
bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
434+
bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
435435
{
436436
if (!index) return false;
437437
if (block.m_hash) *block.m_hash = index->GetBlockHash();
@@ -443,7 +443,7 @@ bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<Rec
443443
if (block.m_locator) { *block.m_locator = GetLocator(index); }
444444
if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
445445
if (block.m_data) {
446-
REVERSE_LOCK(lock);
446+
REVERSE_LOCK(lock, cs_main);
447447
if (!blockman.ReadBlock(*block.m_data, *index)) block.m_data->SetNull();
448448
}
449449
block.found = true;

src/scheduler.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ void CScheduler::serviceQueue()
5656
{
5757
// Unlock before calling f, so it can reschedule itself or another task
5858
// without deadlocking:
59-
REVERSE_LOCK(lock);
59+
REVERSE_LOCK(lock, newTaskMutex);
6060
f();
6161
}
6262
} catch (...) {

src/sync.h

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <threadsafety.h> // IWYU pragma: export
1515
#include <util/macros.h>
1616

17+
#include <cassert>
1718
#include <condition_variable>
1819
#include <mutex>
1920
#include <string>
@@ -212,16 +213,19 @@ class SCOPED_LOCKABLE UniqueLock : public MutexType::unique_lock
212213
/**
213214
* An RAII-style reverse lock. Unlocks on construction and locks on destruction.
214215
*/
215-
class reverse_lock {
216+
class SCOPED_LOCKABLE reverse_lock {
216217
public:
217-
explicit reverse_lock(UniqueLock& _lock, const char* _guardname, const char* _file, int _line) : lock(_lock), file(_file), line(_line) {
218+
explicit reverse_lock(UniqueLock& _lock, const MutexType& mutex, const char* _guardname, const char* _file, int _line) UNLOCK_FUNCTION(mutex) : lock(_lock), file(_file), line(_line) {
219+
// Ensure that mutex passed back for thread-safety analysis is indeed the original
220+
assert(std::addressof(mutex) == lock.mutex());
221+
218222
CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
219223
lock.unlock();
220224
LeaveCritical();
221225
lock.swap(templock);
222226
}
223227

224-
~reverse_lock() {
228+
~reverse_lock() UNLOCK_FUNCTION() {
225229
templock.swap(lock);
226230
EnterCritical(lockname.c_str(), file.c_str(), line, lock.mutex());
227231
lock.lock();
@@ -240,7 +244,11 @@ class SCOPED_LOCKABLE UniqueLock : public MutexType::unique_lock
240244
friend class reverse_lock;
241245
};
242246

243-
#define REVERSE_LOCK(g) typename std::decay<decltype(g)>::type::reverse_lock UNIQUE_NAME(revlock)(g, #g, __FILE__, __LINE__)
247+
// clang's thread-safety analyzer is unable to deal with aliases of mutexes, so
248+
// it is not possible to use the lock's copy of the mutex for that purpose.
249+
// Instead, the original mutex needs to be passed back to the reverse_lock for
250+
// the sake of thread-safety analysis, but it is not actually used otherwise.
251+
#define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock UNIQUE_NAME(revlock)(g, cs, #g, __FILE__, __LINE__)
244252

245253
// When locking a Mutex, require negative capability to ensure the lock
246254
// is not already held

src/test/reverselock_tests.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ BOOST_AUTO_TEST_CASE(reverselock_basics)
1818

1919
BOOST_CHECK(lock.owns_lock());
2020
{
21-
REVERSE_LOCK(lock);
21+
REVERSE_LOCK(lock, mutex);
2222
BOOST_CHECK(!lock.owns_lock());
2323
}
2424
BOOST_CHECK(lock.owns_lock());
@@ -33,9 +33,9 @@ BOOST_AUTO_TEST_CASE(reverselock_multiple)
3333

3434
// Make sure undoing two locks succeeds
3535
{
36-
REVERSE_LOCK(lock);
36+
REVERSE_LOCK(lock, mutex);
3737
BOOST_CHECK(!lock.owns_lock());
38-
REVERSE_LOCK(lock2);
38+
REVERSE_LOCK(lock2, mutex2);
3939
BOOST_CHECK(!lock2.owns_lock());
4040
}
4141
BOOST_CHECK(lock.owns_lock());
@@ -54,7 +54,7 @@ BOOST_AUTO_TEST_CASE(reverselock_errors)
5454
g_debug_lockorder_abort = false;
5555

5656
// Make sure trying to reverse lock a previous lock fails
57-
BOOST_CHECK_EXCEPTION(REVERSE_LOCK(lock2), std::logic_error, HasReason("lock2 was not most recent critical section locked"));
57+
BOOST_CHECK_EXCEPTION(REVERSE_LOCK(lock2, mutex2), std::logic_error, HasReason("lock2 was not most recent critical section locked"));
5858
BOOST_CHECK(lock2.owns_lock());
5959

6060
g_debug_lockorder_abort = prev;
@@ -67,7 +67,7 @@ BOOST_AUTO_TEST_CASE(reverselock_errors)
6767

6868
bool failed = false;
6969
try {
70-
REVERSE_LOCK(lock);
70+
REVERSE_LOCK(lock, mutex);
7171
} catch(...) {
7272
failed = true;
7373
}
@@ -82,7 +82,7 @@ BOOST_AUTO_TEST_CASE(reverselock_errors)
8282
lock.lock();
8383
BOOST_CHECK(lock.owns_lock());
8484
{
85-
REVERSE_LOCK(lock);
85+
REVERSE_LOCK(lock, mutex);
8686
BOOST_CHECK(!lock.owns_lock());
8787
}
8888

src/threadsafety.h

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,24 @@
1515
// See https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
1616
// for documentation. The clang compiler can do advanced static analysis
1717
// of locking when given the -Wthread-safety option.
18-
#define LOCKABLE __attribute__((lockable))
18+
#define LOCKABLE __attribute__((capability("")))
1919
#define SCOPED_LOCKABLE __attribute__((scoped_lockable))
2020
#define GUARDED_BY(x) __attribute__((guarded_by(x)))
2121
#define PT_GUARDED_BY(x) __attribute__((pt_guarded_by(x)))
2222
#define ACQUIRED_AFTER(...) __attribute__((acquired_after(__VA_ARGS__)))
2323
#define ACQUIRED_BEFORE(...) __attribute__((acquired_before(__VA_ARGS__)))
24-
#define EXCLUSIVE_LOCK_FUNCTION(...) __attribute__((exclusive_lock_function(__VA_ARGS__)))
25-
#define SHARED_LOCK_FUNCTION(...) __attribute__((shared_lock_function(__VA_ARGS__)))
26-
#define EXCLUSIVE_TRYLOCK_FUNCTION(...) __attribute__((exclusive_trylock_function(__VA_ARGS__)))
27-
#define SHARED_TRYLOCK_FUNCTION(...) __attribute__((shared_trylock_function(__VA_ARGS__)))
28-
#define UNLOCK_FUNCTION(...) __attribute__((unlock_function(__VA_ARGS__)))
24+
#define EXCLUSIVE_LOCK_FUNCTION(...) __attribute__((acquire_capability(__VA_ARGS__)))
25+
#define SHARED_LOCK_FUNCTION(...) __attribute__((acquire_shared_capability(__VA_ARGS__)))
26+
#define EXCLUSIVE_TRYLOCK_FUNCTION(...) __attribute__((try_acquire_capability(__VA_ARGS__)))
27+
#define SHARED_TRYLOCK_FUNCTION(...) __attribute__((try_acquire_shared_capability(__VA_ARGS__)))
28+
#define UNLOCK_FUNCTION(...) __attribute__((release_capability(__VA_ARGS__)))
29+
#define SHARED_UNLOCK_FUNCTION(...) __attribute__((release_shared_capability(__VA_ARGS__)))
2930
#define LOCK_RETURNED(x) __attribute__((lock_returned(x)))
3031
#define LOCKS_EXCLUDED(...) __attribute__((locks_excluded(__VA_ARGS__)))
31-
#define EXCLUSIVE_LOCKS_REQUIRED(...) __attribute__((exclusive_locks_required(__VA_ARGS__)))
32-
#define SHARED_LOCKS_REQUIRED(...) __attribute__((shared_locks_required(__VA_ARGS__)))
32+
#define EXCLUSIVE_LOCKS_REQUIRED(...) __attribute__((requires_capability(__VA_ARGS__)))
33+
#define SHARED_LOCKS_REQUIRED(...) __attribute__((requires_shared_capability(__VA_ARGS__)))
3334
#define NO_THREAD_SAFETY_ANALYSIS __attribute__((no_thread_safety_analysis))
34-
#define ASSERT_EXCLUSIVE_LOCK(...) __attribute__((assert_exclusive_lock(__VA_ARGS__)))
35+
#define ASSERT_EXCLUSIVE_LOCK(...) __attribute__((assert_capability(__VA_ARGS__)))
3536
#else
3637
#define LOCKABLE
3738
#define SCOPED_LOCKABLE
@@ -44,6 +45,7 @@
4445
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
4546
#define SHARED_TRYLOCK_FUNCTION(...)
4647
#define UNLOCK_FUNCTION(...)
48+
#define SHARED_UNLOCK_FUNCTION(...)
4749
#define LOCK_RETURNED(x)
4850
#define LOCKS_EXCLUDED(...)
4951
#define EXCLUSIVE_LOCKS_REQUIRED(...)

src/validationinterface.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class ValidationSignalsImpl
8383
for (auto it = m_list.begin(); it != m_list.end();) {
8484
++it->count;
8585
{
86-
REVERSE_LOCK(lock);
86+
REVERSE_LOCK(lock, m_mutex);
8787
f(*it->callbacks);
8888
}
8989
it = --it->count ? std::next(it) : m_list.erase(it);

0 commit comments

Comments
 (0)