1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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>
12 #include <chainparamsbase.h>
15 #include <serialize.h>
16 #include <utilstrencodings.h>
21 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
23 #include <pthread_np.h>
27 // for posix_fallocate
30 #ifdef _POSIX_C_SOURCE
31 #undef _POSIX_C_SOURCE
34 #define _POSIX_C_SOURCE 200112L
40 #include <sys/resource.h>
46 #pragma warning(disable:4786)
47 #pragma warning(disable:4804)
48 #pragma warning(disable:4805)
49 #pragma warning(disable:4717)
55 #define _WIN32_WINNT 0x0501
60 #define _WIN32_IE 0x0501
62 #define WIN32_LEAN_AND_MEAN 1
67 #include <io.h> /* for _commit */
71 #ifdef HAVE_SYS_PRCTL_H
72 #include <sys/prctl.h>
75 #ifdef HAVE_MALLOPT_ARENA_MAX
79 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
80 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
81 #include <boost/program_options/detail/config_file.hpp>
82 #include <boost/thread.hpp>
83 #include <openssl/crypto.h>
84 #include <openssl/rand.h>
85 #include <openssl/conf.h>
87 // Application startup time (used for uptime calculation)
88 const int64_t nStartupTime
= GetTime();
90 const char * const BITCOIN_CONF_FILENAME
= "bitcoin.conf";
91 const char * const BITCOIN_PID_FILENAME
= "bitcoind.pid";
92 const char * const DEFAULT_DEBUGLOGFILE
= "debug.log";
95 bool fPrintToConsole
= false;
96 bool fPrintToDebugLog
= true;
98 bool fLogTimestamps
= DEFAULT_LOGTIMESTAMPS
;
99 bool fLogTimeMicros
= DEFAULT_LOGTIMEMICROS
;
100 bool fLogIPs
= DEFAULT_LOGIPS
;
101 std::atomic
<bool> fReopenDebugLog(false);
102 CTranslationInterface translationInterface
;
104 /** Log categories bitfield. */
105 std::atomic
<uint32_t> logCategories(0);
107 /** Init OpenSSL library multithreading support */
108 static std::unique_ptr
<CCriticalSection
[]> ppmutexOpenSSL
;
109 void locking_callback(int mode
, int i
, const char* file
, int line
) NO_THREAD_SAFETY_ANALYSIS
111 if (mode
& CRYPTO_LOCK
) {
112 ENTER_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
114 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
118 // Singleton for wrapping OpenSSL setup/teardown.
124 // Init OpenSSL library multithreading support
125 ppmutexOpenSSL
.reset(new CCriticalSection
[CRYPTO_num_locks()]);
126 CRYPTO_set_locking_callback(locking_callback
);
128 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
129 // We don't use them so we don't require the config. However some of our libs may call functions
130 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
131 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
132 // that the config appears to have been loaded and there are no modules/engines available.
136 // Seed OpenSSL PRNG with current contents of the screen
140 // Seed OpenSSL PRNG with performance counter
145 // Securely erase the memory used by the PRNG
147 // Shutdown OpenSSL library multithreading support
148 CRYPTO_set_locking_callback(nullptr);
149 // Clear the set of locks now to maintain symmetry with the constructor.
150 ppmutexOpenSSL
.reset();
156 * LogPrintf() has been broken a couple of times now
157 * by well-meaning people adding mutexes in the most straightforward way.
158 * It breaks because it may be called by global destructors during shutdown.
159 * Since the order of destruction of static/global objects is undefined,
160 * defining a mutex as a global object doesn't work (the mutex gets
161 * destroyed, and then some later destructor calls OutputDebugStringF,
162 * maybe indirectly, and you get a core dump at shutdown trying to lock
166 static boost::once_flag debugPrintInitFlag
= BOOST_ONCE_INIT
;
169 * We use boost::call_once() to make sure mutexDebugLog and
170 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
172 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
173 * are leaked on exit. This is ugly, but will be cleaned up by
174 * the OS/libc. When the shutdown sequence is fully audited and
175 * tested, explicit destruction of these objects can be implemented.
177 static FILE* fileout
= nullptr;
178 static boost::mutex
* mutexDebugLog
= nullptr;
179 static std::list
<std::string
>* vMsgsBeforeOpenLog
;
181 static int FileWriteStr(const std::string
&str
, FILE *fp
)
183 return fwrite(str
.data(), 1, str
.size(), fp
);
186 static void DebugPrintInit()
188 assert(mutexDebugLog
== nullptr);
189 mutexDebugLog
= new boost::mutex();
190 vMsgsBeforeOpenLog
= new std::list
<std::string
>;
193 fs::path
GetDebugLogPath()
195 fs::path
logfile(gArgs
.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE
));
196 if (logfile
.is_absolute()) {
199 return GetDataDir() / logfile
;
205 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
206 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
208 assert(fileout
== nullptr);
209 assert(vMsgsBeforeOpenLog
);
210 fs::path pathDebug
= GetDebugLogPath();
212 fileout
= fsbridge::fopen(pathDebug
, "a");
217 setbuf(fileout
, nullptr); // 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
= nullptr;
229 struct CLogCategoryDesc
232 std::string category
;
235 const CLogCategoryDesc LogCategories
[] =
238 {BCLog::NONE
, "none"},
241 {BCLog::MEMPOOL
, "mempool"},
242 {BCLog::HTTP
, "http"},
243 {BCLog::BENCH
, "bench"},
247 {BCLog::ESTIMATEFEE
, "estimatefee"},
248 {BCLog::ADDRMAN
, "addrman"},
249 {BCLog::SELECTCOINS
, "selectcoins"},
250 {BCLog::REINDEX
, "reindex"},
251 {BCLog::CMPCTBLOCK
, "cmpctblock"},
252 {BCLog::RAND
, "rand"},
253 {BCLog::PRUNE
, "prune"},
254 {BCLog::PROXY
, "proxy"},
255 {BCLog::MEMPOOLREJ
, "mempoolrej"},
256 {BCLog::LIBEVENT
, "libevent"},
257 {BCLog::COINDB
, "coindb"},
259 {BCLog::LEVELDB
, "leveldb"},
264 bool GetLogCategory(uint32_t *f
, const std::string
*str
)
271 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
272 if (LogCategories
[i
].category
== *str
) {
273 *f
= LogCategories
[i
].flag
;
281 std::string
ListLogCategories()
285 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
286 // Omit the special cases.
287 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
288 if (outcount
!= 0) ret
+= ", ";
289 ret
+= LogCategories
[i
].category
;
296 std::vector
<CLogCategoryActive
> ListActiveLogCategories()
298 std::vector
<CLogCategoryActive
> ret
;
299 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
300 // Omit the special cases.
301 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
302 CLogCategoryActive catActive
;
303 catActive
.category
= LogCategories
[i
].category
;
304 catActive
.active
= LogAcceptCategory(LogCategories
[i
].flag
);
305 ret
.push_back(catActive
);
312 * fStartedNewLine is a state variable held by the calling context that will
313 * suppress printing of the timestamp when multiple calls are made that don't
314 * end in a newline. Initialize it to true, and hold it, in the calling context.
316 static std::string
LogTimestampStr(const std::string
&str
, std::atomic_bool
*fStartedNewLine
)
318 std::string strStamped
;
323 if (*fStartedNewLine
) {
324 int64_t nTimeMicros
= GetTimeMicros();
325 strStamped
= DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros
/1000000);
327 strStamped
+= strprintf(".%06d", nTimeMicros
%1000000);
328 int64_t mocktime
= GetMockTime();
330 strStamped
+= " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime
) + ")";
332 strStamped
+= ' ' + str
;
336 if (!str
.empty() && str
[str
.size()-1] == '\n')
337 *fStartedNewLine
= true;
339 *fStartedNewLine
= false;
344 int LogPrintStr(const std::string
&str
)
346 int ret
= 0; // Returns total number of characters written
347 static std::atomic_bool
fStartedNewLine(true);
349 std::string strTimestamped
= LogTimestampStr(str
, &fStartedNewLine
);
354 ret
= fwrite(strTimestamped
.data(), 1, strTimestamped
.size(), stdout
);
357 else if (fPrintToDebugLog
)
359 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
360 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
362 // buffer if we haven't opened the log yet
363 if (fileout
== nullptr) {
364 assert(vMsgsBeforeOpenLog
);
365 ret
= strTimestamped
.length();
366 vMsgsBeforeOpenLog
->push_back(strTimestamped
);
370 // reopen the log file, if requested
371 if (fReopenDebugLog
) {
372 fReopenDebugLog
= false;
373 fs::path pathDebug
= GetDebugLogPath();
374 if (fsbridge::freopen(pathDebug
,"a",fileout
) != nullptr)
375 setbuf(fileout
, nullptr); // unbuffered
378 ret
= FileWriteStr(strTimestamped
, fileout
);
384 /** Interpret string as boolean, for argument parsing */
385 static bool InterpretBool(const std::string
& strValue
)
387 if (strValue
.empty())
389 return (atoi(strValue
) != 0);
392 /** Turn -noX into -X=0 */
393 static void InterpretNegativeSetting(std::string
& strKey
, std::string
& strValue
)
395 if (strKey
.length()>3 && strKey
[0]=='-' && strKey
[1]=='n' && strKey
[2]=='o')
397 strKey
= "-" + strKey
.substr(3);
398 strValue
= InterpretBool(strValue
) ? "0" : "1";
402 void ArgsManager::ParseParameters(int argc
, const char* const argv
[])
406 mapMultiArgs
.clear();
408 for (int i
= 1; i
< argc
; i
++)
410 std::string
str(argv
[i
]);
411 std::string strValue
;
412 size_t is_index
= str
.find('=');
413 if (is_index
!= std::string::npos
)
415 strValue
= str
.substr(is_index
+1);
416 str
= str
.substr(0, is_index
);
419 boost::to_lower(str
);
420 if (boost::algorithm::starts_with(str
, "/"))
421 str
= "-" + str
.substr(1);
427 // Interpret --foo as -foo.
428 // If both --foo and -foo are set, the last takes effect.
429 if (str
.length() > 1 && str
[1] == '-')
431 InterpretNegativeSetting(str
, strValue
);
433 mapArgs
[str
] = strValue
;
434 mapMultiArgs
[str
].push_back(strValue
);
438 std::vector
<std::string
> ArgsManager::GetArgs(const std::string
& strArg
) const
441 auto it
= mapMultiArgs
.find(strArg
);
442 if (it
!= mapMultiArgs
.end()) return it
->second
;
446 bool ArgsManager::IsArgSet(const std::string
& strArg
) const
449 return mapArgs
.count(strArg
);
452 std::string
ArgsManager::GetArg(const std::string
& strArg
, const std::string
& strDefault
) const
455 auto it
= mapArgs
.find(strArg
);
456 if (it
!= mapArgs
.end()) return it
->second
;
460 int64_t ArgsManager::GetArg(const std::string
& strArg
, int64_t nDefault
) const
463 auto it
= mapArgs
.find(strArg
);
464 if (it
!= mapArgs
.end()) return atoi64(it
->second
);
468 bool ArgsManager::GetBoolArg(const std::string
& strArg
, bool fDefault
) const
471 auto it
= mapArgs
.find(strArg
);
472 if (it
!= mapArgs
.end()) return InterpretBool(it
->second
);
476 bool ArgsManager::SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
479 if (IsArgSet(strArg
)) return false;
480 ForceSetArg(strArg
, strValue
);
484 bool ArgsManager::SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
487 return SoftSetArg(strArg
, std::string("1"));
489 return SoftSetArg(strArg
, std::string("0"));
492 void ArgsManager::ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
495 mapArgs
[strArg
] = strValue
;
496 mapMultiArgs
[strArg
] = {strValue
};
501 static const int screenWidth
= 79;
502 static const int optIndent
= 2;
503 static const int msgIndent
= 7;
505 std::string
HelpMessageGroup(const std::string
&message
) {
506 return std::string(message
) + std::string("\n\n");
509 std::string
HelpMessageOpt(const std::string
&option
, const std::string
&message
) {
510 return std::string(optIndent
,' ') + std::string(option
) +
511 std::string("\n") + std::string(msgIndent
,' ') +
512 FormatParagraph(message
, screenWidth
- msgIndent
, msgIndent
) +
516 static std::string
FormatException(const std::exception
* pex
, const char* pszThread
)
519 char pszModule
[MAX_PATH
] = "";
520 GetModuleFileNameA(nullptr, pszModule
, sizeof(pszModule
));
522 const char* pszModule
= "bitcoin";
526 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex
).name(), pex
->what(), pszModule
, pszThread
);
529 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule
, pszThread
);
532 void PrintExceptionContinue(const std::exception
* pex
, const char* pszThread
)
534 std::string message
= FormatException(pex
, pszThread
);
535 LogPrintf("\n\n************************\n%s\n", message
);
536 fprintf(stderr
, "\n\n************************\n%s\n", message
.c_str());
539 fs::path
GetDefaultDataDir()
541 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
542 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
543 // Mac: ~/Library/Application Support/Bitcoin
547 return GetSpecialFolderPath(CSIDL_APPDATA
) / "Bitcoin";
550 char* pszHome
= getenv("HOME");
551 if (pszHome
== nullptr || strlen(pszHome
) == 0)
552 pathRet
= fs::path("/");
554 pathRet
= fs::path(pszHome
);
557 return pathRet
/ "Library/Application Support/Bitcoin";
560 return pathRet
/ ".bitcoin";
565 static fs::path pathCached
;
566 static fs::path pathCachedNetSpecific
;
567 static CCriticalSection csPathCached
;
569 const fs::path
&GetDataDir(bool fNetSpecific
)
574 fs::path
&path
= fNetSpecific
? pathCachedNetSpecific
: pathCached
;
576 // This can be called during exceptions by LogPrintf(), so we cache the
577 // value so we don't have to do memory allocations after that.
581 if (gArgs
.IsArgSet("-datadir")) {
582 path
= fs::system_complete(gArgs
.GetArg("-datadir", ""));
583 if (!fs::is_directory(path
)) {
588 path
= GetDefaultDataDir();
591 path
/= BaseParams().DataDir();
593 if (fs::create_directories(path
)) {
594 // This is the first run, create wallets subdirectory too
595 fs::create_directories(path
/ "wallets");
601 void ClearDatadirCache()
605 pathCached
= fs::path();
606 pathCachedNetSpecific
= fs::path();
609 fs::path
GetConfigFile(const std::string
& confPath
)
611 fs::path
pathConfigFile(confPath
);
612 if (!pathConfigFile
.is_complete())
613 pathConfigFile
= GetDataDir(false) / pathConfigFile
;
615 return pathConfigFile
;
618 void ArgsManager::ReadConfigFile(const std::string
& confPath
)
620 fs::ifstream
streamConfig(GetConfigFile(confPath
));
621 if (!streamConfig
.good())
622 return; // No bitcoin.conf file is OK
626 std::set
<std::string
> setOptions
;
627 setOptions
.insert("*");
629 for (boost::program_options::detail::config_file_iterator
it(streamConfig
, setOptions
), end
; it
!= end
; ++it
)
631 // Don't overwrite existing settings so command line settings override bitcoin.conf
632 std::string strKey
= std::string("-") + it
->string_key
;
633 std::string strValue
= it
->value
[0];
634 InterpretNegativeSetting(strKey
, strValue
);
635 if (mapArgs
.count(strKey
) == 0)
636 mapArgs
[strKey
] = strValue
;
637 mapMultiArgs
[strKey
].push_back(strValue
);
640 // If datadir is changed in .conf file:
645 fs::path
GetPidFile()
647 fs::path
pathPidFile(gArgs
.GetArg("-pid", BITCOIN_PID_FILENAME
));
648 if (!pathPidFile
.is_complete()) pathPidFile
= GetDataDir() / pathPidFile
;
652 void CreatePidFile(const fs::path
&path
, pid_t pid
)
654 FILE* file
= fsbridge::fopen(path
, "w");
657 fprintf(file
, "%d\n", pid
);
663 bool RenameOver(fs::path src
, fs::path dest
)
666 return MoveFileExA(src
.string().c_str(), dest
.string().c_str(),
667 MOVEFILE_REPLACE_EXISTING
) != 0;
669 int rc
= std::rename(src
.string().c_str(), dest
.string().c_str());
675 * Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
676 * Specifically handles case where path p exists, but it wasn't possible for the user to
677 * write to the parent directory.
679 bool TryCreateDirectories(const fs::path
& p
)
683 return fs::create_directories(p
);
684 } catch (const fs::filesystem_error
&) {
685 if (!fs::exists(p
) || !fs::is_directory(p
))
689 // create_directories didn't create the directory, it had to have existed already
693 void FileCommit(FILE *file
)
695 fflush(file
); // harmless if redundantly called
697 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
698 FlushFileBuffers(hFile
);
700 #if defined(__linux__) || defined(__NetBSD__)
701 fdatasync(fileno(file
));
702 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
703 fcntl(fileno(file
), F_FULLFSYNC
, 0);
710 bool TruncateFile(FILE *file
, unsigned int length
) {
712 return _chsize(_fileno(file
), length
) == 0;
714 return ftruncate(fileno(file
), length
) == 0;
719 * this function tries to raise the file descriptor limit to the requested number.
720 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
722 int RaiseFileDescriptorLimit(int nMinFD
) {
726 struct rlimit limitFD
;
727 if (getrlimit(RLIMIT_NOFILE
, &limitFD
) != -1) {
728 if (limitFD
.rlim_cur
< (rlim_t
)nMinFD
) {
729 limitFD
.rlim_cur
= nMinFD
;
730 if (limitFD
.rlim_cur
> limitFD
.rlim_max
)
731 limitFD
.rlim_cur
= limitFD
.rlim_max
;
732 setrlimit(RLIMIT_NOFILE
, &limitFD
);
733 getrlimit(RLIMIT_NOFILE
, &limitFD
);
735 return limitFD
.rlim_cur
;
737 return nMinFD
; // getrlimit failed, assume it's fine
742 * this function tries to make a particular range of a file allocated (corresponding to disk space)
743 * it is advisory, and the range specified in the arguments will never contain live data
745 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
) {
747 // Windows-specific version
748 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
749 LARGE_INTEGER nFileSize
;
750 int64_t nEndPos
= (int64_t)offset
+ length
;
751 nFileSize
.u
.LowPart
= nEndPos
& 0xFFFFFFFF;
752 nFileSize
.u
.HighPart
= nEndPos
>> 32;
753 SetFilePointerEx(hFile
, nFileSize
, 0, FILE_BEGIN
);
755 #elif defined(MAC_OSX)
756 // OSX specific version
758 fst
.fst_flags
= F_ALLOCATECONTIG
;
759 fst
.fst_posmode
= F_PEOFPOSMODE
;
761 fst
.fst_length
= (off_t
)offset
+ length
;
762 fst
.fst_bytesalloc
= 0;
763 if (fcntl(fileno(file
), F_PREALLOCATE
, &fst
) == -1) {
764 fst
.fst_flags
= F_ALLOCATEALL
;
765 fcntl(fileno(file
), F_PREALLOCATE
, &fst
);
767 ftruncate(fileno(file
), fst
.fst_length
);
768 #elif defined(__linux__)
769 // Version using posix_fallocate
770 off_t nEndPos
= (off_t
)offset
+ length
;
771 posix_fallocate(fileno(file
), 0, nEndPos
);
774 // TODO: just write one byte per block
775 static const char buf
[65536] = {};
776 fseek(file
, offset
, SEEK_SET
);
778 unsigned int now
= 65536;
781 fwrite(buf
, 1, now
, file
); // allowed to fail; this function is advisory anyway
787 void ShrinkDebugFile()
789 // Amount of debug.log to save at end when shrinking (must fit in memory)
790 constexpr size_t RECENT_DEBUG_HISTORY_SIZE
= 10 * 1000000;
791 // Scroll debug.log if it's getting too big
792 fs::path pathLog
= GetDebugLogPath();
793 FILE* file
= fsbridge::fopen(pathLog
, "r");
794 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
795 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
796 if (file
&& fs::file_size(pathLog
) > 11 * (RECENT_DEBUG_HISTORY_SIZE
/ 10))
798 // Restart the file with some of the end
799 std::vector
<char> vch(RECENT_DEBUG_HISTORY_SIZE
, 0);
800 fseek(file
, -((long)vch
.size()), SEEK_END
);
801 int nBytes
= fread(vch
.data(), 1, vch
.size(), file
);
804 file
= fsbridge::fopen(pathLog
, "w");
807 fwrite(vch
.data(), 1, nBytes
, file
);
811 else if (file
!= nullptr)
816 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
)
818 char pszPath
[MAX_PATH
] = "";
820 if(SHGetSpecialFolderPathA(nullptr, pszPath
, nFolder
, fCreate
))
822 return fs::path(pszPath
);
825 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
830 void runCommand(const std::string
& strCommand
)
832 if (strCommand
.empty()) return;
833 int nErr
= ::system(strCommand
.c_str());
835 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand
, nErr
);
838 void RenameThread(const char* name
)
840 #if defined(PR_SET_NAME)
841 // Only the first 15 characters are used (16 - NUL terminator)
842 ::prctl(PR_SET_NAME
, name
, 0, 0, 0);
843 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
844 pthread_set_name_np(pthread_self(), name
);
846 #elif defined(MAC_OSX)
847 pthread_setname_np(name
);
849 // Prevent warnings for unused parameters...
854 void SetupEnvironment()
856 #ifdef HAVE_MALLOPT_ARENA_MAX
857 // glibc-specific: On 32-bit systems set the number of arenas to 1.
858 // By default, since glibc 2.10, the C library will create up to two heap
859 // arenas per core. This is known to cause excessive virtual address space
860 // usage in our usage. Work around it by setting the maximum number of
862 if (sizeof(void*) == 4) {
863 mallopt(M_ARENA_MAX
, 1);
866 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
867 // may be invalid, in which case the "C" locale is used as fallback.
868 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
870 std::locale(""); // Raises a runtime error if current locale is invalid
871 } catch (const std::runtime_error
&) {
872 setenv("LC_ALL", "C", 1);
875 // The path locale is lazy initialized and to avoid deinitialization errors
876 // in multithreading environments, it is set explicitly by the main thread.
877 // A dummy locale is used to extract the internal default locale, used by
878 // fs::path, which is then used to explicitly imbue the path.
879 std::locale loc
= fs::path::imbue(std::locale::classic());
880 fs::path::imbue(loc
);
883 bool SetupNetworking()
886 // Initialize Windows Sockets
888 int ret
= WSAStartup(MAKEWORD(2,2), &wsadata
);
889 if (ret
!= NO_ERROR
|| LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 2)
897 #if BOOST_VERSION >= 105600
898 return boost::thread::physical_concurrency();
899 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
900 return boost::thread::hardware_concurrency();
904 std::string
CopyrightHolders(const std::string
& strPrefix
)
906 std::string strCopyrightHolders
= strPrefix
+ strprintf(_(COPYRIGHT_HOLDERS
), _(COPYRIGHT_HOLDERS_SUBSTITUTION
));
908 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
909 if (strprintf(COPYRIGHT_HOLDERS
, COPYRIGHT_HOLDERS_SUBSTITUTION
).find("Bitcoin Core") == std::string::npos
) {
910 strCopyrightHolders
+= "\n" + strPrefix
+ "The Bitcoin Core developers";
912 return strCopyrightHolders
;
915 // Obtain the application startup time (used for uptime calculation)
916 int64_t GetStartupTime()