PIVX Core  5.6.99
P2P Digital Currency
sync.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2014 The Bitcoin developers
2 // Copyright (c) 2017-2021 The PIVX Core developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include "sync.h"
7 
8 #include "logging.h"
9 #include "utilstrencodings.h"
10 #include "util/threadnames.h"
11 
12 #include <stdio.h>
13 #include <system_error>
14 #include <map>
15 #include <memory>
16 #include <set>
17 
18 #ifdef DEBUG_LOCKCONTENTION
19 #if !defined(HAVE_THREAD_LOCAL)
20 static_assert(false, "thread_local is not supported");
21 #endif
22 void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
23 {
24  LogPrintf("LOCKCONTENTION: %s\n", pszName);
25  LogPrintf("Locker: %s:%d\n", pszFile, nLine);
26 }
27 #endif /* DEBUG_LOCKCONTENTION */
28 
29 #ifdef DEBUG_LOCKORDER
30 //
31 // Early deadlock detection.
32 // Problem being solved:
33 // Thread 1 locks A, then B, then C
34 // Thread 2 locks D, then C, then A
35 // --> may result in deadlock between the two threads, depending on when they run.
36 // Solution implemented here:
37 // Keep track of pairs of locks: (A before B), (A before C), etc.
38 // Complain if any thread tries to lock in a different order.
39 //
40 
41 struct CLockLocation {
42  CLockLocation(
43  const char* pszName,
44  const char* pszFile,
45  int nLine,
46  bool fTryIn,
47  const std::string& thread_name)
48  : fTry(fTryIn),
49  mutexName(pszName),
50  sourceFile(pszFile),
51  m_thread_name(thread_name),
52  sourceLine(nLine) {}
53 
54  std::string ToString() const
55  {
56  return strprintf(
57  "%s %s:%s%s (in thread %s)",
58  mutexName, sourceFile, itostr(sourceLine), (fTry ? " (TRY)" : ""), m_thread_name);
59  }
60 
61  std::string Name() const
62  {
63  return mutexName;
64  }
65 
66 private:
67  bool fTry;
68  std::string mutexName;
69  std::string sourceFile;
70  const std::string& m_thread_name;
71  int sourceLine;
72 };
73 
74 typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
75 typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
76 typedef std::set<std::pair<void*, void*> > InvLockOrders;
77 
78 struct LockData {
79  // Very ugly hack: as the global constructs and destructors run single
80  // threaded, we use this boolean to know whether LockData still exists,
81  // as DeleteLock can get called by global RecursiveMutex destructors
82  // after LockData disappears.
83  bool available;
84  LockData() : available(true) {}
85  ~LockData() { available = false; }
86 
87  LockOrders lockorders;
88  InvLockOrders invlockorders;
89  std::mutex dd_mutex;
90 };
91 LockData& GetLockData() {
92  static LockData lockdata;
93  return lockdata;
94 }
95 
96 static thread_local LockStack g_lockstack;
97 
98 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
99 {
100  LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
101  LogPrintf("Previous lock order was:\n");
102  for (const std::pair<void*, CLockLocation> & i : s2) {
103  if (i.first == mismatch.first) {
104  LogPrintf(" (1)"); /* Continued */
105  }
106  if (i.first == mismatch.second) {
107  LogPrintf(" (2)"); /* Continued */
108  }
109  LogPrintf(" %s\n", i.second.ToString());
110  }
111  LogPrintf("Current lock order is:\n");
112  for (const std::pair<void*, CLockLocation> & i : s1) {
113  if (i.first == mismatch.first) {
114  LogPrintf(" (1)"); /* Continued */
115  }
116  if (i.first == mismatch.second) {
117  LogPrintf(" (2)"); /* Continued */
118  }
119  LogPrintf(" %s\n", i.second.ToString());
120  }
121  if (g_debug_lockorder_abort) {
122  tfm::format(std::cerr, "Assertion failed: detected inconsistent lock order at %s:%i, details in debug log.\n", __FILE__, __LINE__);
123  abort();
124  }
125  throw std::logic_error("potential deadlock detected");
126 }
127 
128 static void push_lock(void* c, const CLockLocation& locklocation)
129 {
130  LockData& lockdata = GetLockData();
131  std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
132 
133  g_lockstack.emplace_back(c, locklocation);
134 
135  for (const std::pair<void*, CLockLocation>& i : g_lockstack) {
136  if (i.first == c)
137  break;
138 
139  std::pair<void*, void*> p1 = std::make_pair(i.first, c);
140  if (lockdata.lockorders.count(p1))
141  continue;
142  lockdata.lockorders.emplace(p1, g_lockstack);
143 
144  std::pair<void*, void*> p2 = std::make_pair(c, i.first);
145  lockdata.invlockorders.insert(p2);
146  if (lockdata.lockorders.count(p2))
147  potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
148  }
149 }
150 
151 static void pop_lock()
152 {
153  g_lockstack.pop_back();
154 }
155 
156 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
157 {
158  push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry, util::ThreadGetInternalName()));
159 }
160 
161 void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line)
162 {
163  if (!g_lockstack.empty()) {
164  const auto& lastlock = g_lockstack.back();
165  if (lastlock.first == cs) {
166  lockname = lastlock.second.Name();
167  return;
168  }
169  }
170  throw std::system_error(EPERM, std::generic_category(), strprintf("%s:%s %s was not most recent critical section locked", file, line, guardname));
171 }
172 
173 void LeaveCritical()
174 {
175  pop_lock();
176 }
177 
178 std::string LocksHeld()
179 {
180  std::string result;
181  for (const std::pair<void*, CLockLocation>& i : g_lockstack)
182  result += i.second.ToString() + std::string("\n");
183  return result;
184 }
185 
186 void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
187 {
188  for (const std::pair<void*, CLockLocation>& i : g_lockstack)
189  if (i.first == cs)
190  return;
191  fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
192  abort();
193 }
194 
195 void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
196 {
197  for (const std::pair<void*, CLockLocation>& i : g_lockstack) {
198  if (i.first == cs) {
199  tfm::format(std::cerr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
200  abort();
201  }
202  }
203 }
204 
205 void DeleteLock(void* cs)
206 {
207  LockData& lockdata = GetLockData();
208  if (!lockdata.available) {
209  // We're already shutting down.
210  return;
211  }
212  std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
213  std::pair<void*, void*> item = std::make_pair(cs, nullptr);
214  LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
215  while (it != lockdata.lockorders.end() && it->first.first == cs) {
216  std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
217  lockdata.invlockorders.erase(invitem);
218  lockdata.lockorders.erase(it++);
219  }
220  InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
221  while (invit != lockdata.invlockorders.end() && invit->first == cs) {
222  std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
223  lockdata.lockorders.erase(invinvitem);
224  lockdata.invlockorders.erase(invit++);
225  }
226 }
227 
228 bool g_debug_lockorder_abort = true;
229 
230 #endif /* DEBUG_LOCKORDER */
true
Definition: bls_dkg.cpp:153
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:958
const std::string & ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:58
#define strprintf
Definition: tinyformat.h:1056
std::string itostr(int n)