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 license.txt 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>
27 using namespace boost;
29 map<string, string> mapArgs;
30 map<string, vector<string> > mapMultiArgs;
32 bool fPrintToConsole = false;
33 bool fPrintToDebugger = false;
34 char pszSetDataDir[MAX_PATH] = "";
35 bool fRequestShutdown = false;
36 bool fShutdown = false;
39 bool fCommandLine = false;
40 string strMiscWarning;
41 bool fTestNet = false;
42 bool fNoListen = false;
43 bool fLogTimestamps = false;
48 // Workaround for "multiple definition of `_tls_used'"
49 // http://svn.boost.org/trac/boost/ticket/4258
50 extern "C" void tss_cleanup_implemented() { }
56 // Init openssl library multithreading support
57 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
58 void locking_callback(int mode, int i, const char* file, int line)
60 if (mode & CRYPTO_LOCK)
61 ppmutexOpenSSL[i]->lock();
63 ppmutexOpenSSL[i]->unlock();
72 // Init openssl library multithreading support
73 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
74 for (int i = 0; i < CRYPTO_num_locks(); i++)
75 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
76 CRYPTO_set_locking_callback(locking_callback);
79 // Seed random number generator with screen scrape and other hardware sources
83 // Seed random number generator with performance counter
88 // Shutdown openssl library multithreading support
89 CRYPTO_set_locking_callback(NULL);
90 for (int i = 0; i < CRYPTO_num_locks(); i++)
91 delete ppmutexOpenSSL[i];
92 OPENSSL_free(ppmutexOpenSSL);
106 // Seed with CPU performance counter
107 int64 nCounter = GetPerformanceCounter();
108 RAND_add(&nCounter, sizeof(nCounter), 1.5);
109 memset(&nCounter, 0, sizeof(nCounter));
112 void RandAddSeedPerfmon()
116 // This can take up to 2 seconds, so only do it every 10 minutes
117 static int64 nLastPerfmon;
118 if (GetTime() < nLastPerfmon + 10 * 60)
120 nLastPerfmon = GetTime();
123 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
124 // Seed with the entire set of perfmon data
125 unsigned char pdata[250000];
126 memset(pdata, 0, sizeof(pdata));
127 unsigned long nSize = sizeof(pdata);
128 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
129 RegCloseKey(HKEY_PERFORMANCE_DATA);
130 if (ret == ERROR_SUCCESS)
132 RAND_add(pdata, nSize, nSize/100.0);
133 memset(pdata, 0, nSize);
134 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
139 uint64 GetRand(uint64 nMax)
144 // The range of the random source must be a multiple of the modulus
145 // to give every possible output value an equal possibility
146 uint64 nRange = (UINT64_MAX / nMax) * nMax;
149 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
150 while (nRand >= nRange);
151 return (nRand % nMax);
154 int GetRandInt(int nMax)
156 return GetRand(nMax);
169 inline int OutputDebugStringF(const char* pszFormat, ...)
176 va_start(arg_ptr, pszFormat);
177 ret = vprintf(pszFormat, arg_ptr);
182 // print to debug.log
183 static FILE* fileout = NULL;
187 char pszFile[MAX_PATH+100];
189 strlcat(pszFile, "/debug.log", sizeof(pszFile));
190 fileout = fopen(pszFile, "a");
191 if (fileout) setbuf(fileout, NULL); // unbuffered
195 static bool fStartedNewLine = true;
197 // Debug print useful for profiling
198 if (fLogTimestamps && fStartedNewLine)
199 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
200 if (pszFormat[strlen(pszFormat) - 1] == '\n')
201 fStartedNewLine = true;
203 fStartedNewLine = false;
206 va_start(arg_ptr, pszFormat);
207 ret = vfprintf(fileout, pszFormat, arg_ptr);
213 if (fPrintToDebugger)
215 static CCriticalSection cs_OutputDebugStringF;
217 // accumulate a line at a time
218 CRITICAL_BLOCK(cs_OutputDebugStringF)
220 static char pszBuffer[50000];
225 va_start(arg_ptr, pszFormat);
226 int limit = END(pszBuffer) - pend - 2;
227 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
229 if (ret < 0 || ret >= limit)
231 pend = END(pszBuffer) - 2;
237 char* p1 = pszBuffer;
239 while (p2 = strchr(p1, '\n'))
244 OutputDebugStringA(p1);
249 memmove(pszBuffer, p1, pend - p1 + 1);
250 pend -= (p1 - pszBuffer);
259 // - prints up to limit-1 characters
260 // - output string is always null terminated even if limit reached
261 // - return value is the number of characters actually printed
262 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
267 va_start(arg_ptr, format);
268 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
270 if (ret < 0 || ret >= limit)
279 string strprintf(const char* format, ...)
283 int limit = sizeof(buffer);
288 va_start(arg_ptr, format);
289 ret = _vsnprintf(p, limit, format, arg_ptr);
291 if (ret >= 0 && ret < limit)
298 throw std::bad_alloc();
300 string str(p, p+ret);
307 bool error(const char* format, ...)
310 int limit = sizeof(buffer);
312 va_start(arg_ptr, format);
313 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
315 if (ret < 0 || ret >= limit)
320 printf("ERROR: %s\n", buffer);
325 void ParseString(const string& str, char c, vector<string>& v)
329 string::size_type i1 = 0;
330 string::size_type i2;
333 i2 = str.find(c, i1);
336 v.push_back(str.substr(i1));
339 v.push_back(str.substr(i1, i2-i1));
345 string FormatMoney(int64 n, bool fPlus)
347 // Note: not using straight sprintf here because we do NOT want
348 // localized number formatting.
349 int64 n_abs = (n > 0 ? n : -n);
350 int64 quotient = n_abs/COIN;
351 int64 remainder = n_abs%COIN;
352 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
354 // Right-trim excess 0's before the decimal point:
356 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
359 str.erase(str.size()-nTrim, nTrim);
362 str.insert((unsigned int)0, 1, '-');
363 else if (fPlus && n > 0)
364 str.insert((unsigned int)0, 1, '+');
369 bool ParseMoney(const string& str, int64& nRet)
371 return ParseMoney(str.c_str(), nRet);
374 bool ParseMoney(const char* pszIn, int64& nRet)
378 const char* p = pszIn;
386 int64 nMult = CENT*10;
387 while (isdigit(*p) && (nMult > 0))
389 nUnits += nMult * (*p++ - '0');
398 strWhole.insert(strWhole.end(), *p);
403 if (strWhole.size() > 10) // guard against 63 bit overflow
405 if (nUnits < 0 || nUnits > COIN)
407 int64 nWhole = atoi64(strWhole);
408 int64 nValue = nWhole*COIN + nUnits;
415 vector<unsigned char> ParseHex(const char* psz)
417 static char phexdigit[256] =
418 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
419 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
420 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
421 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
422 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
425 -1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-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, };
435 // convert hex dump to vector
436 vector<unsigned char> vch;
439 while (isspace(*psz))
441 char c = phexdigit[(unsigned char)*psz++];
444 unsigned char n = (c << 4);
445 c = phexdigit[(unsigned char)*psz++];
454 vector<unsigned char> ParseHex(const string& str)
456 return ParseHex(str.c_str());
460 void ParseParameters(int argc, char* argv[])
463 mapMultiArgs.clear();
464 for (int i = 1; i < argc; i++)
467 strlcpy(psz, argv[i], sizeof(psz));
468 char* pszValue = (char*)"";
469 if (strchr(psz, '='))
471 pszValue = strchr(psz, '=');
481 mapArgs[psz] = pszValue;
482 mapMultiArgs[psz].push_back(pszValue);
486 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
488 if (mapArgs.count(strArg))
490 mapArgs[strArg] = strValue;
494 bool SoftSetArg(const std::string& strArg, bool fValue)
497 return SoftSetArg(strArg, std::string("1"));
499 return SoftSetArg(strArg, std::string("0"));
504 const char* wxGetTranslation(const char* pszEnglish)
507 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
508 static CCriticalSection cs;
512 static map<string, char*> mapCache;
513 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
514 if (mi != mapCache.end())
517 // wxWidgets translation
518 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
520 // We don't cache unknown strings because caller might be passing in a
521 // dynamic string and we would keep allocating memory for each variation.
522 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
525 // Add to cache, memory doesn't need to be freed. We only cache because
526 // we must pass back a pointer to permanently allocated memory.
527 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
528 strcpy(pszCached, strTranslated.utf8_str());
529 mapCache[pszEnglish] = pszCached;
539 bool WildcardMatch(const char* psz, const char* mask)
546 return (*psz == '\0');
548 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
563 bool WildcardMatch(const string& str, const string& mask)
565 return WildcardMatch(str.c_str(), mask.c_str());
575 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
578 char pszModule[MAX_PATH];
580 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
582 const char* pszModule = "bitcoin";
585 snprintf(pszMessage, 1000,
586 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
588 snprintf(pszMessage, 1000,
589 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
592 void LogException(std::exception* pex, const char* pszThread)
594 char pszMessage[10000];
595 FormatException(pszMessage, pex, pszThread);
596 printf("\n%s", pszMessage);
599 void PrintException(std::exception* pex, const char* pszThread)
601 char pszMessage[10000];
602 FormatException(pszMessage, pex, pszThread);
603 printf("\n\n************************\n%s\n", pszMessage);
604 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
605 strMiscWarning = pszMessage;
607 if (wxTheApp && !fDaemon)
608 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
613 void ThreadOneMessageBox(string strMessage)
615 // Skip message boxes if one is already open
616 static bool fMessageBoxOpen;
619 fMessageBoxOpen = true;
620 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
621 fMessageBoxOpen = false;
624 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
626 char pszMessage[10000];
627 FormatException(pszMessage, pex, pszThread);
628 printf("\n\n************************\n%s\n", pszMessage);
629 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
630 strMiscWarning = pszMessage;
632 if (wxTheApp && !fDaemon)
633 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
645 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
647 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
649 char pszPath[MAX_PATH+100] = "";
651 // SHGetSpecialFolderPath isn't always available on old Windows versions
652 HMODULE hShell32 = LoadLibraryA("shell32.dll");
655 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
656 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
657 bool fSuccess = false;
658 if (pSHGetSpecialFolderPath)
660 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
661 FreeModule(hShell32);
670 if (nFolder == CSIDL_STARTUP)
672 pszEnv = getenv("USERPROFILE");
675 strPath += "\\Start Menu\\Programs\\Startup";
677 else if (nFolder == CSIDL_APPDATA)
679 pszEnv = getenv("APPDATA");
689 string GetDefaultDataDir()
691 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
692 // Mac: ~/Library/Application Support/Bitcoin
696 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
698 char* pszHome = getenv("HOME");
699 if (pszHome == NULL || strlen(pszHome) == 0)
700 pszHome = (char*)"/";
701 string strHome = pszHome;
702 if (strHome[strHome.size()-1] != '/')
706 strHome += "Library/Application Support/";
707 filesystem::create_directory(strHome.c_str());
708 return strHome + "Bitcoin";
711 return strHome + ".bitcoin";
716 void GetDataDir(char* pszDir)
718 // pszDir must be at least MAX_PATH length.
720 if (pszSetDataDir[0] != 0)
722 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
727 // This can be called during exceptions by printf, so we cache the
728 // value so we don't have to do memory allocations after that.
729 static char pszCachedDir[MAX_PATH];
730 if (pszCachedDir[0] == 0)
731 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
732 strlcpy(pszDir, pszCachedDir, MAX_PATH);
737 char* p = pszDir + strlen(pszDir);
738 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
740 strcpy(p, "testnet");
743 static bool pfMkdir[4];
744 if (!pfMkdir[nVariation])
746 pfMkdir[nVariation] = true;
747 boost::filesystem::create_directory(pszDir);
753 char pszDir[MAX_PATH];
758 string GetConfigFile()
760 namespace fs = boost::filesystem;
761 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
762 if (!pathConfig.is_complete())
763 pathConfig = fs::path(GetDataDir()) / pathConfig;
764 return pathConfig.string();
767 void ReadConfigFile(map<string, string>& mapSettingsRet,
768 map<string, vector<string> >& mapMultiSettingsRet)
770 namespace fs = boost::filesystem;
771 namespace pod = boost::program_options::detail;
773 fs::ifstream streamConfig(GetConfigFile());
774 if (!streamConfig.good())
777 set<string> setOptions;
778 setOptions.insert("*");
780 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
782 // Don't overwrite existing settings so command line settings override bitcoin.conf
783 string strKey = string("-") + it->string_key;
784 if (mapSettingsRet.count(strKey) == 0)
785 mapSettingsRet[strKey] = it->value[0];
786 mapMultiSettingsRet[strKey].push_back(it->value[0]);
792 namespace fs = boost::filesystem;
793 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
794 if (!pathConfig.is_complete())
795 pathConfig = fs::path(GetDataDir()) / pathConfig;
796 return pathConfig.string();
799 void CreatePidFile(string pidFile, pid_t pid)
801 FILE* file = fopen(pidFile.c_str(), "w");
804 fprintf(file, "%d\n", pid);
809 int GetFilesize(FILE* file)
811 int nSavePos = ftell(file);
813 if (fseek(file, 0, SEEK_END) == 0)
814 nFilesize = ftell(file);
815 fseek(file, nSavePos, SEEK_SET);
819 void ShrinkDebugFile()
821 // Scroll debug.log if it's getting too big
822 string strFile = GetDataDir() + "/debug.log";
823 FILE* file = fopen(strFile.c_str(), "r");
824 if (file && GetFilesize(file) > 10 * 1000000)
826 // Restart the file with some of the end
828 fseek(file, -sizeof(pch), SEEK_END);
829 int nBytes = fread(pch, 1, sizeof(pch), file);
832 file = fopen(strFile.c_str(), "w");
835 fwrite(pch, 1, nBytes, file);
849 // "Never go to sea with two chronometers; take one or three."
850 // Our three time sources are:
852 // - Median of other nodes's clocks
853 // - The user (asking the user to fix the system clock if the first two disagree)
860 static int64 nTimeOffset = 0;
862 int64 GetAdjustedTime()
864 return GetTime() + nTimeOffset;
867 void AddTimeData(unsigned int ip, int64 nTime)
869 int64 nOffsetSample = nTime - GetTime();
872 static set<unsigned int> setKnown;
873 if (!setKnown.insert(ip).second)
877 static vector<int64> vTimeOffsets;
878 if (vTimeOffsets.empty())
879 vTimeOffsets.push_back(0);
880 vTimeOffsets.push_back(nOffsetSample);
881 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
882 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
884 sort(vTimeOffsets.begin(), vTimeOffsets.end());
885 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
886 // Only let other nodes change our time by so much
887 if (abs64(nMedian) < 70 * 60)
889 nTimeOffset = nMedian;
898 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
900 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
901 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
907 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
908 strMiscWarning = strMessage;
909 printf("*** %s\n", strMessage.c_str());
910 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
914 BOOST_FOREACH(int64 n, vTimeOffsets)
915 printf("%+"PRI64d" ", n);
916 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
928 string FormatVersion(int nVersion)
930 if (nVersion%100 == 0)
931 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
933 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
936 string FormatFullVersion()
938 string s = FormatVersion(VERSION) + pszSubVer;
939 if (VERSION_IS_BETA) {
949 #ifdef DEBUG_LOCKORDER
951 // Early deadlock detection.
952 // Problem being solved:
953 // Thread 1 locks A, then B, then C
954 // Thread 2 locks D, then C, then A
955 // --> may result in deadlock between the two threads, depending on when they run.
956 // Solution implemented here:
957 // Keep track of pairs of locks: (A before B), (A before C), etc.
958 // Complain if any thread trys to lock in a different order.
963 CLockLocation(const char* pszName, const char* pszFile, int nLine)
966 sourceFile = pszFile;
970 std::string ToString() const
972 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
976 std::string mutexName;
977 std::string sourceFile;
981 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
983 static boost::interprocess::interprocess_mutex dd_mutex;
984 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
985 static boost::thread_specific_ptr<LockStack> lockstack;
988 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
990 printf("POTENTIAL DEADLOCK DETECTED\n");
991 printf("Previous lock order was:\n");
992 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
994 if (i.first == mismatch.first) printf(" (1)");
995 if (i.first == mismatch.second) printf(" (2)");
996 printf(" %s\n", i.second.ToString().c_str());
998 printf("Current lock order is:\n");
999 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1001 if (i.first == mismatch.first) printf(" (1)");
1002 if (i.first == mismatch.second) printf(" (2)");
1003 printf(" %s\n", i.second.ToString().c_str());
1007 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1009 bool fOrderOK = true;
1010 if (lockstack.get() == NULL)
1011 lockstack.reset(new LockStack);
1013 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1016 (*lockstack).push_back(std::make_pair(c, locklocation));
1018 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1020 if (i.first == c) break;
1022 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1023 if (lockorders.count(p1))
1025 lockorders[p1] = (*lockstack);
1027 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1028 if (lockorders.count(p2))
1030 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1037 static void pop_lock()
1041 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1042 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1045 (*lockstack).pop_back();
1049 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1051 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1054 void CCriticalSection::Leave()
1059 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1061 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1062 bool result = mutex.try_lock();
1063 if (!result) pop_lock();
1069 void CCriticalSection::Enter(const char*, const char*, int)
1074 void CCriticalSection::Leave()
1079 bool CCriticalSection::TryEnter(const char*, const char*, int)
1081 bool result = mutex.try_lock();
1085 #endif /* DEBUG_LOCKORDER */