1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 // Work around clang compilation problem in Boost 1.46:
9 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
10 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
11 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
13 namespace program_options {
14 std::string to_internal(const std::string&);
18 #include <boost/program_options/detail/config_file.hpp>
19 #include <boost/program_options/parsers.hpp>
20 #include <boost/filesystem.hpp>
21 #include <boost/filesystem/fstream.hpp>
22 #include <boost/interprocess/sync/interprocess_mutex.hpp>
23 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
24 #include <boost/foreach.hpp>
25 #include <boost/thread.hpp>
28 using namespace boost;
30 map<string, string> mapArgs;
31 map<string, vector<string> > mapMultiArgs;
33 bool fPrintToConsole = false;
34 bool fPrintToDebugger = false;
35 char pszSetDataDir[MAX_PATH] = "";
36 bool fRequestShutdown = false;
37 bool fShutdown = false;
40 bool fCommandLine = false;
41 string strMiscWarning;
42 bool fTestNet = false;
43 bool fNoListen = false;
44 bool fLogTimestamps = false;
49 // Workaround for "multiple definition of `_tls_used'"
50 // http://svn.boost.org/trac/boost/ticket/4258
51 extern "C" void tss_cleanup_implemented() { }
57 // Init openssl library multithreading support
58 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
59 void locking_callback(int mode, int i, const char* file, int line)
61 if (mode & CRYPTO_LOCK)
62 ppmutexOpenSSL[i]->lock();
64 ppmutexOpenSSL[i]->unlock();
73 // Init openssl library multithreading support
74 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
75 for (int i = 0; i < CRYPTO_num_locks(); i++)
76 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
77 CRYPTO_set_locking_callback(locking_callback);
80 // Seed random number generator with screen scrape and other hardware sources
84 // Seed random number generator with performance counter
89 // Shutdown openssl library multithreading support
90 CRYPTO_set_locking_callback(NULL);
91 for (int i = 0; i < CRYPTO_num_locks(); i++)
92 delete ppmutexOpenSSL[i];
93 OPENSSL_free(ppmutexOpenSSL);
107 // Seed with CPU performance counter
108 int64 nCounter = GetPerformanceCounter();
109 RAND_add(&nCounter, sizeof(nCounter), 1.5);
110 memset(&nCounter, 0, sizeof(nCounter));
113 void RandAddSeedPerfmon()
117 // This can take up to 2 seconds, so only do it every 10 minutes
118 static int64 nLastPerfmon;
119 if (GetTime() < nLastPerfmon + 10 * 60)
121 nLastPerfmon = GetTime();
124 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
125 // Seed with the entire set of perfmon data
126 unsigned char pdata[250000];
127 memset(pdata, 0, sizeof(pdata));
128 unsigned long nSize = sizeof(pdata);
129 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
130 RegCloseKey(HKEY_PERFORMANCE_DATA);
131 if (ret == ERROR_SUCCESS)
133 RAND_add(pdata, nSize, nSize/100.0);
134 memset(pdata, 0, nSize);
135 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
140 uint64 GetRand(uint64 nMax)
145 // The range of the random source must be a multiple of the modulus
146 // to give every possible output value an equal possibility
147 uint64 nRange = (UINT64_MAX / nMax) * nMax;
150 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
151 while (nRand >= nRange);
152 return (nRand % nMax);
155 int GetRandInt(int nMax)
157 return GetRand(nMax);
170 inline int OutputDebugStringF(const char* pszFormat, ...)
177 va_start(arg_ptr, pszFormat);
178 ret = vprintf(pszFormat, arg_ptr);
183 // print to debug.log
184 static FILE* fileout = NULL;
188 char pszFile[MAX_PATH+100];
190 strlcat(pszFile, "/debug.log", sizeof(pszFile));
191 fileout = fopen(pszFile, "a");
192 if (fileout) setbuf(fileout, NULL); // unbuffered
196 static bool fStartedNewLine = true;
197 static boost::mutex mutexDebugLog;
198 boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
200 // Debug print useful for profiling
201 if (fLogTimestamps && fStartedNewLine)
202 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
203 if (pszFormat[strlen(pszFormat) - 1] == '\n')
204 fStartedNewLine = true;
206 fStartedNewLine = false;
209 va_start(arg_ptr, pszFormat);
210 ret = vfprintf(fileout, pszFormat, arg_ptr);
216 if (fPrintToDebugger)
218 static CCriticalSection cs_OutputDebugStringF;
220 // accumulate a line at a time
221 CRITICAL_BLOCK(cs_OutputDebugStringF)
223 static char pszBuffer[50000];
228 va_start(arg_ptr, pszFormat);
229 int limit = END(pszBuffer) - pend - 2;
230 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
232 if (ret < 0 || ret >= limit)
234 pend = END(pszBuffer) - 2;
240 char* p1 = pszBuffer;
242 while ((p2 = strchr(p1, '\n')))
247 OutputDebugStringA(p1);
252 memmove(pszBuffer, p1, pend - p1 + 1);
253 pend -= (p1 - pszBuffer);
262 // - prints up to limit-1 characters
263 // - output string is always null terminated even if limit reached
264 // - return value is the number of characters actually printed
265 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
270 va_start(arg_ptr, format);
271 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
273 if (ret < 0 || ret >= limit)
282 string strprintf(const char* format, ...)
286 int limit = sizeof(buffer);
291 va_start(arg_ptr, format);
292 ret = _vsnprintf(p, limit, format, arg_ptr);
294 if (ret >= 0 && ret < limit)
301 throw std::bad_alloc();
303 string str(p, p+ret);
310 bool error(const char* format, ...)
313 int limit = sizeof(buffer);
315 va_start(arg_ptr, format);
316 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
318 if (ret < 0 || ret >= limit)
323 printf("ERROR: %s\n", buffer);
328 void ParseString(const string& str, char c, vector<string>& v)
332 string::size_type i1 = 0;
333 string::size_type i2;
336 i2 = str.find(c, i1);
339 v.push_back(str.substr(i1));
342 v.push_back(str.substr(i1, i2-i1));
348 string FormatMoney(int64 n, bool fPlus)
350 // Note: not using straight sprintf here because we do NOT want
351 // localized number formatting.
352 int64 n_abs = (n > 0 ? n : -n);
353 int64 quotient = n_abs/COIN;
354 int64 remainder = n_abs%COIN;
355 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
357 // Right-trim excess 0's before the decimal point:
359 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
362 str.erase(str.size()-nTrim, nTrim);
365 str.insert((unsigned int)0, 1, '-');
366 else if (fPlus && n > 0)
367 str.insert((unsigned int)0, 1, '+');
372 bool ParseMoney(const string& str, int64& nRet)
374 return ParseMoney(str.c_str(), nRet);
377 bool ParseMoney(const char* pszIn, int64& nRet)
381 const char* p = pszIn;
389 int64 nMult = CENT*10;
390 while (isdigit(*p) && (nMult > 0))
392 nUnits += nMult * (*p++ - '0');
401 strWhole.insert(strWhole.end(), *p);
406 if (strWhole.size() > 10) // guard against 63 bit overflow
408 if (nUnits < 0 || nUnits > COIN)
410 int64 nWhole = atoi64(strWhole);
411 int64 nValue = nWhole*COIN + nUnits;
418 vector<unsigned char> ParseHex(const char* psz)
420 static signed char phexdigit[256] =
421 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
422 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
423 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
424 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
425 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
426 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
427 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
428 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
429 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
430 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
431 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
432 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
433 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
434 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
435 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
436 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
438 // convert hex dump to vector
439 vector<unsigned char> vch;
442 while (isspace(*psz))
444 signed char c = phexdigit[(unsigned char)*psz++];
445 if (c == (signed char)-1)
447 unsigned char n = (c << 4);
448 c = phexdigit[(unsigned char)*psz++];
449 if (c == (signed char)-1)
457 vector<unsigned char> ParseHex(const string& str)
459 return ParseHex(str.c_str());
463 void ParseParameters(int argc, char* argv[])
466 mapMultiArgs.clear();
467 for (int i = 1; i < argc; i++)
470 strlcpy(psz, argv[i], sizeof(psz));
471 char* pszValue = (char*)"";
472 if (strchr(psz, '='))
474 pszValue = strchr(psz, '=');
484 mapArgs[psz] = pszValue;
485 mapMultiArgs[psz].push_back(pszValue);
489 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
491 if (mapArgs.count(strArg))
493 mapArgs[strArg] = strValue;
497 bool SoftSetArg(const std::string& strArg, bool fValue)
500 return SoftSetArg(strArg, std::string("1"));
502 return SoftSetArg(strArg, std::string("0"));
507 const char* wxGetTranslation(const char* pszEnglish)
510 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
511 static CCriticalSection cs;
515 static map<string, char*> mapCache;
516 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
517 if (mi != mapCache.end())
520 // wxWidgets translation
521 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
523 // We don't cache unknown strings because caller might be passing in a
524 // dynamic string and we would keep allocating memory for each variation.
525 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
528 // Add to cache, memory doesn't need to be freed. We only cache because
529 // we must pass back a pointer to permanently allocated memory.
530 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
531 strcpy(pszCached, strTranslated.utf8_str());
532 mapCache[pszEnglish] = pszCached;
542 bool WildcardMatch(const char* psz, const char* mask)
549 return (*psz == '\0');
551 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
566 bool WildcardMatch(const string& str, const string& mask)
568 return WildcardMatch(str.c_str(), mask.c_str());
578 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
581 char pszModule[MAX_PATH];
583 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
585 const char* pszModule = "bitcoin";
588 snprintf(pszMessage, 1000,
589 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
591 snprintf(pszMessage, 1000,
592 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
595 void LogException(std::exception* pex, const char* pszThread)
597 char pszMessage[10000];
598 FormatException(pszMessage, pex, pszThread);
599 printf("\n%s", pszMessage);
602 void PrintException(std::exception* pex, const char* pszThread)
604 char pszMessage[10000];
605 FormatException(pszMessage, pex, pszThread);
606 printf("\n\n************************\n%s\n", pszMessage);
607 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
608 strMiscWarning = pszMessage;
610 if (wxTheApp && !fDaemon)
611 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
616 void ThreadOneMessageBox(string strMessage)
618 // Skip message boxes if one is already open
619 static bool fMessageBoxOpen;
622 fMessageBoxOpen = true;
623 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
624 fMessageBoxOpen = false;
627 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
629 char pszMessage[10000];
630 FormatException(pszMessage, pex, pszThread);
631 printf("\n\n************************\n%s\n", pszMessage);
632 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
633 strMiscWarning = pszMessage;
635 if (wxTheApp && !fDaemon)
636 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
648 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
650 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
652 char pszPath[MAX_PATH+100] = "";
654 // SHGetSpecialFolderPath isn't always available on old Windows versions
655 HMODULE hShell32 = LoadLibraryA("shell32.dll");
658 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
659 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
660 bool fSuccess = false;
661 if (pSHGetSpecialFolderPath)
663 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
664 FreeModule(hShell32);
673 if (nFolder == CSIDL_STARTUP)
675 pszEnv = getenv("USERPROFILE");
678 strPath += "\\Start Menu\\Programs\\Startup";
680 else if (nFolder == CSIDL_APPDATA)
682 pszEnv = getenv("APPDATA");
692 string GetDefaultDataDir()
694 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
695 // Mac: ~/Library/Application Support/Bitcoin
699 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
701 char* pszHome = getenv("HOME");
702 if (pszHome == NULL || strlen(pszHome) == 0)
703 pszHome = (char*)"/";
704 string strHome = pszHome;
705 if (strHome[strHome.size()-1] != '/')
709 strHome += "Library/Application Support/";
710 filesystem::create_directory(strHome.c_str());
711 return strHome + "Bitcoin";
714 return strHome + ".bitcoin";
719 void GetDataDir(char* pszDir)
721 // pszDir must be at least MAX_PATH length.
723 if (pszSetDataDir[0] != 0)
725 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
730 // This can be called during exceptions by printf, so we cache the
731 // value so we don't have to do memory allocations after that.
732 static char pszCachedDir[MAX_PATH];
733 if (pszCachedDir[0] == 0)
734 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
735 strlcpy(pszDir, pszCachedDir, MAX_PATH);
740 char* p = pszDir + strlen(pszDir);
741 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
743 strcpy(p, "testnet");
746 static bool pfMkdir[4];
747 if (!pfMkdir[nVariation])
749 pfMkdir[nVariation] = true;
750 boost::filesystem::create_directory(pszDir);
756 char pszDir[MAX_PATH];
761 string GetConfigFile()
763 namespace fs = boost::filesystem;
764 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
765 if (!pathConfig.is_complete())
766 pathConfig = fs::path(GetDataDir()) / pathConfig;
767 return pathConfig.string();
770 void ReadConfigFile(map<string, string>& mapSettingsRet,
771 map<string, vector<string> >& mapMultiSettingsRet)
773 namespace fs = boost::filesystem;
774 namespace pod = boost::program_options::detail;
776 fs::ifstream streamConfig(GetConfigFile());
777 if (!streamConfig.good())
780 set<string> setOptions;
781 setOptions.insert("*");
783 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
785 // Don't overwrite existing settings so command line settings override bitcoin.conf
786 string strKey = string("-") + it->string_key;
787 if (mapSettingsRet.count(strKey) == 0)
788 mapSettingsRet[strKey] = it->value[0];
789 mapMultiSettingsRet[strKey].push_back(it->value[0]);
795 namespace fs = boost::filesystem;
796 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
797 if (!pathConfig.is_complete())
798 pathConfig = fs::path(GetDataDir()) / pathConfig;
799 return pathConfig.string();
802 void CreatePidFile(string pidFile, pid_t pid)
804 FILE* file = fopen(pidFile.c_str(), "w");
807 fprintf(file, "%d\n", pid);
812 int GetFilesize(FILE* file)
814 int nSavePos = ftell(file);
816 if (fseek(file, 0, SEEK_END) == 0)
817 nFilesize = ftell(file);
818 fseek(file, nSavePos, SEEK_SET);
822 void ShrinkDebugFile()
824 // Scroll debug.log if it's getting too big
825 string strFile = GetDataDir() + "/debug.log";
826 FILE* file = fopen(strFile.c_str(), "r");
827 if (file && GetFilesize(file) > 10 * 1000000)
829 // Restart the file with some of the end
831 fseek(file, -sizeof(pch), SEEK_END);
832 int nBytes = fread(pch, 1, sizeof(pch), file);
835 file = fopen(strFile.c_str(), "w");
838 fwrite(pch, 1, nBytes, file);
852 // "Never go to sea with two chronometers; take one or three."
853 // Our three time sources are:
855 // - Median of other nodes's clocks
856 // - The user (asking the user to fix the system clock if the first two disagree)
863 static int64 nTimeOffset = 0;
865 int64 GetAdjustedTime()
867 return GetTime() + nTimeOffset;
870 void AddTimeData(unsigned int ip, int64 nTime)
872 int64 nOffsetSample = nTime - GetTime();
875 static set<unsigned int> setKnown;
876 if (!setKnown.insert(ip).second)
880 static vector<int64> vTimeOffsets;
881 if (vTimeOffsets.empty())
882 vTimeOffsets.push_back(0);
883 vTimeOffsets.push_back(nOffsetSample);
884 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
885 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
887 sort(vTimeOffsets.begin(), vTimeOffsets.end());
888 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
889 // Only let other nodes change our time by so much
890 if (abs64(nMedian) < 70 * 60)
892 nTimeOffset = nMedian;
901 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
903 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
904 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
910 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
911 strMiscWarning = strMessage;
912 printf("*** %s\n", strMessage.c_str());
913 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
917 BOOST_FOREACH(int64 n, vTimeOffsets)
918 printf("%+"PRI64d" ", n);
919 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
931 string FormatVersion(int nVersion)
933 if (nVersion%100 == 0)
934 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
936 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
939 string FormatFullVersion()
941 string s = FormatVersion(VERSION) + pszSubVer;
942 if (VERSION_IS_BETA) {
952 #ifdef DEBUG_LOCKORDER
954 // Early deadlock detection.
955 // Problem being solved:
956 // Thread 1 locks A, then B, then C
957 // Thread 2 locks D, then C, then A
958 // --> may result in deadlock between the two threads, depending on when they run.
959 // Solution implemented here:
960 // Keep track of pairs of locks: (A before B), (A before C), etc.
961 // Complain if any thread trys to lock in a different order.
966 CLockLocation(const char* pszName, const char* pszFile, int nLine)
969 sourceFile = pszFile;
973 std::string ToString() const
975 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
979 std::string mutexName;
980 std::string sourceFile;
984 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
986 static boost::interprocess::interprocess_mutex dd_mutex;
987 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
988 static boost::thread_specific_ptr<LockStack> lockstack;
991 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
993 printf("POTENTIAL DEADLOCK DETECTED\n");
994 printf("Previous lock order was:\n");
995 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
997 if (i.first == mismatch.first) printf(" (1)");
998 if (i.first == mismatch.second) printf(" (2)");
999 printf(" %s\n", i.second.ToString().c_str());
1001 printf("Current lock order is:\n");
1002 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1004 if (i.first == mismatch.first) printf(" (1)");
1005 if (i.first == mismatch.second) printf(" (2)");
1006 printf(" %s\n", i.second.ToString().c_str());
1010 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1012 bool fOrderOK = true;
1013 if (lockstack.get() == NULL)
1014 lockstack.reset(new LockStack);
1016 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1019 (*lockstack).push_back(std::make_pair(c, locklocation));
1021 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1023 if (i.first == c) break;
1025 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1026 if (lockorders.count(p1))
1028 lockorders[p1] = (*lockstack);
1030 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1031 if (lockorders.count(p2))
1033 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1040 static void pop_lock()
1044 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1045 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1048 (*lockstack).pop_back();
1052 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1054 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1057 void CCriticalSection::Leave()
1062 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1064 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1065 bool result = mutex.try_lock();
1066 if (!result) pop_lock();
1072 void CCriticalSection::Enter(const char*, const char*, int)
1077 void CCriticalSection::Leave()
1082 bool CCriticalSection::TryEnter(const char*, const char*, int)
1084 bool result = mutex.try_lock();
1088 #endif /* DEBUG_LOCKORDER */