Remove unused var UNLIKELY_PCT from fees.h
[bitcoinplatinum.git] / src / util.cpp
blobc20ede62210b165f951933bbecb8b751ca06add8
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 bool fServer = false;
111 string strMiscWarning;
112 bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
113 bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
114 bool fLogIPs = DEFAULT_LOGIPS;
115 std::atomic<bool> fReopenDebugLog(false);
116 CTranslationInterface translationInterface;
118 /** Init OpenSSL library multithreading support */
119 static CCriticalSection** ppmutexOpenSSL;
120 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
122 if (mode & CRYPTO_LOCK) {
123 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
124 } else {
125 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
129 // Init
130 class CInit
132 public:
133 CInit()
135 // Init OpenSSL library multithreading support
136 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
137 for (int i = 0; i < CRYPTO_num_locks(); i++)
138 ppmutexOpenSSL[i] = new CCriticalSection();
139 CRYPTO_set_locking_callback(locking_callback);
141 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
142 // We don't use them so we don't require the config. However some of our libs may call functions
143 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
144 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
145 // that the config appears to have been loaded and there are no modules/engines available.
146 OPENSSL_no_config();
148 #ifdef WIN32
149 // Seed OpenSSL PRNG with current contents of the screen
150 RAND_screen();
151 #endif
153 // Seed OpenSSL PRNG with performance counter
154 RandAddSeed();
156 ~CInit()
158 // Securely erase the memory used by the PRNG
159 RAND_cleanup();
160 // Shutdown OpenSSL library multithreading support
161 CRYPTO_set_locking_callback(NULL);
162 for (int i = 0; i < CRYPTO_num_locks(); i++)
163 delete ppmutexOpenSSL[i];
164 OPENSSL_free(ppmutexOpenSSL);
167 instance_of_cinit;
170 * LogPrintf() has been broken a couple of times now
171 * by well-meaning people adding mutexes in the most straightforward way.
172 * It breaks because it may be called by global destructors during shutdown.
173 * Since the order of destruction of static/global objects is undefined,
174 * defining a mutex as a global object doesn't work (the mutex gets
175 * destroyed, and then some later destructor calls OutputDebugStringF,
176 * maybe indirectly, and you get a core dump at shutdown trying to lock
177 * the mutex).
180 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
183 * We use boost::call_once() to make sure mutexDebugLog and
184 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
186 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
187 * are leaked on exit. This is ugly, but will be cleaned up by
188 * the OS/libc. When the shutdown sequence is fully audited and
189 * tested, explicit destruction of these objects can be implemented.
191 static FILE* fileout = NULL;
192 static boost::mutex* mutexDebugLog = NULL;
193 static list<string> *vMsgsBeforeOpenLog;
195 static int FileWriteStr(const std::string &str, FILE *fp)
197 return fwrite(str.data(), 1, str.size(), fp);
200 static void DebugPrintInit()
202 assert(mutexDebugLog == NULL);
203 mutexDebugLog = new boost::mutex();
204 vMsgsBeforeOpenLog = new list<string>;
207 void OpenDebugLog()
209 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
210 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
212 assert(fileout == NULL);
213 assert(vMsgsBeforeOpenLog);
214 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
215 fileout = fopen(pathDebug.string().c_str(), "a");
216 if (fileout) setbuf(fileout, NULL); // unbuffered
218 // dump buffered messages from before we opened the log
219 while (!vMsgsBeforeOpenLog->empty()) {
220 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
221 vMsgsBeforeOpenLog->pop_front();
224 delete vMsgsBeforeOpenLog;
225 vMsgsBeforeOpenLog = NULL;
228 bool LogAcceptCategory(const char* category)
230 if (category != NULL)
232 if (!fDebug)
233 return false;
235 // Give each thread quick access to -debug settings.
236 // This helps prevent issues debugging global destructors,
237 // where mapMultiArgs might be deleted before another
238 // global destructor calls LogPrint()
239 static boost::thread_specific_ptr<set<string> > ptrCategory;
240 if (ptrCategory.get() == NULL)
242 const vector<string>& categories = mapMultiArgs["-debug"];
243 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
244 // thread_specific_ptr automatically deletes the set when the thread ends.
246 const set<string>& setCategories = *ptrCategory.get();
248 // if not debugging everything and not debugging specific category, LogPrint does nothing.
249 if (setCategories.count(string("")) == 0 &&
250 setCategories.count(string("1")) == 0 &&
251 setCategories.count(string(category)) == 0)
252 return false;
254 return true;
258 * fStartedNewLine is a state variable held by the calling context that will
259 * suppress printing of the timestamp when multiple calls are made that don't
260 * end in a newline. Initialize it to true, and hold it, in the calling context.
262 static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine)
264 string strStamped;
266 if (!fLogTimestamps)
267 return str;
269 if (*fStartedNewLine) {
270 int64_t nTimeMicros = GetLogTimeMicros();
271 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
272 if (fLogTimeMicros)
273 strStamped += strprintf(".%06d", nTimeMicros%1000000);
274 strStamped += ' ' + str;
275 } else
276 strStamped = str;
278 if (!str.empty() && str[str.size()-1] == '\n')
279 *fStartedNewLine = true;
280 else
281 *fStartedNewLine = false;
283 return strStamped;
286 int LogPrintStr(const std::string &str)
288 int ret = 0; // Returns total number of characters written
289 static bool fStartedNewLine = true;
291 string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
293 if (fPrintToConsole)
295 // print to console
296 ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
297 fflush(stdout);
299 else if (fPrintToDebugLog)
301 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
302 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
304 // buffer if we haven't opened the log yet
305 if (fileout == NULL) {
306 assert(vMsgsBeforeOpenLog);
307 ret = strTimestamped.length();
308 vMsgsBeforeOpenLog->push_back(strTimestamped);
310 else
312 // reopen the log file, if requested
313 if (fReopenDebugLog) {
314 fReopenDebugLog = false;
315 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
316 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
317 setbuf(fileout, NULL); // unbuffered
320 ret = FileWriteStr(strTimestamped, fileout);
323 return ret;
326 /** Interpret string as boolean, for argument parsing */
327 static bool InterpretBool(const std::string& strValue)
329 if (strValue.empty())
330 return true;
331 return (atoi(strValue) != 0);
334 /** Turn -noX into -X=0 */
335 static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
337 if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
339 strKey = "-" + strKey.substr(3);
340 strValue = InterpretBool(strValue) ? "0" : "1";
344 void ParseParameters(int argc, const char* const argv[])
346 mapArgs.clear();
347 mapMultiArgs.clear();
349 for (int i = 1; i < argc; i++)
351 std::string str(argv[i]);
352 std::string strValue;
353 size_t is_index = str.find('=');
354 if (is_index != std::string::npos)
356 strValue = str.substr(is_index+1);
357 str = str.substr(0, is_index);
359 #ifdef WIN32
360 boost::to_lower(str);
361 if (boost::algorithm::starts_with(str, "/"))
362 str = "-" + str.substr(1);
363 #endif
365 if (str[0] != '-')
366 break;
368 // Interpret --foo as -foo.
369 // If both --foo and -foo are set, the last takes effect.
370 if (str.length() > 1 && str[1] == '-')
371 str = str.substr(1);
372 InterpretNegativeSetting(str, strValue);
374 mapArgs[str] = strValue;
375 mapMultiArgs[str].push_back(strValue);
379 std::string GetArg(const std::string& strArg, const std::string& strDefault)
381 if (mapArgs.count(strArg))
382 return mapArgs[strArg];
383 return strDefault;
386 int64_t GetArg(const std::string& strArg, int64_t nDefault)
388 if (mapArgs.count(strArg))
389 return atoi64(mapArgs[strArg]);
390 return nDefault;
393 bool GetBoolArg(const std::string& strArg, bool fDefault)
395 if (mapArgs.count(strArg))
396 return InterpretBool(mapArgs[strArg]);
397 return fDefault;
400 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
402 if (mapArgs.count(strArg))
403 return false;
404 mapArgs[strArg] = strValue;
405 return true;
408 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
410 if (fValue)
411 return SoftSetArg(strArg, std::string("1"));
412 else
413 return SoftSetArg(strArg, std::string("0"));
416 static const int screenWidth = 79;
417 static const int optIndent = 2;
418 static const int msgIndent = 7;
420 std::string HelpMessageGroup(const std::string &message) {
421 return std::string(message) + std::string("\n\n");
424 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
425 return std::string(optIndent,' ') + std::string(option) +
426 std::string("\n") + std::string(msgIndent,' ') +
427 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
428 std::string("\n\n");
431 static std::string FormatException(const std::exception* pex, const char* pszThread)
433 #ifdef WIN32
434 char pszModule[MAX_PATH] = "";
435 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
436 #else
437 const char* pszModule = "bitcoin";
438 #endif
439 if (pex)
440 return strprintf(
441 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
442 else
443 return strprintf(
444 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
447 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
449 std::string message = FormatException(pex, pszThread);
450 LogPrintf("\n\n************************\n%s\n", message);
451 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
454 boost::filesystem::path GetDefaultDataDir()
456 namespace fs = boost::filesystem;
457 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
458 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
459 // Mac: ~/Library/Application Support/Bitcoin
460 // Unix: ~/.bitcoin
461 #ifdef WIN32
462 // Windows
463 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
464 #else
465 fs::path pathRet;
466 char* pszHome = getenv("HOME");
467 if (pszHome == NULL || strlen(pszHome) == 0)
468 pathRet = fs::path("/");
469 else
470 pathRet = fs::path(pszHome);
471 #ifdef MAC_OSX
472 // Mac
473 return pathRet / "Library/Application Support/Bitcoin";
474 #else
475 // Unix
476 return pathRet / ".bitcoin";
477 #endif
478 #endif
481 static boost::filesystem::path pathCached;
482 static boost::filesystem::path pathCachedNetSpecific;
483 static CCriticalSection csPathCached;
485 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
487 namespace fs = boost::filesystem;
489 LOCK(csPathCached);
491 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
493 // This can be called during exceptions by LogPrintf(), so we cache the
494 // value so we don't have to do memory allocations after that.
495 if (!path.empty())
496 return path;
498 if (mapArgs.count("-datadir")) {
499 path = fs::system_complete(mapArgs["-datadir"]);
500 if (!fs::is_directory(path)) {
501 path = "";
502 return path;
504 } else {
505 path = GetDefaultDataDir();
507 if (fNetSpecific)
508 path /= BaseParams().DataDir();
510 fs::create_directories(path);
512 return path;
515 void ClearDatadirCache()
517 pathCached = boost::filesystem::path();
518 pathCachedNetSpecific = boost::filesystem::path();
521 boost::filesystem::path GetConfigFile(const std::string& confPath)
523 boost::filesystem::path pathConfigFile(confPath);
524 if (!pathConfigFile.is_complete())
525 pathConfigFile = GetDataDir(false) / pathConfigFile;
527 return pathConfigFile;
530 void ReadConfigFile(const std::string& confPath,
531 map<string, string>& mapSettingsRet,
532 map<string, vector<string> >& mapMultiSettingsRet)
534 boost::filesystem::ifstream streamConfig(GetConfigFile(confPath));
535 if (!streamConfig.good())
536 return; // No bitcoin.conf file is OK
538 set<string> setOptions;
539 setOptions.insert("*");
541 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
543 // Don't overwrite existing settings so command line settings override bitcoin.conf
544 string strKey = string("-") + it->string_key;
545 string strValue = it->value[0];
546 InterpretNegativeSetting(strKey, strValue);
547 if (mapSettingsRet.count(strKey) == 0)
548 mapSettingsRet[strKey] = strValue;
549 mapMultiSettingsRet[strKey].push_back(strValue);
551 // If datadir is changed in .conf file:
552 ClearDatadirCache();
555 #ifndef WIN32
556 boost::filesystem::path GetPidFile()
558 boost::filesystem::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME));
559 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
560 return pathPidFile;
563 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
565 FILE* file = fopen(path.string().c_str(), "w");
566 if (file)
568 fprintf(file, "%d\n", pid);
569 fclose(file);
572 #endif
574 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
576 #ifdef WIN32
577 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
578 MOVEFILE_REPLACE_EXISTING) != 0;
579 #else
580 int rc = std::rename(src.string().c_str(), dest.string().c_str());
581 return (rc == 0);
582 #endif /* WIN32 */
586 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
587 * Specifically handles case where path p exists, but it wasn't possible for the user to
588 * write to the parent directory.
590 bool TryCreateDirectory(const boost::filesystem::path& p)
594 return boost::filesystem::create_directory(p);
595 } catch (const boost::filesystem::filesystem_error&) {
596 if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
597 throw;
600 // create_directory didn't create the directory, it had to have existed already
601 return false;
604 void FileCommit(FILE *file)
606 fflush(file); // harmless if redundantly called
607 #ifdef WIN32
608 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
609 FlushFileBuffers(hFile);
610 #else
611 #if defined(__linux__) || defined(__NetBSD__)
612 fdatasync(fileno(file));
613 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
614 fcntl(fileno(file), F_FULLFSYNC, 0);
615 #else
616 fsync(fileno(file));
617 #endif
618 #endif
621 bool TruncateFile(FILE *file, unsigned int length) {
622 #if defined(WIN32)
623 return _chsize(_fileno(file), length) == 0;
624 #else
625 return ftruncate(fileno(file), length) == 0;
626 #endif
630 * this function tries to raise the file descriptor limit to the requested number.
631 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
633 int RaiseFileDescriptorLimit(int nMinFD) {
634 #if defined(WIN32)
635 return 2048;
636 #else
637 struct rlimit limitFD;
638 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
639 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
640 limitFD.rlim_cur = nMinFD;
641 if (limitFD.rlim_cur > limitFD.rlim_max)
642 limitFD.rlim_cur = limitFD.rlim_max;
643 setrlimit(RLIMIT_NOFILE, &limitFD);
644 getrlimit(RLIMIT_NOFILE, &limitFD);
646 return limitFD.rlim_cur;
648 return nMinFD; // getrlimit failed, assume it's fine
649 #endif
653 * this function tries to make a particular range of a file allocated (corresponding to disk space)
654 * it is advisory, and the range specified in the arguments will never contain live data
656 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
657 #if defined(WIN32)
658 // Windows-specific version
659 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
660 LARGE_INTEGER nFileSize;
661 int64_t nEndPos = (int64_t)offset + length;
662 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
663 nFileSize.u.HighPart = nEndPos >> 32;
664 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
665 SetEndOfFile(hFile);
666 #elif defined(MAC_OSX)
667 // OSX specific version
668 fstore_t fst;
669 fst.fst_flags = F_ALLOCATECONTIG;
670 fst.fst_posmode = F_PEOFPOSMODE;
671 fst.fst_offset = 0;
672 fst.fst_length = (off_t)offset + length;
673 fst.fst_bytesalloc = 0;
674 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
675 fst.fst_flags = F_ALLOCATEALL;
676 fcntl(fileno(file), F_PREALLOCATE, &fst);
678 ftruncate(fileno(file), fst.fst_length);
679 #elif defined(__linux__)
680 // Version using posix_fallocate
681 off_t nEndPos = (off_t)offset + length;
682 posix_fallocate(fileno(file), 0, nEndPos);
683 #else
684 // Fallback version
685 // TODO: just write one byte per block
686 static const char buf[65536] = {};
687 fseek(file, offset, SEEK_SET);
688 while (length > 0) {
689 unsigned int now = 65536;
690 if (length < now)
691 now = length;
692 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
693 length -= now;
695 #endif
698 void ShrinkDebugFile()
700 // Scroll debug.log if it's getting too big
701 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
702 FILE* file = fopen(pathLog.string().c_str(), "r");
703 if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
705 // Restart the file with some of the end
706 std::vector <char> vch(200000,0);
707 fseek(file, -((long)vch.size()), SEEK_END);
708 int nBytes = fread(begin_ptr(vch), 1, vch.size(), file);
709 fclose(file);
711 file = fopen(pathLog.string().c_str(), "w");
712 if (file)
714 fwrite(begin_ptr(vch), 1, nBytes, file);
715 fclose(file);
718 else if (file != NULL)
719 fclose(file);
722 #ifdef WIN32
723 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
725 namespace fs = boost::filesystem;
727 char pszPath[MAX_PATH] = "";
729 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
731 return fs::path(pszPath);
734 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
735 return fs::path("");
737 #endif
739 void runCommand(const std::string& strCommand)
741 int nErr = ::system(strCommand.c_str());
742 if (nErr)
743 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
746 void RenameThread(const char* name)
748 #if defined(PR_SET_NAME)
749 // Only the first 15 characters are used (16 - NUL terminator)
750 ::prctl(PR_SET_NAME, name, 0, 0, 0);
751 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
752 pthread_set_name_np(pthread_self(), name);
754 #elif defined(MAC_OSX)
755 pthread_setname_np(name);
756 #else
757 // Prevent warnings for unused parameters...
758 (void)name;
759 #endif
762 void SetupEnvironment()
764 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
765 // may be invalid, in which case the "C" locale is used as fallback.
766 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
767 try {
768 std::locale(""); // Raises a runtime error if current locale is invalid
769 } catch (const std::runtime_error&) {
770 setenv("LC_ALL", "C", 1);
772 #endif
773 // The path locale is lazy initialized and to avoid deinitialization errors
774 // in multithreading environments, it is set explicitly by the main thread.
775 // A dummy locale is used to extract the internal default locale, used by
776 // boost::filesystem::path, which is then used to explicitly imbue the path.
777 std::locale loc = boost::filesystem::path::imbue(std::locale::classic());
778 boost::filesystem::path::imbue(loc);
781 bool SetupNetworking()
783 #ifdef WIN32
784 // Initialize Windows Sockets
785 WSADATA wsadata;
786 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
787 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
788 return false;
789 #endif
790 return true;
793 int GetNumCores()
795 #if BOOST_VERSION >= 105600
796 return boost::thread::physical_concurrency();
797 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
798 return boost::thread::hardware_concurrency();
799 #endif
802 std::string CopyrightHolders(const std::string& strPrefix)
804 std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
806 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
807 if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) {
808 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
810 return strCopyrightHolders;