[depends] ZeroMQ 4.1.5
[bitcoinplatinum.git] / src / util.cpp
blob9a9209c62140b6ae73a8a4d6d780936bd45ed557
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 fDaemon = false;
111 bool fServer = false;
112 string strMiscWarning;
113 bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
114 bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
115 bool fLogIPs = DEFAULT_LOGIPS;
116 std::atomic<bool> fReopenDebugLog(false);
117 CTranslationInterface translationInterface;
119 /** Init OpenSSL library multithreading support */
120 static CCriticalSection** ppmutexOpenSSL;
121 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
123 if (mode & CRYPTO_LOCK) {
124 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
125 } else {
126 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
130 // Init
131 class CInit
133 public:
134 CInit()
136 // Init OpenSSL library multithreading support
137 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
138 for (int i = 0; i < CRYPTO_num_locks(); i++)
139 ppmutexOpenSSL[i] = new CCriticalSection();
140 CRYPTO_set_locking_callback(locking_callback);
142 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
143 // We don't use them so we don't require the config. However some of our libs may call functions
144 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
145 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
146 // that the config appears to have been loaded and there are no modules/engines available.
147 OPENSSL_no_config();
149 #ifdef WIN32
150 // Seed OpenSSL PRNG with current contents of the screen
151 RAND_screen();
152 #endif
154 // Seed OpenSSL PRNG with performance counter
155 RandAddSeed();
157 ~CInit()
159 // Securely erase the memory used by the PRNG
160 RAND_cleanup();
161 // Shutdown OpenSSL library multithreading support
162 CRYPTO_set_locking_callback(NULL);
163 for (int i = 0; i < CRYPTO_num_locks(); i++)
164 delete ppmutexOpenSSL[i];
165 OPENSSL_free(ppmutexOpenSSL);
168 instance_of_cinit;
171 * LogPrintf() has been broken a couple of times now
172 * by well-meaning people adding mutexes in the most straightforward way.
173 * It breaks because it may be called by global destructors during shutdown.
174 * Since the order of destruction of static/global objects is undefined,
175 * defining a mutex as a global object doesn't work (the mutex gets
176 * destroyed, and then some later destructor calls OutputDebugStringF,
177 * maybe indirectly, and you get a core dump at shutdown trying to lock
178 * the mutex).
181 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
184 * We use boost::call_once() to make sure mutexDebugLog and
185 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
187 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
188 * are leaked on exit. This is ugly, but will be cleaned up by
189 * the OS/libc. When the shutdown sequence is fully audited and
190 * tested, explicit destruction of these objects can be implemented.
192 static FILE* fileout = NULL;
193 static boost::mutex* mutexDebugLog = NULL;
194 static list<string> *vMsgsBeforeOpenLog;
196 static int FileWriteStr(const std::string &str, FILE *fp)
198 return fwrite(str.data(), 1, str.size(), fp);
201 static void DebugPrintInit()
203 assert(mutexDebugLog == NULL);
204 mutexDebugLog = new boost::mutex();
205 vMsgsBeforeOpenLog = new list<string>;
208 void OpenDebugLog()
210 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
211 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
213 assert(fileout == NULL);
214 assert(vMsgsBeforeOpenLog);
215 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
216 fileout = fopen(pathDebug.string().c_str(), "a");
217 if (fileout) setbuf(fileout, NULL); // unbuffered
219 // dump buffered messages from before we opened the log
220 while (!vMsgsBeforeOpenLog->empty()) {
221 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
222 vMsgsBeforeOpenLog->pop_front();
225 delete vMsgsBeforeOpenLog;
226 vMsgsBeforeOpenLog = NULL;
229 bool LogAcceptCategory(const char* category)
231 if (category != NULL)
233 if (!fDebug)
234 return false;
236 // Give each thread quick access to -debug settings.
237 // This helps prevent issues debugging global destructors,
238 // where mapMultiArgs might be deleted before another
239 // global destructor calls LogPrint()
240 static boost::thread_specific_ptr<set<string> > ptrCategory;
241 if (ptrCategory.get() == NULL)
243 const vector<string>& categories = mapMultiArgs["-debug"];
244 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
245 // thread_specific_ptr automatically deletes the set when the thread ends.
247 const set<string>& setCategories = *ptrCategory.get();
249 // if not debugging everything and not debugging specific category, LogPrint does nothing.
250 if (setCategories.count(string("")) == 0 &&
251 setCategories.count(string("1")) == 0 &&
252 setCategories.count(string(category)) == 0)
253 return false;
255 return true;
259 * fStartedNewLine is a state variable held by the calling context that will
260 * suppress printing of the timestamp when multiple calls are made that don't
261 * end in a newline. Initialize it to true, and hold it, in the calling context.
263 static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine)
265 string strStamped;
267 if (!fLogTimestamps)
268 return str;
270 if (*fStartedNewLine) {
271 int64_t nTimeMicros = GetLogTimeMicros();
272 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
273 if (fLogTimeMicros)
274 strStamped += strprintf(".%06d", nTimeMicros%1000000);
275 strStamped += ' ' + str;
276 } else
277 strStamped = str;
279 if (!str.empty() && str[str.size()-1] == '\n')
280 *fStartedNewLine = true;
281 else
282 *fStartedNewLine = false;
284 return strStamped;
287 int LogPrintStr(const std::string &str)
289 int ret = 0; // Returns total number of characters written
290 static bool fStartedNewLine = true;
292 string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
294 if (fPrintToConsole)
296 // print to console
297 ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
298 fflush(stdout);
300 else if (fPrintToDebugLog)
302 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
303 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
305 // buffer if we haven't opened the log yet
306 if (fileout == NULL) {
307 assert(vMsgsBeforeOpenLog);
308 ret = strTimestamped.length();
309 vMsgsBeforeOpenLog->push_back(strTimestamped);
311 else
313 // reopen the log file, if requested
314 if (fReopenDebugLog) {
315 fReopenDebugLog = false;
316 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
317 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
318 setbuf(fileout, NULL); // unbuffered
321 ret = FileWriteStr(strTimestamped, fileout);
324 return ret;
327 /** Interpret string as boolean, for argument parsing */
328 static bool InterpretBool(const std::string& strValue)
330 if (strValue.empty())
331 return true;
332 return (atoi(strValue) != 0);
335 /** Turn -noX into -X=0 */
336 static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
338 if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
340 strKey = "-" + strKey.substr(3);
341 strValue = InterpretBool(strValue) ? "0" : "1";
345 void ParseParameters(int argc, const char* const argv[])
347 mapArgs.clear();
348 mapMultiArgs.clear();
350 for (int i = 1; i < argc; i++)
352 std::string str(argv[i]);
353 std::string strValue;
354 size_t is_index = str.find('=');
355 if (is_index != std::string::npos)
357 strValue = str.substr(is_index+1);
358 str = str.substr(0, is_index);
360 #ifdef WIN32
361 boost::to_lower(str);
362 if (boost::algorithm::starts_with(str, "/"))
363 str = "-" + str.substr(1);
364 #endif
366 if (str[0] != '-')
367 break;
369 // Interpret --foo as -foo.
370 // If both --foo and -foo are set, the last takes effect.
371 if (str.length() > 1 && str[1] == '-')
372 str = str.substr(1);
373 InterpretNegativeSetting(str, strValue);
375 mapArgs[str] = strValue;
376 mapMultiArgs[str].push_back(strValue);
380 std::string GetArg(const std::string& strArg, const std::string& strDefault)
382 if (mapArgs.count(strArg))
383 return mapArgs[strArg];
384 return strDefault;
387 int64_t GetArg(const std::string& strArg, int64_t nDefault)
389 if (mapArgs.count(strArg))
390 return atoi64(mapArgs[strArg]);
391 return nDefault;
394 bool GetBoolArg(const std::string& strArg, bool fDefault)
396 if (mapArgs.count(strArg))
397 return InterpretBool(mapArgs[strArg]);
398 return fDefault;
401 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
403 if (mapArgs.count(strArg))
404 return false;
405 mapArgs[strArg] = strValue;
406 return true;
409 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
411 if (fValue)
412 return SoftSetArg(strArg, std::string("1"));
413 else
414 return SoftSetArg(strArg, std::string("0"));
417 static const int screenWidth = 79;
418 static const int optIndent = 2;
419 static const int msgIndent = 7;
421 std::string HelpMessageGroup(const std::string &message) {
422 return std::string(message) + std::string("\n\n");
425 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
426 return std::string(optIndent,' ') + std::string(option) +
427 std::string("\n") + std::string(msgIndent,' ') +
428 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
429 std::string("\n\n");
432 static std::string FormatException(const std::exception* pex, const char* pszThread)
434 #ifdef WIN32
435 char pszModule[MAX_PATH] = "";
436 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
437 #else
438 const char* pszModule = "bitcoin";
439 #endif
440 if (pex)
441 return strprintf(
442 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
443 else
444 return strprintf(
445 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
448 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
450 std::string message = FormatException(pex, pszThread);
451 LogPrintf("\n\n************************\n%s\n", message);
452 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
455 boost::filesystem::path GetDefaultDataDir()
457 namespace fs = boost::filesystem;
458 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
459 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
460 // Mac: ~/Library/Application Support/Bitcoin
461 // Unix: ~/.bitcoin
462 #ifdef WIN32
463 // Windows
464 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
465 #else
466 fs::path pathRet;
467 char* pszHome = getenv("HOME");
468 if (pszHome == NULL || strlen(pszHome) == 0)
469 pathRet = fs::path("/");
470 else
471 pathRet = fs::path(pszHome);
472 #ifdef MAC_OSX
473 // Mac
474 return pathRet / "Library/Application Support/Bitcoin";
475 #else
476 // Unix
477 return pathRet / ".bitcoin";
478 #endif
479 #endif
482 static boost::filesystem::path pathCached;
483 static boost::filesystem::path pathCachedNetSpecific;
484 static CCriticalSection csPathCached;
486 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
488 namespace fs = boost::filesystem;
490 LOCK(csPathCached);
492 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
494 // This can be called during exceptions by LogPrintf(), so we cache the
495 // value so we don't have to do memory allocations after that.
496 if (!path.empty())
497 return path;
499 if (mapArgs.count("-datadir")) {
500 path = fs::system_complete(mapArgs["-datadir"]);
501 if (!fs::is_directory(path)) {
502 path = "";
503 return path;
505 } else {
506 path = GetDefaultDataDir();
508 if (fNetSpecific)
509 path /= BaseParams().DataDir();
511 fs::create_directories(path);
513 return path;
516 void ClearDatadirCache()
518 pathCached = boost::filesystem::path();
519 pathCachedNetSpecific = boost::filesystem::path();
522 boost::filesystem::path GetConfigFile()
524 boost::filesystem::path pathConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
525 if (!pathConfigFile.is_complete())
526 pathConfigFile = GetDataDir(false) / pathConfigFile;
528 return pathConfigFile;
531 void ReadConfigFile(map<string, string>& mapSettingsRet,
532 map<string, vector<string> >& mapMultiSettingsRet)
534 boost::filesystem::ifstream streamConfig(GetConfigFile());
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 *fileout)
606 fflush(fileout); // harmless if redundantly called
607 #ifdef WIN32
608 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
609 FlushFileBuffers(hFile);
610 #else
611 #if defined(__linux__) || defined(__NetBSD__)
612 fdatasync(fileno(fileout));
613 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
614 fcntl(fileno(fileout), F_FULLFSYNC, 0);
615 #else
616 fsync(fileno(fileout));
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 + _(COPYRIGHT_HOLDERS);
805 if (strCopyrightHolders.find("%s") != strCopyrightHolders.npos) {
806 strCopyrightHolders = strprintf(strCopyrightHolders, _(COPYRIGHT_HOLDERS_SUBSTITUTION));
808 if (strCopyrightHolders.find("Bitcoin Core developers") == strCopyrightHolders.npos) {
809 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
811 return strCopyrightHolders;