1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include <boost/program_options/detail/config_file.hpp>
9 #include <boost/program_options/parsers.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12 #include <boost/interprocess/sync/interprocess_mutex.hpp>
13 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
14 #include <boost/foreach.hpp>
21 using namespace boost;
23 map<string, string> mapArgs;
24 map<string, vector<string> > mapMultiArgs;
26 bool fPrintToConsole = false;
27 bool fPrintToDebugger = false;
28 char pszSetDataDir[MAX_PATH] = "";
29 bool fRequestShutdown = false;
30 bool fShutdown = false;
33 bool fCommandLine = false;
34 string strMiscWarning;
35 bool fTestNet = false;
36 bool fNoListen = false;
37 bool fLogTimestamps = false;
42 // Workaround for "multiple definition of `_tls_used'"
43 // http://svn.boost.org/trac/boost/ticket/4258
44 extern "C" void tss_cleanup_implemented() { }
50 // Init openssl library multithreading support
51 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
52 void locking_callback(int mode, int i, const char* file, int line)
54 if (mode & CRYPTO_LOCK)
55 ppmutexOpenSSL[i]->lock();
57 ppmutexOpenSSL[i]->unlock();
66 // Init openssl library multithreading support
67 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
68 for (int i = 0; i < CRYPTO_num_locks(); i++)
69 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
70 CRYPTO_set_locking_callback(locking_callback);
73 // Seed random number generator with screen scrape and other hardware sources
77 // Seed random number generator with performance counter
82 // Shutdown openssl library multithreading support
83 CRYPTO_set_locking_callback(NULL);
84 for (int i = 0; i < CRYPTO_num_locks(); i++)
85 delete ppmutexOpenSSL[i];
86 OPENSSL_free(ppmutexOpenSSL);
100 // Seed with CPU performance counter
101 int64 nCounter = GetPerformanceCounter();
102 RAND_add(&nCounter, sizeof(nCounter), 1.5);
103 memset(&nCounter, 0, sizeof(nCounter));
106 void RandAddSeedPerfmon()
110 // This can take up to 2 seconds, so only do it every 10 minutes
111 static int64 nLastPerfmon;
112 if (GetTime() < nLastPerfmon + 10 * 60)
114 nLastPerfmon = GetTime();
117 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
118 // Seed with the entire set of perfmon data
119 unsigned char pdata[250000];
120 memset(pdata, 0, sizeof(pdata));
121 unsigned long nSize = sizeof(pdata);
122 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
123 RegCloseKey(HKEY_PERFORMANCE_DATA);
124 if (ret == ERROR_SUCCESS)
126 RAND_add(pdata, nSize, nSize/100.0);
127 memset(pdata, 0, nSize);
128 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
133 uint64 GetRand(uint64 nMax)
138 // The range of the random source must be a multiple of the modulus
139 // to give every possible output value an equal possibility
140 uint64 nRange = (UINT64_MAX / nMax) * nMax;
143 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
144 while (nRand >= nRange);
145 return (nRand % nMax);
148 int GetRandInt(int nMax)
150 return GetRand(nMax);
161 static FILE* fileout = NULL;
163 inline int OutputDebugStringF(const char* pszFormat, ...)
170 va_start(arg_ptr, pszFormat);
171 ret = vprintf(pszFormat, arg_ptr);
176 // print to debug.log
179 char pszFile[MAX_PATH+100];
181 strlcat(pszFile, "/debug.log", sizeof(pszFile));
182 fileout = fopen(pszFile, "a");
183 if (fileout) setbuf(fileout, NULL); // unbuffered
187 static bool fStartedNewLine = true;
189 // Debug print useful for profiling
190 if (fLogTimestamps && fStartedNewLine)
191 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
192 if (pszFormat[strlen(pszFormat) - 1] == '\n')
193 fStartedNewLine = true;
195 fStartedNewLine = false;
198 va_start(arg_ptr, pszFormat);
199 ret = vfprintf(fileout, pszFormat, arg_ptr);
205 if (fPrintToDebugger)
207 static CCriticalSection cs_OutputDebugStringF;
209 // accumulate a line at a time
210 CRITICAL_BLOCK(cs_OutputDebugStringF)
212 static char pszBuffer[50000];
217 va_start(arg_ptr, pszFormat);
218 int limit = END(pszBuffer) - pend - 2;
219 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
221 if (ret < 0 || ret >= limit)
223 pend = END(pszBuffer) - 2;
229 char* p1 = pszBuffer;
231 while (p2 = strchr(p1, '\n'))
236 OutputDebugStringA(p1);
241 memmove(pszBuffer, p1, pend - p1 + 1);
242 pend -= (p1 - pszBuffer);
251 // - prints up to limit-1 characters
252 // - output string is always null terminated even if limit reached
253 // - return value is the number of characters actually printed
254 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
259 va_start(arg_ptr, format);
260 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
262 if (ret < 0 || ret >= limit)
270 string strprintf(const std::string &format, ...)
274 int limit = sizeof(buffer);
279 va_start(arg_ptr, format);
280 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
282 if (ret >= 0 && ret < limit)
289 throw std::bad_alloc();
291 string str(p, p+ret);
297 bool error(const std::string &format, ...)
300 int limit = sizeof(buffer);
302 va_start(arg_ptr, format);
303 int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
305 if (ret < 0 || ret >= limit)
310 printf("ERROR: %s\n", buffer);
315 void ParseString(const string& str, char c, vector<string>& v)
319 string::size_type i1 = 0;
320 string::size_type i2;
323 i2 = str.find(c, i1);
326 v.push_back(str.substr(i1));
329 v.push_back(str.substr(i1, i2-i1));
335 string FormatMoney(int64 n, bool fPlus)
337 // Note: not using straight sprintf here because we do NOT want
338 // localized number formatting.
339 int64 n_abs = (n > 0 ? n : -n);
340 int64 quotient = n_abs/COIN;
341 int64 remainder = n_abs%COIN;
342 string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
344 // Right-trim excess 0's before the decimal point:
346 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
349 str.erase(str.size()-nTrim, nTrim);
352 str.insert((unsigned int)0, 1, '-');
353 else if (fPlus && n > 0)
354 str.insert((unsigned int)0, 1, '+');
359 bool ParseMoney(const string& str, int64& nRet)
361 return ParseMoney(str.c_str(), nRet);
364 bool ParseMoney(const char* pszIn, int64& nRet)
368 const char* p = pszIn;
376 int64 nMult = CENT*10;
377 while (isdigit(*p) && (nMult > 0))
379 nUnits += nMult * (*p++ - '0');
388 strWhole.insert(strWhole.end(), *p);
393 if (strWhole.size() > 10) // guard against 63 bit overflow
395 if (nUnits < 0 || nUnits > COIN)
397 int64 nWhole = atoi64(strWhole);
398 int64 nValue = nWhole*COIN + nUnits;
405 vector<unsigned char> ParseHex(const char* psz)
407 static char phexdigit[256] =
408 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
409 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
410 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
411 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
412 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
413 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
414 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
415 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
416 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
417 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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 -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, };
425 // convert hex dump to vector
426 vector<unsigned char> vch;
429 while (isspace(*psz))
431 char c = phexdigit[(unsigned char)*psz++];
434 unsigned char n = (c << 4);
435 c = phexdigit[(unsigned char)*psz++];
444 vector<unsigned char> ParseHex(const string& str)
446 return ParseHex(str.c_str());
449 void ParseParameters(int argc, char* argv[])
452 mapMultiArgs.clear();
453 for (int i = 1; i < argc; i++)
456 strlcpy(psz, argv[i], sizeof(psz));
457 char* pszValue = (char*)"";
458 if (strchr(psz, '='))
460 pszValue = strchr(psz, '=');
470 mapArgs[psz] = pszValue;
471 mapMultiArgs[psz].push_back(pszValue);
475 string EncodeBase64(const unsigned char* pch, size_t len)
477 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
480 strRet.reserve((len+2)/3*4);
483 const unsigned char *pchEnd = pch+len;
490 case 0: // we have no bits
491 strRet += pbase64[enc >> 2];
492 left = (enc & 3) << 4;
496 case 1: // we have two bits
497 strRet += pbase64[left | (enc >> 4)];
498 left = (enc & 15) << 2;
502 case 2: // we have four bits
503 strRet += pbase64[left | (enc >> 6)];
504 strRet += pbase64[enc & 63];
512 strRet += pbase64[left];
521 string EncodeBase64(const string& str)
523 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
526 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
528 static const int decode64_table[256] =
530 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
531 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
532 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
533 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
534 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
535 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
536 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
537 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
538 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
539 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
540 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
541 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
542 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
548 vector<unsigned char> vchRet;
549 vchRet.reserve(strlen(p)*3/4);
556 int dec = decode64_table[*p];
557 if (dec == -1) break;
561 case 0: // we have no bits and get 6
566 case 1: // we have 6 bits and keep 4
567 vchRet.push_back((left<<2) | (dec>>4));
572 case 2: // we have 4 bits and get 6, we keep 2
573 vchRet.push_back((left<<4) | (dec>>2));
578 case 3: // we have 2 bits and get 6
579 vchRet.push_back((left<<6) | dec);
588 case 0: // 4n base64 characters processed: ok
591 case 1: // 4n+1 base64 character processed: impossible
595 case 2: // 4n+2 base64 characters processed: require '=='
596 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
600 case 3: // 4n+3 base64 characters processed: require '='
601 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
609 string DecodeBase64(const string& str)
611 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
612 return string((const char*)&vchRet[0], vchRet.size());
616 bool WildcardMatch(const char* psz, const char* mask)
623 return (*psz == '\0');
625 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
640 bool WildcardMatch(const string& str, const string& mask)
642 return WildcardMatch(str.c_str(), mask.c_str());
652 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
655 char pszModule[MAX_PATH];
657 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
659 const char* pszModule = "bitcoin";
662 snprintf(pszMessage, 1000,
663 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
665 snprintf(pszMessage, 1000,
666 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
669 void LogException(std::exception* pex, const char* pszThread)
671 char pszMessage[10000];
672 FormatException(pszMessage, pex, pszThread);
673 printf("\n%s", pszMessage);
676 void PrintException(std::exception* pex, const char* pszThread)
678 char pszMessage[10000];
679 FormatException(pszMessage, pex, pszThread);
680 printf("\n\n************************\n%s\n", pszMessage);
681 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
682 strMiscWarning = pszMessage;
686 void LogStackTrace() {
687 printf("\n\n******* exception encountered *******\n");
693 size = backtrace(pszBuffer, 32);
694 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
699 void ThreadOneMessageBox(string strMessage)
701 // Skip message boxes if one is already open
702 static bool fMessageBoxOpen;
705 fMessageBoxOpen = true;
706 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
707 fMessageBoxOpen = false;
710 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
712 char pszMessage[10000];
713 FormatException(pszMessage, pex, pszThread);
714 printf("\n\n************************\n%s\n", pszMessage);
715 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
716 strMiscWarning = pszMessage;
727 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
729 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
731 char pszPath[MAX_PATH+100] = "";
733 // SHGetSpecialFolderPath isn't always available on old Windows versions
734 HMODULE hShell32 = LoadLibraryA("shell32.dll");
737 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
738 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
739 if (pSHGetSpecialFolderPath)
740 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
741 FreeModule(hShell32);
745 if (pszPath[0] == '\0')
747 if (nFolder == CSIDL_STARTUP)
749 strcpy(pszPath, getenv("USERPROFILE"));
750 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
752 else if (nFolder == CSIDL_APPDATA)
754 strcpy(pszPath, getenv("APPDATA"));
762 string GetDefaultDataDir()
764 // Windows: C:\Documents and Settings\username\Application Data\PPCoin
765 // Mac: ~/Library/Application Support/PPCoin
769 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\PPCoin";
771 char* pszHome = getenv("HOME");
772 if (pszHome == NULL || strlen(pszHome) == 0)
773 pszHome = (char*)"/";
774 string strHome = pszHome;
775 if (strHome[strHome.size()-1] != '/')
779 strHome += "Library/Application Support/";
780 filesystem::create_directory(strHome.c_str());
781 return strHome + "PPCoin";
784 return strHome + ".ppcoin";
789 void GetDataDir(char* pszDir)
791 // pszDir must be at least MAX_PATH length.
793 if (pszSetDataDir[0] != 0)
795 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
800 // This can be called during exceptions by printf, so we cache the
801 // value so we don't have to do memory allocations after that.
802 static char pszCachedDir[MAX_PATH];
803 if (pszCachedDir[0] == 0)
804 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
805 strlcpy(pszDir, pszCachedDir, MAX_PATH);
810 char* p = pszDir + strlen(pszDir);
811 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
813 strcpy(p, "testnet");
816 static bool pfMkdir[4];
817 if (!pfMkdir[nVariation])
819 pfMkdir[nVariation] = true;
820 boost::filesystem::create_directory(pszDir);
826 char pszDir[MAX_PATH];
831 string GetConfigFile()
833 namespace fs = boost::filesystem;
834 fs::path pathConfig(GetArg("-conf", "ppcoin.conf"));
835 if (!pathConfig.is_complete())
836 pathConfig = fs::path(GetDataDir()) / pathConfig;
837 return pathConfig.string();
840 void ReadConfigFile(map<string, string>& mapSettingsRet,
841 map<string, vector<string> >& mapMultiSettingsRet)
843 namespace fs = boost::filesystem;
844 namespace pod = boost::program_options::detail;
846 fs::ifstream streamConfig(GetConfigFile());
847 if (!streamConfig.good())
850 set<string> setOptions;
851 setOptions.insert("*");
853 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
855 // Don't overwrite existing settings so command line settings override bitcoin.conf
856 string strKey = string("-") + it->string_key;
857 if (mapSettingsRet.count(strKey) == 0)
858 mapSettingsRet[strKey] = it->value[0];
859 mapMultiSettingsRet[strKey].push_back(it->value[0]);
865 namespace fs = boost::filesystem;
866 fs::path pathConfig(GetArg("-pid", "ppcoind.pid"));
867 if (!pathConfig.is_complete())
868 pathConfig = fs::path(GetDataDir()) / pathConfig;
869 return pathConfig.string();
872 void CreatePidFile(string pidFile, pid_t pid)
874 FILE* file = fopen(pidFile.c_str(), "w");
877 fprintf(file, "%d\n", pid);
882 int GetFilesize(FILE* file)
884 int nSavePos = ftell(file);
886 if (fseek(file, 0, SEEK_END) == 0)
887 nFilesize = ftell(file);
888 fseek(file, nSavePos, SEEK_SET);
892 void ShrinkDebugFile()
894 // Scroll debug.log if it's getting too big
895 string strFile = GetDataDir() + "/debug.log";
896 FILE* file = fopen(strFile.c_str(), "r");
897 if (file && GetFilesize(file) > 10 * 1000000)
899 // Restart the file with some of the end
901 fseek(file, -sizeof(pch), SEEK_END);
902 int nBytes = fread(pch, 1, sizeof(pch), file);
905 file = fopen(strFile.c_str(), "w");
908 fwrite(pch, 1, nBytes, file);
922 // "Never go to sea with two chronometers; take one or three."
923 // Our three time sources are:
925 // - Median of other nodes's clocks
926 // - The user (asking the user to fix the system clock if the first two disagree)
928 static int64 nMockTime = 0; // For unit testing
932 if (nMockTime) return nMockTime;
937 void SetMockTime(int64 nMockTimeIn)
939 nMockTime = nMockTimeIn;
942 static int64 nTimeOffset = 0;
944 int64 GetAdjustedTime()
946 return GetTime() + nTimeOffset;
949 void AddTimeData(unsigned int ip, int64 nTime)
951 int64 nOffsetSample = nTime - GetTime();
954 static set<unsigned int> setKnown;
955 if (!setKnown.insert(ip).second)
959 static vector<int64> vTimeOffsets;
960 if (vTimeOffsets.empty())
961 vTimeOffsets.push_back(0);
962 vTimeOffsets.push_back(nOffsetSample);
963 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
964 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
966 sort(vTimeOffsets.begin(), vTimeOffsets.end());
967 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
968 // Only let other nodes change our time by so much
969 if (abs64(nMedian) < 70 * 60)
971 nTimeOffset = nMedian;
980 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
982 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
983 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
989 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
990 strMiscWarning = strMessage;
991 printf("*** %s\n", strMessage.c_str());
992 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
996 BOOST_FOREACH(int64 n, vTimeOffsets)
997 printf("%+"PRI64d" ", n);
998 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1010 string FormatVersion(int nVersion)
1012 if (nVersion%100 == 0)
1013 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1015 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1018 string FormatFullVersion()
1020 string s = FormatVersion(VERSION) + pszSubVer;
1021 if (VERSION_IS_BETA) {
1031 #ifdef DEBUG_LOCKORDER
1033 // Early deadlock detection.
1034 // Problem being solved:
1035 // Thread 1 locks A, then B, then C
1036 // Thread 2 locks D, then C, then A
1037 // --> may result in deadlock between the two threads, depending on when they run.
1038 // Solution implemented here:
1039 // Keep track of pairs of locks: (A before B), (A before C), etc.
1040 // Complain if any thread trys to lock in a different order.
1043 struct CLockLocation
1045 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1047 mutexName = pszName;
1048 sourceFile = pszFile;
1052 std::string ToString() const
1054 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1058 std::string mutexName;
1059 std::string sourceFile;
1063 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
1065 static boost::interprocess::interprocess_mutex dd_mutex;
1066 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
1067 static boost::thread_specific_ptr<LockStack> lockstack;
1070 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
1072 printf("POTENTIAL DEADLOCK DETECTED\n");
1073 printf("Previous lock order was:\n");
1074 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
1076 if (i.first == mismatch.first) printf(" (1)");
1077 if (i.first == mismatch.second) printf(" (2)");
1078 printf(" %s\n", i.second.ToString().c_str());
1080 printf("Current lock order is:\n");
1081 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1083 if (i.first == mismatch.first) printf(" (1)");
1084 if (i.first == mismatch.second) printf(" (2)");
1085 printf(" %s\n", i.second.ToString().c_str());
1089 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1091 bool fOrderOK = true;
1092 if (lockstack.get() == NULL)
1093 lockstack.reset(new LockStack);
1095 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1098 (*lockstack).push_back(std::make_pair(c, locklocation));
1100 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1102 if (i.first == c) break;
1104 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1105 if (lockorders.count(p1))
1107 lockorders[p1] = (*lockstack);
1109 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1110 if (lockorders.count(p2))
1112 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1119 static void pop_lock()
1123 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1124 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1127 (*lockstack).pop_back();
1131 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1133 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1136 void CCriticalSection::Leave()
1141 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1143 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1144 bool result = mutex.try_lock();
1145 if (!result) pop_lock();
1151 void CCriticalSection::Enter(const char*, const char*, int)
1156 void CCriticalSection::Leave()
1161 bool CCriticalSection::TryEnter(const char*, const char*, int)
1163 bool result = mutex.try_lock();
1167 #endif /* DEBUG_LOCKORDER */