Merge #9226: Remove fNetworkNode and pnodeLocalHost.
[bitcoinplatinum.git] / src / util.cpp
blob332e077627e46dbed1924f43189519e1695b8ae1
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
103 const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
105 map<string, string> mapArgs;
106 map<string, vector<string> > mapMultiArgs;
107 bool fDebug = false;
108 bool fPrintToConsole = false;
109 bool fPrintToDebugLog = true;
110 string strMiscWarning;
111 bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
112 bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
113 bool fLogIPs = DEFAULT_LOGIPS;
114 std::atomic<bool> fReopenDebugLog(false);
115 CTranslationInterface translationInterface;
117 /** Init OpenSSL library multithreading support */
118 static CCriticalSection** ppmutexOpenSSL;
119 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
121 if (mode & CRYPTO_LOCK) {
122 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
123 } else {
124 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
128 // Init
129 class CInit
131 public:
132 CInit()
134 // Init OpenSSL library multithreading support
135 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
136 for (int i = 0; i < CRYPTO_num_locks(); i++)
137 ppmutexOpenSSL[i] = new CCriticalSection();
138 CRYPTO_set_locking_callback(locking_callback);
140 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
141 // We don't use them so we don't require the config. However some of our libs may call functions
142 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
143 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
144 // that the config appears to have been loaded and there are no modules/engines available.
145 OPENSSL_no_config();
147 #ifdef WIN32
148 // Seed OpenSSL PRNG with current contents of the screen
149 RAND_screen();
150 #endif
152 // Seed OpenSSL PRNG with performance counter
153 RandAddSeed();
155 ~CInit()
157 // Securely erase the memory used by the PRNG
158 RAND_cleanup();
159 // Shutdown OpenSSL library multithreading support
160 CRYPTO_set_locking_callback(NULL);
161 for (int i = 0; i < CRYPTO_num_locks(); i++)
162 delete ppmutexOpenSSL[i];
163 OPENSSL_free(ppmutexOpenSSL);
166 instance_of_cinit;
169 * LogPrintf() has been broken a couple of times now
170 * by well-meaning people adding mutexes in the most straightforward way.
171 * It breaks because it may be called by global destructors during shutdown.
172 * Since the order of destruction of static/global objects is undefined,
173 * defining a mutex as a global object doesn't work (the mutex gets
174 * destroyed, and then some later destructor calls OutputDebugStringF,
175 * maybe indirectly, and you get a core dump at shutdown trying to lock
176 * the mutex).
179 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
182 * We use boost::call_once() to make sure mutexDebugLog and
183 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
185 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
186 * are leaked on exit. This is ugly, but will be cleaned up by
187 * the OS/libc. When the shutdown sequence is fully audited and
188 * tested, explicit destruction of these objects can be implemented.
190 static FILE* fileout = NULL;
191 static boost::mutex* mutexDebugLog = NULL;
192 static list<string> *vMsgsBeforeOpenLog;
194 static int FileWriteStr(const std::string &str, FILE *fp)
196 return fwrite(str.data(), 1, str.size(), fp);
199 static void DebugPrintInit()
201 assert(mutexDebugLog == NULL);
202 mutexDebugLog = new boost::mutex();
203 vMsgsBeforeOpenLog = new list<string>;
206 void OpenDebugLog()
208 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
209 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
211 assert(fileout == NULL);
212 assert(vMsgsBeforeOpenLog);
213 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
214 fileout = fopen(pathDebug.string().c_str(), "a");
215 if (fileout) setbuf(fileout, NULL); // unbuffered
217 // dump buffered messages from before we opened the log
218 while (!vMsgsBeforeOpenLog->empty()) {
219 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
220 vMsgsBeforeOpenLog->pop_front();
223 delete vMsgsBeforeOpenLog;
224 vMsgsBeforeOpenLog = NULL;
227 bool LogAcceptCategory(const char* category)
229 if (category != NULL)
231 if (!fDebug)
232 return false;
234 // Give each thread quick access to -debug settings.
235 // This helps prevent issues debugging global destructors,
236 // where mapMultiArgs might be deleted before another
237 // global destructor calls LogPrint()
238 static boost::thread_specific_ptr<set<string> > ptrCategory;
239 if (ptrCategory.get() == NULL)
241 const vector<string>& categories = mapMultiArgs["-debug"];
242 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
243 // thread_specific_ptr automatically deletes the set when the thread ends.
245 const set<string>& setCategories = *ptrCategory.get();
247 // if not debugging everything and not debugging specific category, LogPrint does nothing.
248 if (setCategories.count(string("")) == 0 &&
249 setCategories.count(string("1")) == 0 &&
250 setCategories.count(string(category)) == 0)
251 return false;
253 return true;
257 * fStartedNewLine is a state variable held by the calling context that will
258 * suppress printing of the timestamp when multiple calls are made that don't
259 * end in a newline. Initialize it to true, and hold it, in the calling context.
261 static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine)
263 string strStamped;
265 if (!fLogTimestamps)
266 return str;
268 if (*fStartedNewLine) {
269 int64_t nTimeMicros = GetLogTimeMicros();
270 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
271 if (fLogTimeMicros)
272 strStamped += strprintf(".%06d", nTimeMicros%1000000);
273 strStamped += ' ' + str;
274 } else
275 strStamped = str;
277 if (!str.empty() && str[str.size()-1] == '\n')
278 *fStartedNewLine = true;
279 else
280 *fStartedNewLine = false;
282 return strStamped;
285 int LogPrintStr(const std::string &str)
287 int ret = 0; // Returns total number of characters written
288 static bool fStartedNewLine = true;
290 string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
292 if (fPrintToConsole)
294 // print to console
295 ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
296 fflush(stdout);
298 else if (fPrintToDebugLog)
300 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
301 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
303 // buffer if we haven't opened the log yet
304 if (fileout == NULL) {
305 assert(vMsgsBeforeOpenLog);
306 ret = strTimestamped.length();
307 vMsgsBeforeOpenLog->push_back(strTimestamped);
309 else
311 // reopen the log file, if requested
312 if (fReopenDebugLog) {
313 fReopenDebugLog = false;
314 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
315 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
316 setbuf(fileout, NULL); // unbuffered
319 ret = FileWriteStr(strTimestamped, fileout);
322 return ret;
325 /** Interpret string as boolean, for argument parsing */
326 static bool InterpretBool(const std::string& strValue)
328 if (strValue.empty())
329 return true;
330 return (atoi(strValue) != 0);
333 /** Turn -noX into -X=0 */
334 static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
336 if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
338 strKey = "-" + strKey.substr(3);
339 strValue = InterpretBool(strValue) ? "0" : "1";
343 void ParseParameters(int argc, const char* const argv[])
345 mapArgs.clear();
346 mapMultiArgs.clear();
348 for (int i = 1; i < argc; i++)
350 std::string str(argv[i]);
351 std::string strValue;
352 size_t is_index = str.find('=');
353 if (is_index != std::string::npos)
355 strValue = str.substr(is_index+1);
356 str = str.substr(0, is_index);
358 #ifdef WIN32
359 boost::to_lower(str);
360 if (boost::algorithm::starts_with(str, "/"))
361 str = "-" + str.substr(1);
362 #endif
364 if (str[0] != '-')
365 break;
367 // Interpret --foo as -foo.
368 // If both --foo and -foo are set, the last takes effect.
369 if (str.length() > 1 && str[1] == '-')
370 str = str.substr(1);
371 InterpretNegativeSetting(str, strValue);
373 mapArgs[str] = strValue;
374 mapMultiArgs[str].push_back(strValue);
378 std::string GetArg(const std::string& strArg, const std::string& strDefault)
380 if (mapArgs.count(strArg))
381 return mapArgs[strArg];
382 return strDefault;
385 int64_t GetArg(const std::string& strArg, int64_t nDefault)
387 if (mapArgs.count(strArg))
388 return atoi64(mapArgs[strArg]);
389 return nDefault;
392 bool GetBoolArg(const std::string& strArg, bool fDefault)
394 if (mapArgs.count(strArg))
395 return InterpretBool(mapArgs[strArg]);
396 return fDefault;
399 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
401 if (mapArgs.count(strArg))
402 return false;
403 mapArgs[strArg] = strValue;
404 return true;
407 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
409 if (fValue)
410 return SoftSetArg(strArg, std::string("1"));
411 else
412 return SoftSetArg(strArg, std::string("0"));
415 static const int screenWidth = 79;
416 static const int optIndent = 2;
417 static const int msgIndent = 7;
419 std::string HelpMessageGroup(const std::string &message) {
420 return std::string(message) + std::string("\n\n");
423 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
424 return std::string(optIndent,' ') + std::string(option) +
425 std::string("\n") + std::string(msgIndent,' ') +
426 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
427 std::string("\n\n");
430 static std::string FormatException(const std::exception* pex, const char* pszThread)
432 #ifdef WIN32
433 char pszModule[MAX_PATH] = "";
434 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
435 #else
436 const char* pszModule = "bitcoin";
437 #endif
438 if (pex)
439 return strprintf(
440 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
441 else
442 return strprintf(
443 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
446 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
448 std::string message = FormatException(pex, pszThread);
449 LogPrintf("\n\n************************\n%s\n", message);
450 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
453 boost::filesystem::path GetDefaultDataDir()
455 namespace fs = boost::filesystem;
456 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
457 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
458 // Mac: ~/Library/Application Support/Bitcoin
459 // Unix: ~/.bitcoin
460 #ifdef WIN32
461 // Windows
462 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
463 #else
464 fs::path pathRet;
465 char* pszHome = getenv("HOME");
466 if (pszHome == NULL || strlen(pszHome) == 0)
467 pathRet = fs::path("/");
468 else
469 pathRet = fs::path(pszHome);
470 #ifdef MAC_OSX
471 // Mac
472 return pathRet / "Library/Application Support/Bitcoin";
473 #else
474 // Unix
475 return pathRet / ".bitcoin";
476 #endif
477 #endif
480 static boost::filesystem::path pathCached;
481 static boost::filesystem::path pathCachedNetSpecific;
482 static CCriticalSection csPathCached;
484 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
486 namespace fs = boost::filesystem;
488 LOCK(csPathCached);
490 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
492 // This can be called during exceptions by LogPrintf(), so we cache the
493 // value so we don't have to do memory allocations after that.
494 if (!path.empty())
495 return path;
497 if (mapArgs.count("-datadir")) {
498 path = fs::system_complete(mapArgs["-datadir"]);
499 if (!fs::is_directory(path)) {
500 path = "";
501 return path;
503 } else {
504 path = GetDefaultDataDir();
506 if (fNetSpecific)
507 path /= BaseParams().DataDir();
509 fs::create_directories(path);
511 return path;
514 void ClearDatadirCache()
516 pathCached = boost::filesystem::path();
517 pathCachedNetSpecific = boost::filesystem::path();
520 boost::filesystem::path GetConfigFile(const std::string& confPath)
522 boost::filesystem::path pathConfigFile(confPath);
523 if (!pathConfigFile.is_complete())
524 pathConfigFile = GetDataDir(false) / pathConfigFile;
526 return pathConfigFile;
529 void ReadConfigFile(const std::string& confPath,
530 map<string, string>& mapSettingsRet,
531 map<string, vector<string> >& mapMultiSettingsRet)
533 boost::filesystem::ifstream streamConfig(GetConfigFile(confPath));
534 if (!streamConfig.good())
535 return; // No bitcoin.conf file is OK
537 set<string> setOptions;
538 setOptions.insert("*");
540 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
542 // Don't overwrite existing settings so command line settings override bitcoin.conf
543 string strKey = string("-") + it->string_key;
544 string strValue = it->value[0];
545 InterpretNegativeSetting(strKey, strValue);
546 if (mapSettingsRet.count(strKey) == 0)
547 mapSettingsRet[strKey] = strValue;
548 mapMultiSettingsRet[strKey].push_back(strValue);
550 // If datadir is changed in .conf file:
551 ClearDatadirCache();
554 #ifndef WIN32
555 boost::filesystem::path GetPidFile()
557 boost::filesystem::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME));
558 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
559 return pathPidFile;
562 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
564 FILE* file = fopen(path.string().c_str(), "w");
565 if (file)
567 fprintf(file, "%d\n", pid);
568 fclose(file);
571 #endif
573 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
575 #ifdef WIN32
576 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
577 MOVEFILE_REPLACE_EXISTING) != 0;
578 #else
579 int rc = std::rename(src.string().c_str(), dest.string().c_str());
580 return (rc == 0);
581 #endif /* WIN32 */
585 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
586 * Specifically handles case where path p exists, but it wasn't possible for the user to
587 * write to the parent directory.
589 bool TryCreateDirectory(const boost::filesystem::path& p)
593 return boost::filesystem::create_directory(p);
594 } catch (const boost::filesystem::filesystem_error&) {
595 if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
596 throw;
599 // create_directory didn't create the directory, it had to have existed already
600 return false;
603 void FileCommit(FILE *file)
605 fflush(file); // harmless if redundantly called
606 #ifdef WIN32
607 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
608 FlushFileBuffers(hFile);
609 #else
610 #if defined(__linux__) || defined(__NetBSD__)
611 fdatasync(fileno(file));
612 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
613 fcntl(fileno(file), F_FULLFSYNC, 0);
614 #else
615 fsync(fileno(file));
616 #endif
617 #endif
620 bool TruncateFile(FILE *file, unsigned int length) {
621 #if defined(WIN32)
622 return _chsize(_fileno(file), length) == 0;
623 #else
624 return ftruncate(fileno(file), length) == 0;
625 #endif
629 * this function tries to raise the file descriptor limit to the requested number.
630 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
632 int RaiseFileDescriptorLimit(int nMinFD) {
633 #if defined(WIN32)
634 return 2048;
635 #else
636 struct rlimit limitFD;
637 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
638 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
639 limitFD.rlim_cur = nMinFD;
640 if (limitFD.rlim_cur > limitFD.rlim_max)
641 limitFD.rlim_cur = limitFD.rlim_max;
642 setrlimit(RLIMIT_NOFILE, &limitFD);
643 getrlimit(RLIMIT_NOFILE, &limitFD);
645 return limitFD.rlim_cur;
647 return nMinFD; // getrlimit failed, assume it's fine
648 #endif
652 * this function tries to make a particular range of a file allocated (corresponding to disk space)
653 * it is advisory, and the range specified in the arguments will never contain live data
655 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
656 #if defined(WIN32)
657 // Windows-specific version
658 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
659 LARGE_INTEGER nFileSize;
660 int64_t nEndPos = (int64_t)offset + length;
661 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
662 nFileSize.u.HighPart = nEndPos >> 32;
663 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
664 SetEndOfFile(hFile);
665 #elif defined(MAC_OSX)
666 // OSX specific version
667 fstore_t fst;
668 fst.fst_flags = F_ALLOCATECONTIG;
669 fst.fst_posmode = F_PEOFPOSMODE;
670 fst.fst_offset = 0;
671 fst.fst_length = (off_t)offset + length;
672 fst.fst_bytesalloc = 0;
673 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
674 fst.fst_flags = F_ALLOCATEALL;
675 fcntl(fileno(file), F_PREALLOCATE, &fst);
677 ftruncate(fileno(file), fst.fst_length);
678 #elif defined(__linux__)
679 // Version using posix_fallocate
680 off_t nEndPos = (off_t)offset + length;
681 posix_fallocate(fileno(file), 0, nEndPos);
682 #else
683 // Fallback version
684 // TODO: just write one byte per block
685 static const char buf[65536] = {};
686 fseek(file, offset, SEEK_SET);
687 while (length > 0) {
688 unsigned int now = 65536;
689 if (length < now)
690 now = length;
691 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
692 length -= now;
694 #endif
697 void ShrinkDebugFile()
699 // Scroll debug.log if it's getting too big
700 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
701 FILE* file = fopen(pathLog.string().c_str(), "r");
702 if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
704 // Restart the file with some of the end
705 std::vector <char> vch(200000,0);
706 fseek(file, -((long)vch.size()), SEEK_END);
707 int nBytes = fread(begin_ptr(vch), 1, vch.size(), file);
708 fclose(file);
710 file = fopen(pathLog.string().c_str(), "w");
711 if (file)
713 fwrite(begin_ptr(vch), 1, nBytes, file);
714 fclose(file);
717 else if (file != NULL)
718 fclose(file);
721 #ifdef WIN32
722 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
724 namespace fs = boost::filesystem;
726 char pszPath[MAX_PATH] = "";
728 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
730 return fs::path(pszPath);
733 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
734 return fs::path("");
736 #endif
738 void runCommand(const std::string& strCommand)
740 int nErr = ::system(strCommand.c_str());
741 if (nErr)
742 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
745 void RenameThread(const char* name)
747 #if defined(PR_SET_NAME)
748 // Only the first 15 characters are used (16 - NUL terminator)
749 ::prctl(PR_SET_NAME, name, 0, 0, 0);
750 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
751 pthread_set_name_np(pthread_self(), name);
753 #elif defined(MAC_OSX)
754 pthread_setname_np(name);
755 #else
756 // Prevent warnings for unused parameters...
757 (void)name;
758 #endif
761 void SetupEnvironment()
763 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
764 // may be invalid, in which case the "C" locale is used as fallback.
765 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
766 try {
767 std::locale(""); // Raises a runtime error if current locale is invalid
768 } catch (const std::runtime_error&) {
769 setenv("LC_ALL", "C", 1);
771 #endif
772 // The path locale is lazy initialized and to avoid deinitialization errors
773 // in multithreading environments, it is set explicitly by the main thread.
774 // A dummy locale is used to extract the internal default locale, used by
775 // boost::filesystem::path, which is then used to explicitly imbue the path.
776 std::locale loc = boost::filesystem::path::imbue(std::locale::classic());
777 boost::filesystem::path::imbue(loc);
780 bool SetupNetworking()
782 #ifdef WIN32
783 // Initialize Windows Sockets
784 WSADATA wsadata;
785 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
786 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
787 return false;
788 #endif
789 return true;
792 int GetNumCores()
794 #if BOOST_VERSION >= 105600
795 return boost::thread::physical_concurrency();
796 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
797 return boost::thread::hardware_concurrency();
798 #endif
801 std::string CopyrightHolders(const std::string& strPrefix)
803 std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
805 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
806 if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) {
807 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
809 return strCopyrightHolders;