Add UpdatedBlockTip signal to CMainSignals and CValidationInterface
[bitcoinplatinum.git] / src / util.cpp
blobf50d25e17a14e55063daa790b009bf751db7b181
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
8 #endif
10 #include "util.h"
12 #include "chainparamsbase.h"
13 #include "random.h"
14 #include "serialize.h"
15 #include "sync.h"
16 #include "utilstrencodings.h"
17 #include "utiltime.h"
19 #include <stdarg.h>
21 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
22 #include <pthread.h>
23 #include <pthread_np.h>
24 #endif
26 #ifndef WIN32
27 // for posix_fallocate
28 #ifdef __linux__
30 #ifdef _POSIX_C_SOURCE
31 #undef _POSIX_C_SOURCE
32 #endif
34 #define _POSIX_C_SOURCE 200112L
36 #endif // __linux__
38 #include <algorithm>
39 #include <fcntl.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
43 #else
45 #ifdef _MSC_VER
46 #pragma warning(disable:4786)
47 #pragma warning(disable:4804)
48 #pragma warning(disable:4805)
49 #pragma warning(disable:4717)
50 #endif
52 #ifdef _WIN32_WINNT
53 #undef _WIN32_WINNT
54 #endif
55 #define _WIN32_WINNT 0x0501
57 #ifdef _WIN32_IE
58 #undef _WIN32_IE
59 #endif
60 #define _WIN32_IE 0x0501
62 #define WIN32_LEAN_AND_MEAN 1
63 #ifndef NOMINMAX
64 #define NOMINMAX
65 #endif
67 #include <io.h> /* for _commit */
68 #include <shlobj.h>
69 #endif
71 #ifdef HAVE_SYS_PRCTL_H
72 #include <sys/prctl.h>
73 #endif
75 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
76 #include <boost/algorithm/string/join.hpp>
77 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
78 #include <boost/filesystem.hpp>
79 #include <boost/filesystem/fstream.hpp>
80 #include <boost/foreach.hpp>
81 #include <boost/program_options/detail/config_file.hpp>
82 #include <boost/program_options/parsers.hpp>
83 #include <boost/thread.hpp>
84 #include <openssl/crypto.h>
85 #include <openssl/rand.h>
86 #include <openssl/conf.h>
88 // Work around clang compilation problem in Boost 1.46:
89 // /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
90 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
91 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
92 namespace boost {
94 namespace program_options {
95 std::string to_internal(const std::string&);
98 } // namespace boost
100 using namespace std;
102 map<string, string> mapArgs;
103 map<string, vector<string> > mapMultiArgs;
104 bool fDebug = false;
105 bool fPrintToConsole = false;
106 bool fPrintToDebugLog = true;
107 bool fDaemon = false;
108 bool fServer = false;
109 string strMiscWarning;
110 bool fLogTimestamps = false;
111 bool fLogIPs = false;
112 volatile bool fReopenDebugLog = false;
113 CTranslationInterface translationInterface;
115 /** Init OpenSSL library multithreading support */
116 static CCriticalSection** ppmutexOpenSSL;
117 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
119 if (mode & CRYPTO_LOCK) {
120 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
121 } else {
122 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
126 // Init
127 class CInit
129 public:
130 CInit()
132 // Init OpenSSL library multithreading support
133 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
134 for (int i = 0; i < CRYPTO_num_locks(); i++)
135 ppmutexOpenSSL[i] = new CCriticalSection();
136 CRYPTO_set_locking_callback(locking_callback);
138 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
139 // We don't use them so we don't require the config. However some of our libs may call functions
140 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
141 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
142 // that the config appears to have been loaded and there are no modules/engines available.
143 OPENSSL_no_config();
145 #ifdef WIN32
146 // Seed OpenSSL PRNG with current contents of the screen
147 RAND_screen();
148 #endif
150 // Seed OpenSSL PRNG with performance counter
151 RandAddSeed();
153 ~CInit()
155 // Securely erase the memory used by the PRNG
156 RAND_cleanup();
157 // Shutdown OpenSSL library multithreading support
158 CRYPTO_set_locking_callback(NULL);
159 for (int i = 0; i < CRYPTO_num_locks(); i++)
160 delete ppmutexOpenSSL[i];
161 OPENSSL_free(ppmutexOpenSSL);
164 instance_of_cinit;
167 * LogPrintf() has been broken a couple of times now
168 * by well-meaning people adding mutexes in the most straightforward way.
169 * It breaks because it may be called by global destructors during shutdown.
170 * Since the order of destruction of static/global objects is undefined,
171 * defining a mutex as a global object doesn't work (the mutex gets
172 * destroyed, and then some later destructor calls OutputDebugStringF,
173 * maybe indirectly, and you get a core dump at shutdown trying to lock
174 * the mutex).
177 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
180 * We use boost::call_once() to make sure mutexDebugLog and
181 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
183 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
184 * are leaked on exit. This is ugly, but will be cleaned up by
185 * the OS/libc. When the shutdown sequence is fully audited and
186 * tested, explicit destruction of these objects can be implemented.
188 static FILE* fileout = NULL;
189 static boost::mutex* mutexDebugLog = NULL;
190 static list<string> *vMsgsBeforeOpenLog;
192 static int FileWriteStr(const std::string &str, FILE *fp)
194 return fwrite(str.data(), 1, str.size(), fp);
197 static void DebugPrintInit()
199 assert(mutexDebugLog == NULL);
200 mutexDebugLog = new boost::mutex();
201 vMsgsBeforeOpenLog = new list<string>;
204 void OpenDebugLog()
206 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
207 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
209 assert(fileout == NULL);
210 assert(vMsgsBeforeOpenLog);
211 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
212 fileout = fopen(pathDebug.string().c_str(), "a");
213 if (fileout) setbuf(fileout, NULL); // unbuffered
215 // dump buffered messages from before we opened the log
216 while (!vMsgsBeforeOpenLog->empty()) {
217 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
218 vMsgsBeforeOpenLog->pop_front();
221 delete vMsgsBeforeOpenLog;
222 vMsgsBeforeOpenLog = NULL;
225 bool LogAcceptCategory(const char* category)
227 if (category != NULL)
229 if (!fDebug)
230 return false;
232 // Give each thread quick access to -debug settings.
233 // This helps prevent issues debugging global destructors,
234 // where mapMultiArgs might be deleted before another
235 // global destructor calls LogPrint()
236 static boost::thread_specific_ptr<set<string> > ptrCategory;
237 if (ptrCategory.get() == NULL)
239 const vector<string>& categories = mapMultiArgs["-debug"];
240 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
241 // thread_specific_ptr automatically deletes the set when the thread ends.
243 const set<string>& setCategories = *ptrCategory.get();
245 // if not debugging everything and not debugging specific category, LogPrint does nothing.
246 if (setCategories.count(string("")) == 0 &&
247 setCategories.count(string("1")) == 0 &&
248 setCategories.count(string(category)) == 0)
249 return false;
251 return true;
255 * fStartedNewLine is a state variable held by the calling context that will
256 * suppress printing of the timestamp when multiple calls are made that don't
257 * end in a newline. Initialize it to true, and hold it, in the calling context.
259 static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine)
261 string strStamped;
263 if (!fLogTimestamps)
264 return str;
266 if (*fStartedNewLine)
267 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()) + ' ' + str;
268 else
269 strStamped = str;
271 if (!str.empty() && str[str.size()-1] == '\n')
272 *fStartedNewLine = true;
273 else
274 *fStartedNewLine = false;
276 return strStamped;
279 int LogPrintStr(const std::string &str)
281 int ret = 0; // Returns total number of characters written
282 static bool fStartedNewLine = true;
283 if (fPrintToConsole)
285 // print to console
286 ret = fwrite(str.data(), 1, str.size(), stdout);
287 fflush(stdout);
289 else if (fPrintToDebugLog)
291 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
292 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
294 string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
296 // buffer if we haven't opened the log yet
297 if (fileout == NULL) {
298 assert(vMsgsBeforeOpenLog);
299 ret = strTimestamped.length();
300 vMsgsBeforeOpenLog->push_back(strTimestamped);
302 else
304 // reopen the log file, if requested
305 if (fReopenDebugLog) {
306 fReopenDebugLog = false;
307 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
308 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
309 setbuf(fileout, NULL); // unbuffered
312 ret = FileWriteStr(strTimestamped, fileout);
315 return ret;
318 /** Interpret string as boolean, for argument parsing */
319 static bool InterpretBool(const std::string& strValue)
321 if (strValue.empty())
322 return true;
323 return (atoi(strValue) != 0);
326 /** Turn -noX into -X=0 */
327 static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
329 if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
331 strKey = "-" + strKey.substr(3);
332 strValue = InterpretBool(strValue) ? "0" : "1";
336 void ParseParameters(int argc, const char* const argv[])
338 mapArgs.clear();
339 mapMultiArgs.clear();
341 for (int i = 1; i < argc; i++)
343 std::string str(argv[i]);
344 std::string strValue;
345 size_t is_index = str.find('=');
346 if (is_index != std::string::npos)
348 strValue = str.substr(is_index+1);
349 str = str.substr(0, is_index);
351 #ifdef WIN32
352 boost::to_lower(str);
353 if (boost::algorithm::starts_with(str, "/"))
354 str = "-" + str.substr(1);
355 #endif
357 if (str[0] != '-')
358 break;
360 // Interpret --foo as -foo.
361 // If both --foo and -foo are set, the last takes effect.
362 if (str.length() > 1 && str[1] == '-')
363 str = str.substr(1);
364 InterpretNegativeSetting(str, strValue);
366 mapArgs[str] = strValue;
367 mapMultiArgs[str].push_back(strValue);
371 std::string GetArg(const std::string& strArg, const std::string& strDefault)
373 if (mapArgs.count(strArg))
374 return mapArgs[strArg];
375 return strDefault;
378 int64_t GetArg(const std::string& strArg, int64_t nDefault)
380 if (mapArgs.count(strArg))
381 return atoi64(mapArgs[strArg]);
382 return nDefault;
385 bool GetBoolArg(const std::string& strArg, bool fDefault)
387 if (mapArgs.count(strArg))
388 return InterpretBool(mapArgs[strArg]);
389 return fDefault;
392 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
394 if (mapArgs.count(strArg))
395 return false;
396 mapArgs[strArg] = strValue;
397 return true;
400 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
402 if (fValue)
403 return SoftSetArg(strArg, std::string("1"));
404 else
405 return SoftSetArg(strArg, std::string("0"));
408 static const int screenWidth = 79;
409 static const int optIndent = 2;
410 static const int msgIndent = 7;
412 std::string HelpMessageGroup(const std::string &message) {
413 return std::string(message) + std::string("\n\n");
416 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
417 return std::string(optIndent,' ') + std::string(option) +
418 std::string("\n") + std::string(msgIndent,' ') +
419 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
420 std::string("\n\n");
423 static std::string FormatException(const std::exception* pex, const char* pszThread)
425 #ifdef WIN32
426 char pszModule[MAX_PATH] = "";
427 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
428 #else
429 const char* pszModule = "bitcoin";
430 #endif
431 if (pex)
432 return strprintf(
433 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
434 else
435 return strprintf(
436 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
439 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
441 std::string message = FormatException(pex, pszThread);
442 LogPrintf("\n\n************************\n%s\n", message);
443 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
444 strMiscWarning = message;
447 boost::filesystem::path GetDefaultDataDir()
449 namespace fs = boost::filesystem;
450 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
451 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
452 // Mac: ~/Library/Application Support/Bitcoin
453 // Unix: ~/.bitcoin
454 #ifdef WIN32
455 // Windows
456 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
457 #else
458 fs::path pathRet;
459 char* pszHome = getenv("HOME");
460 if (pszHome == NULL || strlen(pszHome) == 0)
461 pathRet = fs::path("/");
462 else
463 pathRet = fs::path(pszHome);
464 #ifdef MAC_OSX
465 // Mac
466 pathRet /= "Library/Application Support";
467 TryCreateDirectory(pathRet);
468 return pathRet / "Bitcoin";
469 #else
470 // Unix
471 return pathRet / ".bitcoin";
472 #endif
473 #endif
476 static boost::filesystem::path pathCached;
477 static boost::filesystem::path pathCachedNetSpecific;
478 static CCriticalSection csPathCached;
480 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
482 namespace fs = boost::filesystem;
484 LOCK(csPathCached);
486 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
488 // This can be called during exceptions by LogPrintf(), so we cache the
489 // value so we don't have to do memory allocations after that.
490 if (!path.empty())
491 return path;
493 if (mapArgs.count("-datadir")) {
494 path = fs::system_complete(mapArgs["-datadir"]);
495 if (!fs::is_directory(path)) {
496 path = "";
497 return path;
499 } else {
500 path = GetDefaultDataDir();
502 if (fNetSpecific)
503 path /= BaseParams().DataDir();
505 fs::create_directories(path);
507 return path;
510 void ClearDatadirCache()
512 pathCached = boost::filesystem::path();
513 pathCachedNetSpecific = boost::filesystem::path();
516 boost::filesystem::path GetConfigFile()
518 boost::filesystem::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
519 if (!pathConfigFile.is_complete())
520 pathConfigFile = GetDataDir(false) / pathConfigFile;
522 return pathConfigFile;
525 void ReadConfigFile(map<string, string>& mapSettingsRet,
526 map<string, vector<string> >& mapMultiSettingsRet)
528 boost::filesystem::ifstream streamConfig(GetConfigFile());
529 if (!streamConfig.good())
530 return; // No bitcoin.conf file is OK
532 set<string> setOptions;
533 setOptions.insert("*");
535 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
537 // Don't overwrite existing settings so command line settings override bitcoin.conf
538 string strKey = string("-") + it->string_key;
539 string strValue = it->value[0];
540 InterpretNegativeSetting(strKey, strValue);
541 if (mapSettingsRet.count(strKey) == 0)
542 mapSettingsRet[strKey] = strValue;
543 mapMultiSettingsRet[strKey].push_back(strValue);
545 // If datadir is changed in .conf file:
546 ClearDatadirCache();
549 #ifndef WIN32
550 boost::filesystem::path GetPidFile()
552 boost::filesystem::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
553 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
554 return pathPidFile;
557 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
559 FILE* file = fopen(path.string().c_str(), "w");
560 if (file)
562 fprintf(file, "%d\n", pid);
563 fclose(file);
566 #endif
568 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
570 #ifdef WIN32
571 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
572 MOVEFILE_REPLACE_EXISTING) != 0;
573 #else
574 int rc = std::rename(src.string().c_str(), dest.string().c_str());
575 return (rc == 0);
576 #endif /* WIN32 */
580 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
581 * Specifically handles case where path p exists, but it wasn't possible for the user to
582 * write to the parent directory.
584 bool TryCreateDirectory(const boost::filesystem::path& p)
588 return boost::filesystem::create_directory(p);
589 } catch (const boost::filesystem::filesystem_error&) {
590 if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
591 throw;
594 // create_directory didn't create the directory, it had to have existed already
595 return false;
598 void FileCommit(FILE *fileout)
600 fflush(fileout); // harmless if redundantly called
601 #ifdef WIN32
602 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
603 FlushFileBuffers(hFile);
604 #else
605 #if defined(__linux__) || defined(__NetBSD__)
606 fdatasync(fileno(fileout));
607 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
608 fcntl(fileno(fileout), F_FULLFSYNC, 0);
609 #else
610 fsync(fileno(fileout));
611 #endif
612 #endif
615 bool TruncateFile(FILE *file, unsigned int length) {
616 #if defined(WIN32)
617 return _chsize(_fileno(file), length) == 0;
618 #else
619 return ftruncate(fileno(file), length) == 0;
620 #endif
624 * this function tries to raise the file descriptor limit to the requested number.
625 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
627 int RaiseFileDescriptorLimit(int nMinFD) {
628 #if defined(WIN32)
629 return 2048;
630 #else
631 struct rlimit limitFD;
632 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
633 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
634 limitFD.rlim_cur = nMinFD;
635 if (limitFD.rlim_cur > limitFD.rlim_max)
636 limitFD.rlim_cur = limitFD.rlim_max;
637 setrlimit(RLIMIT_NOFILE, &limitFD);
638 getrlimit(RLIMIT_NOFILE, &limitFD);
640 return limitFD.rlim_cur;
642 return nMinFD; // getrlimit failed, assume it's fine
643 #endif
647 * this function tries to make a particular range of a file allocated (corresponding to disk space)
648 * it is advisory, and the range specified in the arguments will never contain live data
650 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
651 #if defined(WIN32)
652 // Windows-specific version
653 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
654 LARGE_INTEGER nFileSize;
655 int64_t nEndPos = (int64_t)offset + length;
656 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
657 nFileSize.u.HighPart = nEndPos >> 32;
658 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
659 SetEndOfFile(hFile);
660 #elif defined(MAC_OSX)
661 // OSX specific version
662 fstore_t fst;
663 fst.fst_flags = F_ALLOCATECONTIG;
664 fst.fst_posmode = F_PEOFPOSMODE;
665 fst.fst_offset = 0;
666 fst.fst_length = (off_t)offset + length;
667 fst.fst_bytesalloc = 0;
668 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
669 fst.fst_flags = F_ALLOCATEALL;
670 fcntl(fileno(file), F_PREALLOCATE, &fst);
672 ftruncate(fileno(file), fst.fst_length);
673 #elif defined(__linux__)
674 // Version using posix_fallocate
675 off_t nEndPos = (off_t)offset + length;
676 posix_fallocate(fileno(file), 0, nEndPos);
677 #else
678 // Fallback version
679 // TODO: just write one byte per block
680 static const char buf[65536] = {};
681 fseek(file, offset, SEEK_SET);
682 while (length > 0) {
683 unsigned int now = 65536;
684 if (length < now)
685 now = length;
686 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
687 length -= now;
689 #endif
692 void ShrinkDebugFile()
694 // Scroll debug.log if it's getting too big
695 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
696 FILE* file = fopen(pathLog.string().c_str(), "r");
697 if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
699 // Restart the file with some of the end
700 std::vector <char> vch(200000,0);
701 fseek(file, -((long)vch.size()), SEEK_END);
702 int nBytes = fread(begin_ptr(vch), 1, vch.size(), file);
703 fclose(file);
705 file = fopen(pathLog.string().c_str(), "w");
706 if (file)
708 fwrite(begin_ptr(vch), 1, nBytes, file);
709 fclose(file);
712 else if (file != NULL)
713 fclose(file);
716 #ifdef WIN32
717 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
719 namespace fs = boost::filesystem;
721 char pszPath[MAX_PATH] = "";
723 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
725 return fs::path(pszPath);
728 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
729 return fs::path("");
731 #endif
733 boost::filesystem::path GetTempPath() {
734 #if BOOST_FILESYSTEM_VERSION == 3
735 return boost::filesystem::temp_directory_path();
736 #else
737 // TODO: remove when we don't support filesystem v2 anymore
738 boost::filesystem::path path;
739 #ifdef WIN32
740 char pszPath[MAX_PATH] = "";
742 if (GetTempPathA(MAX_PATH, pszPath))
743 path = boost::filesystem::path(pszPath);
744 #else
745 path = boost::filesystem::path("/tmp");
746 #endif
747 if (path.empty() || !boost::filesystem::is_directory(path)) {
748 LogPrintf("GetTempPath(): failed to find temp path\n");
749 return boost::filesystem::path("");
751 return path;
752 #endif
755 void runCommand(const std::string& strCommand)
757 int nErr = ::system(strCommand.c_str());
758 if (nErr)
759 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
762 void RenameThread(const char* name)
764 #if defined(PR_SET_NAME)
765 // Only the first 15 characters are used (16 - NUL terminator)
766 ::prctl(PR_SET_NAME, name, 0, 0, 0);
767 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
768 pthread_set_name_np(pthread_self(), name);
770 #elif defined(MAC_OSX)
771 pthread_setname_np(name);
772 #else
773 // Prevent warnings for unused parameters...
774 (void)name;
775 #endif
778 void SetupEnvironment()
780 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
781 // may be invalid, in which case the "C" locale is used as fallback.
782 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
783 try {
784 std::locale(""); // Raises a runtime error if current locale is invalid
785 } catch (const std::runtime_error&) {
786 setenv("LC_ALL", "C", 1);
788 #endif
789 // The path locale is lazy initialized and to avoid deinitialization errors
790 // in multithreading environments, it is set explicitly by the main thread.
791 // A dummy locale is used to extract the internal default locale, used by
792 // boost::filesystem::path, which is then used to explicitly imbue the path.
793 std::locale loc = boost::filesystem::path::imbue(std::locale::classic());
794 boost::filesystem::path::imbue(loc);
797 bool SetupNetworking()
799 #ifdef WIN32
800 // Initialize Windows Sockets
801 WSADATA wsadata;
802 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
803 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
804 return false;
805 #endif
806 return true;
809 void SetThreadPriority(int nPriority)
811 #ifdef WIN32
812 SetThreadPriority(GetCurrentThread(), nPriority);
813 #else // WIN32
814 #ifdef PRIO_THREAD
815 setpriority(PRIO_THREAD, 0, nPriority);
816 #else // PRIO_THREAD
817 setpriority(PRIO_PROCESS, 0, nPriority);
818 #endif // PRIO_THREAD
819 #endif // WIN32
822 int GetNumCores()
824 #if BOOST_VERSION >= 105600
825 return boost::thread::physical_concurrency();
826 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
827 return boost::thread::hardware_concurrency();
828 #endif