Skip to content

Commit f58674a

Browse files
committed
Merge #13423: [net] Thread safety annotations in net_processing
1e3bcd2 [net_processing] Add thread safety annotations (Jesse Cohen) f393a53 Annotate AssertLockHeld() with ASSERT_CAPABILITY() for thread safety analysis (Jesse Cohen) Pull request description: (note that this depends on #13417) This commit fully annotates all globals in net_processing with clang thread safety annotations. Subsequent commits will begin transitioning some of this data away from cs_main into locks that are local to net_processing. Static thread safety analysis should it easier to verify correctness of that process. Tree-SHA512: b47aa410cb9ada21072370176aea9a74c575643fa1ee8cf1d43c8e28675eef17f33e5242ac422f840e8178e132ecb58412034c6334b68f1b57c686df80d4e8e2
2 parents 415f2bf + 1e3bcd2 commit f58674a

File tree

3 files changed

+50
-47
lines changed

3 files changed

+50
-47
lines changed

src/net_processing.cpp

Lines changed: 46 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans);
7676
void EraseOrphansFor(NodeId peer);
7777

7878
/** Increase a node's misbehavior score. */
79-
void Misbehaving(NodeId nodeid, int howmuch, const std::string& message="");
79+
void Misbehaving(NodeId nodeid, int howmuch, const std::string& message="") EXCLUSIVE_LOCKS_REQUIRED(cs_main);
8080

8181
/** Average delay between local address broadcasts in seconds. */
8282
static constexpr unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 60 * 60;
@@ -96,22 +96,20 @@ static constexpr unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
9696
// Internal stuff
9797
namespace {
9898
/** Number of nodes with fSyncStarted. */
99-
int nSyncStarted = 0;
99+
int nSyncStarted GUARDED_BY(cs_main) = 0;
100100

101101
/**
102102
* Sources of received blocks, saved to be able to send them reject
103-
* messages or ban them when processing happens afterwards. Protected by
104-
* cs_main.
103+
* messages or ban them when processing happens afterwards.
105104
* Set mapBlockSource[hash].second to false if the node should not be
106105
* punished if the block is invalid.
107106
*/
108-
std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
107+
std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
109108

110109
/**
111110
* Filter for transactions that were recently rejected by
112111
* AcceptToMemoryPool. These are not rerequested until the chain tip
113-
* changes, at which point the entire filter is reset. Protected by
114-
* cs_main.
112+
* changes, at which point the entire filter is reset.
115113
*
116114
* Without this filter we'd be re-requesting txs from each of our peers,
117115
* increasing bandwidth consumption considerably. For instance, with 100
@@ -127,38 +125,38 @@ namespace {
127125
*
128126
* Memory used: 1.3 MB
129127
*/
130-
std::unique_ptr<CRollingBloomFilter> recentRejects;
131-
uint256 hashRecentRejectsChainTip;
128+
std::unique_ptr<CRollingBloomFilter> recentRejects GUARDED_BY(cs_main);
129+
uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
132130

133-
/** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
131+
/** Blocks that are in flight, and that are in the queue to be downloaded. */
134132
struct QueuedBlock {
135133
uint256 hash;
136134
const CBlockIndex* pindex; //!< Optional.
137135
bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
138136
std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
139137
};
140-
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
138+
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight GUARDED_BY(cs_main);
141139

142140
/** Stack of nodes which we have set to announce using compact blocks */
143-
std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
141+
std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
144142

145143
/** Number of preferable block download peers. */
146-
int nPreferredDownload = 0;
144+
int nPreferredDownload GUARDED_BY(cs_main) = 0;
147145

148146
/** Number of peers from which we're downloading blocks. */
149-
int nPeersWithValidatedDownloads = 0;
147+
int nPeersWithValidatedDownloads GUARDED_BY(cs_main) = 0;
150148

151149
/** Number of outbound peers with m_chain_sync.m_protect. */
152-
int g_outbound_peers_with_protect_from_disconnect = 0;
150+
int g_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
153151

154152
/** When our tip was last updated. */
155153
std::atomic<int64_t> g_last_tip_update(0);
156154

157-
/** Relay map, protected by cs_main. */
155+
/** Relay map */
158156
typedef std::map<uint256, CTransactionRef> MapRelay;
159-
MapRelay mapRelay;
160-
/** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
161-
std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
157+
MapRelay mapRelay GUARDED_BY(cs_main);
158+
/** Expiration-time ordered list of (expire time, relay map entry) pairs. */
159+
std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration GUARDED_BY(cs_main);
162160

163161
std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
164162

@@ -302,18 +300,17 @@ struct CNodeState {
302300
}
303301
};
304302

305-
/** Map maintaining per-node state. Requires cs_main. */
306-
static std::map<NodeId, CNodeState> mapNodeState;
303+
/** Map maintaining per-node state. */
304+
static std::map<NodeId, CNodeState> mapNodeState GUARDED_BY(cs_main);
307305

308-
// Requires cs_main.
309-
static CNodeState *State(NodeId pnode) {
306+
static CNodeState *State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
310307
std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
311308
if (it == mapNodeState.end())
312309
return nullptr;
313310
return &it->second;
314311
}
315312

316-
static void UpdatePreferredDownload(CNode* node, CNodeState* state)
313+
static void UpdatePreferredDownload(CNode* node, CNodeState* state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
317314
{
318315
nPreferredDownload -= state->fPreferredDownload;
319316

@@ -344,10 +341,9 @@ static void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime)
344341
}
345342
}
346343

347-
// Requires cs_main.
348344
// Returns a bool indicating whether we requested this block.
349345
// Also used if a block was /not/ received and timed out or started with another peer
350-
static bool MarkBlockAsReceived(const uint256& hash) {
346+
static bool MarkBlockAsReceived(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
351347
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
352348
if (itInFlight != mapBlocksInFlight.end()) {
353349
CNodeState *state = State(itInFlight->second.first);
@@ -370,10 +366,9 @@ static bool MarkBlockAsReceived(const uint256& hash) {
370366
return false;
371367
}
372368

373-
// Requires cs_main.
374369
// returns false, still setting pit, if the block was already in flight from the same peer
375370
// pit will only be valid as long as the same cs_main lock is being held
376-
static bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) {
371+
static bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
377372
CNodeState *state = State(nodeid);
378373
assert(state != nullptr);
379374

@@ -407,7 +402,7 @@ static bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlock
407402
}
408403

409404
/** Check whether the last unknown block a peer advertised is not yet known. */
410-
static void ProcessBlockAvailability(NodeId nodeid) {
405+
static void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
411406
CNodeState *state = State(nodeid);
412407
assert(state != nullptr);
413408

@@ -423,7 +418,7 @@ static void ProcessBlockAvailability(NodeId nodeid) {
423418
}
424419

425420
/** Update tracking information about which blocks a peer is assumed to have. */
426-
static void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
421+
static void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
427422
CNodeState *state = State(nodeid);
428423
assert(state != nullptr);
429424

@@ -447,7 +442,8 @@ static void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
447442
* lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by
448443
* removing the first element if necessary.
449444
*/
450-
static void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) {
445+
static void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman)
446+
{
451447
AssertLockHeld(cs_main);
452448
CNodeState* nodestate = State(nodeid);
453449
if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
@@ -463,11 +459,13 @@ static void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connma
463459
}
464460
}
465461
connman->ForNode(nodeid, [connman](CNode* pfrom){
462+
AssertLockHeld(cs_main);
466463
uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
467464
if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
468465
// As per BIP152, we only get 3 of our peers to announce
469466
// blocks using compact encodings.
470467
connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){
468+
AssertLockHeld(cs_main);
471469
connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
472470
return true;
473471
});
@@ -480,7 +478,7 @@ static void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connma
480478
}
481479
}
482480

483-
static bool TipMayBeStale(const Consensus::Params &consensusParams)
481+
static bool TipMayBeStale(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
484482
{
485483
AssertLockHeld(cs_main);
486484
if (g_last_tip_update == 0) {
@@ -489,14 +487,12 @@ static bool TipMayBeStale(const Consensus::Params &consensusParams)
489487
return g_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
490488
}
491489

492-
// Requires cs_main
493-
static bool CanDirectFetch(const Consensus::Params &consensusParams)
490+
static bool CanDirectFetch(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
494491
{
495492
return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
496493
}
497494

498-
// Requires cs_main
499-
static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
495+
static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
500496
{
501497
if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
502498
return true;
@@ -507,7 +503,8 @@ static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
507503

508504
/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
509505
* at most count entries. */
510-
static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
506+
static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
507+
{
511508
if (count == 0)
512509
return;
513510

@@ -797,10 +794,8 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
797794

798795
/**
799796
* Mark a misbehaving peer to be banned depending upon the value of `-banscore`.
800-
*
801-
* Requires cs_main.
802797
*/
803-
void Misbehaving(NodeId pnode, int howmuch, const std::string& message)
798+
void Misbehaving(NodeId pnode, int howmuch, const std::string& message) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
804799
{
805800
if (howmuch == 0)
806801
return;
@@ -898,10 +893,10 @@ void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pb
898893

899894
// All of the following cache a recent block, and are protected by cs_most_recent_block
900895
static CCriticalSection cs_most_recent_block;
901-
static std::shared_ptr<const CBlock> most_recent_block;
902-
static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
903-
static uint256 most_recent_block_hash;
904-
static bool fWitnessesPresentInMostRecentCompactBlock;
896+
static std::shared_ptr<const CBlock> most_recent_block GUARDED_BY(cs_most_recent_block);
897+
static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block GUARDED_BY(cs_most_recent_block);
898+
static uint256 most_recent_block_hash GUARDED_BY(cs_most_recent_block);
899+
static bool fWitnessesPresentInMostRecentCompactBlock GUARDED_BY(cs_most_recent_block);
905900

906901
/**
907902
* Maintain state about the best-seen block and fast-announce a compact block
@@ -930,6 +925,8 @@ void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std:
930925
}
931926

932927
connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
928+
AssertLockHeld(cs_main);
929+
933930
// TODO: Avoid the repeated-serialization here
934931
if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
935932
return;
@@ -1327,7 +1324,7 @@ void static ProcessGetData(CNode* pfrom, const CChainParams& chainparams, CConnm
13271324
}
13281325
}
13291326

1330-
static uint32_t GetFetchFlags(CNode* pfrom) {
1327+
static uint32_t GetFetchFlags(CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
13311328
uint32_t nFetchFlags = 0;
13321329
if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
13331330
nFetchFlags |= MSG_WITNESS_FLAG;
@@ -3160,6 +3157,8 @@ void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
31603157
LOCK(cs_main);
31613158

31623159
connman->ForEachNode([&](CNode* pnode) {
3160+
AssertLockHeld(cs_main);
3161+
31633162
// Ignore non-outbound peers, or nodes marked for disconnect already
31643163
if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return;
31653164
CNodeState *state = State(pnode->GetId());
@@ -3173,6 +3172,8 @@ void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
31733172
});
31743173
if (worst_peer != -1) {
31753174
bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) {
3175+
AssertLockHeld(cs_main);
3176+
31763177
// Only disconnect a peer that has been connected to us for
31773178
// some reasonable fraction of our check-frequency, to give
31783179
// it time for new information to have arrived.

src/sync.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,13 @@ class LOCKABLE AnnotatedMixin : public PARENT
7474
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
7575
void LeaveCritical();
7676
std::string LocksHeld();
77-
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs);
77+
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) ASSERT_EXCLUSIVE_LOCK(cs);
7878
void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs);
7979
void DeleteLock(void* cs);
8080
#else
8181
void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {}
8282
void static inline LeaveCritical() {}
83-
void static inline AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) {}
83+
void static inline AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) ASSERT_EXCLUSIVE_LOCK(cs) {}
8484
void static inline AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) {}
8585
void static inline DeleteLock(void* cs) {}
8686
#endif

src/threadsafety.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#define EXCLUSIVE_LOCKS_REQUIRED(...) __attribute__((exclusive_locks_required(__VA_ARGS__)))
3232
#define SHARED_LOCKS_REQUIRED(...) __attribute__((shared_locks_required(__VA_ARGS__)))
3333
#define NO_THREAD_SAFETY_ANALYSIS __attribute__((no_thread_safety_analysis))
34+
#define ASSERT_EXCLUSIVE_LOCK(...) __attribute((assert_exclusive_lock(__VA_ARGS__)))
3435
#else
3536
#define LOCKABLE
3637
#define SCOPED_LOCKABLE
@@ -50,6 +51,7 @@
5051
#define EXCLUSIVE_LOCKS_REQUIRED(...)
5152
#define SHARED_LOCKS_REQUIRED(...)
5253
#define NO_THREAD_SAFETY_ANALYSIS
54+
#define ASSERT_EXCLUSIVE_LOCK(...)
5355
#endif // __GNUC__
5456

5557
#endif // BITCOIN_THREADSAFETY_H

0 commit comments

Comments
 (0)