Skip to content

Commit fe1357a

Browse files
author
MarcoFalke
committed
Merge #18881: Prevent UB in DeleteLock() function
90eb027 doc: Add and fix comments about never destroyed objects (Hennadii Stepanov) 26c093a Replace thread_local g_lockstack with a mutex-protected map (Hennadii Stepanov) 58e6881 refactor: Refactor duplicated code into LockHeld() (Hennadii Stepanov) f511f61 refactor: Add LockPair type alias (Hennadii Stepanov) 8d8921a refactor: Add LockStackItem type alias (Hennadii Stepanov) 458992b Prevent UB in DeleteLock() function (Hennadii Stepanov) Pull request description: Tracking our instrumented mutexes (`Mutex` and `RecursiveMutex` types) requires that all involved objects should not be destroyed until after their last use. On master (ec79b5f) we have two problems related to the object destroying order: - the function-local `static` `lockdata` object that is destroyed at [program exit](https://en.cppreference.com/w/cpp/utility/program/exit) - the `thread_local` `g_lockstack` that is destroyed at [thread exit](https://en.cppreference.com/w/cpp/language/destructor) Both cases could cause UB at program exit in so far as mutexes are used in other static object destructors. Fix #18824 ACKs for top commit: MarcoFalke: re-ACK 90eb027, only change is new doc commit 👠 ryanofsky: Code review ACK 90eb027 because all the changes look correct and safe. But I don't know the purpose of commit 26c093a "Replace thread_local g_lockstack with a mutex-protected map (5/6)." It seems like it could have a bad impact on debug performance, and the commit message and PR description don't give a reason for the change. Tree-SHA512: 99f29157fd1278994e3f6eebccedfd9dae540450f5f8b980518345a89d56b635f943a85b20864cef087027fd0fcdb4880b659ef59bfe5626d110452ae22031c6
2 parents 13397dc + 90eb027 commit fe1357a

File tree

2 files changed

+75
-50
lines changed

2 files changed

+75
-50
lines changed

src/logging.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ BCLog::Logger& LogInstance()
2222
* access the logger. When the shutdown sequence is fully audited and tested,
2323
* explicit destruction of these objects can be implemented by changing this
2424
* from a raw pointer to a std::unique_ptr.
25-
* Since the destructor is never called, the logger and all its members must
26-
* have a trivial destructor.
25+
* Since the ~Logger() destructor is never called, the Logger class and all
26+
* its subclasses must have implicitly-defined destructors.
2727
*
2828
* This method of initialization was originally introduced in
2929
* ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.

src/sync.cpp

Lines changed: 73 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,19 @@
77
#endif
88

99
#include <sync.h>
10-
#include <tinyformat.h>
1110

1211
#include <logging.h>
12+
#include <tinyformat.h>
1313
#include <util/strencodings.h>
1414
#include <util/threadnames.h>
1515

1616
#include <map>
1717
#include <set>
1818
#include <system_error>
19+
#include <thread>
20+
#include <unordered_map>
21+
#include <utility>
22+
#include <vector>
1923

2024
#ifdef DEBUG_LOCKCONTENTION
2125
#if !defined(HAVE_THREAD_LOCAL)
@@ -73,35 +77,35 @@ struct CLockLocation {
7377
int sourceLine;
7478
};
7579

76-
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
77-
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
78-
typedef std::set<std::pair<void*, void*> > InvLockOrders;
80+
using LockStackItem = std::pair<void*, CLockLocation>;
81+
using LockStack = std::vector<LockStackItem>;
82+
using LockStacks = std::unordered_map<std::thread::id, LockStack>;
7983

80-
struct LockData {
81-
// Very ugly hack: as the global constructs and destructors run single
82-
// threaded, we use this boolean to know whether LockData still exists,
83-
// as DeleteLock can get called by global RecursiveMutex destructors
84-
// after LockData disappears.
85-
bool available;
86-
LockData() : available(true) {}
87-
~LockData() { available = false; }
84+
using LockPair = std::pair<void*, void*>;
85+
using LockOrders = std::map<LockPair, LockStack>;
86+
using InvLockOrders = std::set<LockPair>;
8887

88+
struct LockData {
89+
LockStacks m_lock_stacks;
8990
LockOrders lockorders;
9091
InvLockOrders invlockorders;
9192
std::mutex dd_mutex;
9293
};
94+
9395
LockData& GetLockData() {
94-
static LockData lockdata;
95-
return lockdata;
96+
// This approach guarantees that the object is not destroyed until after its last use.
97+
// The operating system automatically reclaims all the memory in a program's heap when that program exits.
98+
// Since the ~LockData() destructor is never called, the LockData class and all
99+
// its subclasses must have implicitly-defined destructors.
100+
static LockData& lock_data = *new LockData();
101+
return lock_data;
96102
}
97103

98-
static thread_local LockStack g_lockstack;
99-
100-
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
104+
static void potential_deadlock_detected(const LockPair& mismatch, const LockStack& s1, const LockStack& s2)
101105
{
102106
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
103107
LogPrintf("Previous lock order was:\n");
104-
for (const std::pair<void*, CLockLocation> & i : s2) {
108+
for (const LockStackItem& i : s2) {
105109
if (i.first == mismatch.first) {
106110
LogPrintf(" (1)"); /* Continued */
107111
}
@@ -111,7 +115,7 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch,
111115
LogPrintf(" %s\n", i.second.ToString());
112116
}
113117
LogPrintf("Current lock order is:\n");
114-
for (const std::pair<void*, CLockLocation> & i : s1) {
118+
for (const LockStackItem& i : s1) {
115119
if (i.first == mismatch.first) {
116120
LogPrintf(" (1)"); /* Continued */
117121
}
@@ -132,18 +136,18 @@ static void push_lock(void* c, const CLockLocation& locklocation)
132136
LockData& lockdata = GetLockData();
133137
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
134138

135-
g_lockstack.push_back(std::make_pair(c, locklocation));
136-
137-
for (const std::pair<void*, CLockLocation>& i : g_lockstack) {
139+
LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
140+
lock_stack.emplace_back(c, locklocation);
141+
for (const LockStackItem& i : lock_stack) {
138142
if (i.first == c)
139143
break;
140144

141-
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
145+
const LockPair p1 = std::make_pair(i.first, c);
142146
if (lockdata.lockorders.count(p1))
143147
continue;
144-
lockdata.lockorders.emplace(p1, g_lockstack);
148+
lockdata.lockorders.emplace(p1, lock_stack);
145149

146-
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
150+
const LockPair p2 = std::make_pair(c, i.first);
147151
lockdata.invlockorders.insert(p2);
148152
if (lockdata.lockorders.count(p2))
149153
potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
@@ -152,7 +156,14 @@ static void push_lock(void* c, const CLockLocation& locklocation)
152156

153157
static void pop_lock()
154158
{
155-
g_lockstack.pop_back();
159+
LockData& lockdata = GetLockData();
160+
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
161+
162+
LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
163+
lock_stack.pop_back();
164+
if (lock_stack.empty()) {
165+
lockdata.m_lock_stacks.erase(std::this_thread::get_id());
166+
}
156167
}
157168

158169
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
@@ -162,11 +173,17 @@ void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs
162173

163174
void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line)
164175
{
165-
if (!g_lockstack.empty()) {
166-
const auto& lastlock = g_lockstack.back();
167-
if (lastlock.first == cs) {
168-
lockname = lastlock.second.Name();
169-
return;
176+
{
177+
LockData& lockdata = GetLockData();
178+
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
179+
180+
const LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
181+
if (!lock_stack.empty()) {
182+
const auto& lastlock = lock_stack.back();
183+
if (lastlock.first == cs) {
184+
lockname = lastlock.second.Name();
185+
return;
186+
}
170187
}
171188
}
172189
throw std::system_error(EPERM, std::generic_category(), strprintf("%s:%s %s was not most recent critical section locked", file, line, guardname));
@@ -179,49 +196,57 @@ void LeaveCritical()
179196

180197
std::string LocksHeld()
181198
{
199+
LockData& lockdata = GetLockData();
200+
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
201+
202+
const LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
182203
std::string result;
183-
for (const std::pair<void*, CLockLocation>& i : g_lockstack)
204+
for (const LockStackItem& i : lock_stack)
184205
result += i.second.ToString() + std::string("\n");
185206
return result;
186207
}
187208

209+
static bool LockHeld(void* mutex)
210+
{
211+
LockData& lockdata = GetLockData();
212+
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
213+
214+
const LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
215+
for (const LockStackItem& i : lock_stack) {
216+
if (i.first == mutex) return true;
217+
}
218+
219+
return false;
220+
}
221+
188222
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
189223
{
190-
for (const std::pair<void*, CLockLocation>& i : g_lockstack)
191-
if (i.first == cs)
192-
return;
224+
if (LockHeld(cs)) return;
193225
tfm::format(std::cerr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
194226
abort();
195227
}
196228

197229
void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
198230
{
199-
for (const std::pair<void*, CLockLocation>& i : g_lockstack) {
200-
if (i.first == cs) {
201-
tfm::format(std::cerr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
202-
abort();
203-
}
204-
}
231+
if (!LockHeld(cs)) return;
232+
tfm::format(std::cerr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
233+
abort();
205234
}
206235

207236
void DeleteLock(void* cs)
208237
{
209238
LockData& lockdata = GetLockData();
210-
if (!lockdata.available) {
211-
// We're already shutting down.
212-
return;
213-
}
214239
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
215-
std::pair<void*, void*> item = std::make_pair(cs, nullptr);
240+
const LockPair item = std::make_pair(cs, nullptr);
216241
LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
217242
while (it != lockdata.lockorders.end() && it->first.first == cs) {
218-
std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
243+
const LockPair invitem = std::make_pair(it->first.second, it->first.first);
219244
lockdata.invlockorders.erase(invitem);
220245
lockdata.lockorders.erase(it++);
221246
}
222247
InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
223248
while (invit != lockdata.invlockorders.end() && invit->first == cs) {
224-
std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
249+
const LockPair invinvitem = std::make_pair(invit->second, invit->first);
225250
lockdata.lockorders.erase(invinvitem);
226251
lockdata.invlockorders.erase(invit++);
227252
}

0 commit comments

Comments
 (0)