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";
94 bool fPrintToConsole
= false;
95 bool fPrintToDebugLog
= true;
97 bool fLogTimestamps
= DEFAULT_LOGTIMESTAMPS
;
98 bool fLogTimeMicros
= DEFAULT_LOGTIMEMICROS
;
99 bool fLogIPs
= DEFAULT_LOGIPS
;
100 std::atomic
<bool> fReopenDebugLog(false);
101 CTranslationInterface translationInterface
;
103 /** Log categories bitfield. */
104 std::atomic
<uint32_t> logCategories(0);
106 /** Init OpenSSL library multithreading support */
107 static std::unique_ptr
<CCriticalSection
[]> ppmutexOpenSSL
;
108 void locking_callback(int mode
, int i
, const char* file
, int line
) NO_THREAD_SAFETY_ANALYSIS
110 if (mode
& CRYPTO_LOCK
) {
111 ENTER_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
113 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
117 // Singleton for wrapping OpenSSL setup/teardown.
123 // Init OpenSSL library multithreading support
124 ppmutexOpenSSL
.reset(new CCriticalSection
[CRYPTO_num_locks()]);
125 CRYPTO_set_locking_callback(locking_callback
);
127 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
128 // We don't use them so we don't require the config. However some of our libs may call functions
129 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
130 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
131 // that the config appears to have been loaded and there are no modules/engines available.
135 // Seed OpenSSL PRNG with current contents of the screen
139 // Seed OpenSSL PRNG with performance counter
144 // Securely erase the memory used by the PRNG
146 // Shutdown OpenSSL library multithreading support
147 CRYPTO_set_locking_callback(nullptr);
148 // Clear the set of locks now to maintain symmetry with the constructor.
149 ppmutexOpenSSL
.reset();
155 * LogPrintf() has been broken a couple of times now
156 * by well-meaning people adding mutexes in the most straightforward way.
157 * It breaks because it may be called by global destructors during shutdown.
158 * Since the order of destruction of static/global objects is undefined,
159 * defining a mutex as a global object doesn't work (the mutex gets
160 * destroyed, and then some later destructor calls OutputDebugStringF,
161 * maybe indirectly, and you get a core dump at shutdown trying to lock
165 static boost::once_flag debugPrintInitFlag
= BOOST_ONCE_INIT
;
168 * We use boost::call_once() to make sure mutexDebugLog and
169 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
171 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
172 * are leaked on exit. This is ugly, but will be cleaned up by
173 * the OS/libc. When the shutdown sequence is fully audited and
174 * tested, explicit destruction of these objects can be implemented.
176 static FILE* fileout
= nullptr;
177 static boost::mutex
* mutexDebugLog
= nullptr;
178 static std::list
<std::string
>* vMsgsBeforeOpenLog
;
180 static int FileWriteStr(const std::string
&str
, FILE *fp
)
182 return fwrite(str
.data(), 1, str
.size(), fp
);
185 static void DebugPrintInit()
187 assert(mutexDebugLog
== nullptr);
188 mutexDebugLog
= new boost::mutex();
189 vMsgsBeforeOpenLog
= new std::list
<std::string
>;
194 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
195 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
197 assert(fileout
== nullptr);
198 assert(vMsgsBeforeOpenLog
);
199 fs::path pathDebug
= GetDataDir() / "debug.log";
200 fileout
= fsbridge::fopen(pathDebug
, "a");
202 setbuf(fileout
, nullptr); // unbuffered
203 // dump buffered messages from before we opened the log
204 while (!vMsgsBeforeOpenLog
->empty()) {
205 FileWriteStr(vMsgsBeforeOpenLog
->front(), fileout
);
206 vMsgsBeforeOpenLog
->pop_front();
210 delete vMsgsBeforeOpenLog
;
211 vMsgsBeforeOpenLog
= nullptr;
214 struct CLogCategoryDesc
217 std::string category
;
220 const CLogCategoryDesc LogCategories
[] =
223 {BCLog::NONE
, "none"},
226 {BCLog::MEMPOOL
, "mempool"},
227 {BCLog::HTTP
, "http"},
228 {BCLog::BENCH
, "bench"},
232 {BCLog::ESTIMATEFEE
, "estimatefee"},
233 {BCLog::ADDRMAN
, "addrman"},
234 {BCLog::SELECTCOINS
, "selectcoins"},
235 {BCLog::REINDEX
, "reindex"},
236 {BCLog::CMPCTBLOCK
, "cmpctblock"},
237 {BCLog::RAND
, "rand"},
238 {BCLog::PRUNE
, "prune"},
239 {BCLog::PROXY
, "proxy"},
240 {BCLog::MEMPOOLREJ
, "mempoolrej"},
241 {BCLog::LIBEVENT
, "libevent"},
242 {BCLog::COINDB
, "coindb"},
244 {BCLog::LEVELDB
, "leveldb"},
249 bool GetLogCategory(uint32_t *f
, const std::string
*str
)
256 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
257 if (LogCategories
[i
].category
== *str
) {
258 *f
= LogCategories
[i
].flag
;
266 std::string
ListLogCategories()
270 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
271 // Omit the special cases.
272 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
273 if (outcount
!= 0) ret
+= ", ";
274 ret
+= LogCategories
[i
].category
;
281 std::vector
<CLogCategoryActive
> ListActiveLogCategories()
283 std::vector
<CLogCategoryActive
> ret
;
284 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
285 // Omit the special cases.
286 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
287 CLogCategoryActive catActive
;
288 catActive
.category
= LogCategories
[i
].category
;
289 catActive
.active
= LogAcceptCategory(LogCategories
[i
].flag
);
290 ret
.push_back(catActive
);
297 * fStartedNewLine is a state variable held by the calling context that will
298 * suppress printing of the timestamp when multiple calls are made that don't
299 * end in a newline. Initialize it to true, and hold it, in the calling context.
301 static std::string
LogTimestampStr(const std::string
&str
, std::atomic_bool
*fStartedNewLine
)
303 std::string strStamped
;
308 if (*fStartedNewLine
) {
309 int64_t nTimeMicros
= GetTimeMicros();
310 strStamped
= DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros
/1000000);
312 strStamped
+= strprintf(".%06d", nTimeMicros
%1000000);
313 int64_t mocktime
= GetMockTime();
315 strStamped
+= " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime
) + ")";
317 strStamped
+= ' ' + str
;
321 if (!str
.empty() && str
[str
.size()-1] == '\n')
322 *fStartedNewLine
= true;
324 *fStartedNewLine
= false;
329 int LogPrintStr(const std::string
&str
)
331 int ret
= 0; // Returns total number of characters written
332 static std::atomic_bool
fStartedNewLine(true);
334 std::string strTimestamped
= LogTimestampStr(str
, &fStartedNewLine
);
339 ret
= fwrite(strTimestamped
.data(), 1, strTimestamped
.size(), stdout
);
342 else if (fPrintToDebugLog
)
344 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
345 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
347 // buffer if we haven't opened the log yet
348 if (fileout
== nullptr) {
349 assert(vMsgsBeforeOpenLog
);
350 ret
= strTimestamped
.length();
351 vMsgsBeforeOpenLog
->push_back(strTimestamped
);
355 // reopen the log file, if requested
356 if (fReopenDebugLog
) {
357 fReopenDebugLog
= false;
358 fs::path pathDebug
= GetDataDir() / "debug.log";
359 if (fsbridge::freopen(pathDebug
,"a",fileout
) != nullptr)
360 setbuf(fileout
, nullptr); // unbuffered
363 ret
= FileWriteStr(strTimestamped
, fileout
);
369 /** Interpret string as boolean, for argument parsing */
370 static bool InterpretBool(const std::string
& strValue
)
372 if (strValue
.empty())
374 return (atoi(strValue
) != 0);
377 /** Turn -noX into -X=0 */
378 static void InterpretNegativeSetting(std::string
& strKey
, std::string
& strValue
)
380 if (strKey
.length()>3 && strKey
[0]=='-' && strKey
[1]=='n' && strKey
[2]=='o')
382 strKey
= "-" + strKey
.substr(3);
383 strValue
= InterpretBool(strValue
) ? "0" : "1";
387 void ArgsManager::ParseParameters(int argc
, const char* const argv
[])
391 mapMultiArgs
.clear();
393 for (int i
= 1; i
< argc
; i
++)
395 std::string
str(argv
[i
]);
396 std::string strValue
;
397 size_t is_index
= str
.find('=');
398 if (is_index
!= std::string::npos
)
400 strValue
= str
.substr(is_index
+1);
401 str
= str
.substr(0, is_index
);
404 boost::to_lower(str
);
405 if (boost::algorithm::starts_with(str
, "/"))
406 str
= "-" + str
.substr(1);
412 // Interpret --foo as -foo.
413 // If both --foo and -foo are set, the last takes effect.
414 if (str
.length() > 1 && str
[1] == '-')
416 InterpretNegativeSetting(str
, strValue
);
418 mapArgs
[str
] = strValue
;
419 mapMultiArgs
[str
].push_back(strValue
);
423 std::vector
<std::string
> ArgsManager::GetArgs(const std::string
& strArg
) const
426 auto it
= mapMultiArgs
.find(strArg
);
427 if (it
!= mapMultiArgs
.end()) return it
->second
;
431 bool ArgsManager::IsArgSet(const std::string
& strArg
) const
434 return mapArgs
.count(strArg
);
437 std::string
ArgsManager::GetArg(const std::string
& strArg
, const std::string
& strDefault
) const
440 auto it
= mapArgs
.find(strArg
);
441 if (it
!= mapArgs
.end()) return it
->second
;
445 int64_t ArgsManager::GetArg(const std::string
& strArg
, int64_t nDefault
) const
448 auto it
= mapArgs
.find(strArg
);
449 if (it
!= mapArgs
.end()) return atoi64(it
->second
);
453 bool ArgsManager::GetBoolArg(const std::string
& strArg
, bool fDefault
) const
456 auto it
= mapArgs
.find(strArg
);
457 if (it
!= mapArgs
.end()) return InterpretBool(it
->second
);
461 bool ArgsManager::SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
464 if (IsArgSet(strArg
)) return false;
465 ForceSetArg(strArg
, strValue
);
469 bool ArgsManager::SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
472 return SoftSetArg(strArg
, std::string("1"));
474 return SoftSetArg(strArg
, std::string("0"));
477 void ArgsManager::ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
480 mapArgs
[strArg
] = strValue
;
481 mapMultiArgs
[strArg
] = {strValue
};
486 static const int screenWidth
= 79;
487 static const int optIndent
= 2;
488 static const int msgIndent
= 7;
490 std::string
HelpMessageGroup(const std::string
&message
) {
491 return std::string(message
) + std::string("\n\n");
494 std::string
HelpMessageOpt(const std::string
&option
, const std::string
&message
) {
495 return std::string(optIndent
,' ') + std::string(option
) +
496 std::string("\n") + std::string(msgIndent
,' ') +
497 FormatParagraph(message
, screenWidth
- msgIndent
, msgIndent
) +
501 static std::string
FormatException(const std::exception
* pex
, const char* pszThread
)
504 char pszModule
[MAX_PATH
] = "";
505 GetModuleFileNameA(nullptr, pszModule
, sizeof(pszModule
));
507 const char* pszModule
= "bitcoin";
511 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex
).name(), pex
->what(), pszModule
, pszThread
);
514 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule
, pszThread
);
517 void PrintExceptionContinue(const std::exception
* pex
, const char* pszThread
)
519 std::string message
= FormatException(pex
, pszThread
);
520 LogPrintf("\n\n************************\n%s\n", message
);
521 fprintf(stderr
, "\n\n************************\n%s\n", message
.c_str());
524 fs::path
GetDefaultDataDir()
526 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
527 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
528 // Mac: ~/Library/Application Support/Bitcoin
532 return GetSpecialFolderPath(CSIDL_APPDATA
) / "Bitcoin";
535 char* pszHome
= getenv("HOME");
536 if (pszHome
== nullptr || strlen(pszHome
) == 0)
537 pathRet
= fs::path("/");
539 pathRet
= fs::path(pszHome
);
542 return pathRet
/ "Library/Application Support/Bitcoin";
545 return pathRet
/ ".bitcoin";
550 static fs::path pathCached
;
551 static fs::path pathCachedNetSpecific
;
552 static CCriticalSection csPathCached
;
554 const fs::path
&GetDataDir(bool fNetSpecific
)
559 fs::path
&path
= fNetSpecific
? pathCachedNetSpecific
: pathCached
;
561 // This can be called during exceptions by LogPrintf(), so we cache the
562 // value so we don't have to do memory allocations after that.
566 if (gArgs
.IsArgSet("-datadir")) {
567 path
= fs::system_complete(gArgs
.GetArg("-datadir", ""));
568 if (!fs::is_directory(path
)) {
573 path
= GetDefaultDataDir();
576 path
/= BaseParams().DataDir();
578 if (fs::create_directories(path
)) {
579 // This is the first run, create wallets subdirectory too
580 fs::create_directories(path
/ "wallets");
586 void ClearDatadirCache()
590 pathCached
= fs::path();
591 pathCachedNetSpecific
= fs::path();
594 fs::path
GetConfigFile(const std::string
& confPath
)
596 fs::path
pathConfigFile(confPath
);
597 if (!pathConfigFile
.is_complete())
598 pathConfigFile
= GetDataDir(false) / pathConfigFile
;
600 return pathConfigFile
;
603 void ArgsManager::ReadConfigFile(const std::string
& confPath
)
605 fs::ifstream
streamConfig(GetConfigFile(confPath
));
606 if (!streamConfig
.good())
607 return; // No bitcoin.conf file is OK
611 std::set
<std::string
> setOptions
;
612 setOptions
.insert("*");
614 for (boost::program_options::detail::config_file_iterator
it(streamConfig
, setOptions
), end
; it
!= end
; ++it
)
616 // Don't overwrite existing settings so command line settings override bitcoin.conf
617 std::string strKey
= std::string("-") + it
->string_key
;
618 std::string strValue
= it
->value
[0];
619 InterpretNegativeSetting(strKey
, strValue
);
620 if (mapArgs
.count(strKey
) == 0)
621 mapArgs
[strKey
] = strValue
;
622 mapMultiArgs
[strKey
].push_back(strValue
);
625 // If datadir is changed in .conf file:
630 fs::path
GetPidFile()
632 fs::path
pathPidFile(gArgs
.GetArg("-pid", BITCOIN_PID_FILENAME
));
633 if (!pathPidFile
.is_complete()) pathPidFile
= GetDataDir() / pathPidFile
;
637 void CreatePidFile(const fs::path
&path
, pid_t pid
)
639 FILE* file
= fsbridge::fopen(path
, "w");
642 fprintf(file
, "%d\n", pid
);
648 bool RenameOver(fs::path src
, fs::path dest
)
651 return MoveFileExA(src
.string().c_str(), dest
.string().c_str(),
652 MOVEFILE_REPLACE_EXISTING
) != 0;
654 int rc
= std::rename(src
.string().c_str(), dest
.string().c_str());
660 * Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
661 * Specifically handles case where path p exists, but it wasn't possible for the user to
662 * write to the parent directory.
664 bool TryCreateDirectories(const fs::path
& p
)
668 return fs::create_directories(p
);
669 } catch (const fs::filesystem_error
&) {
670 if (!fs::exists(p
) || !fs::is_directory(p
))
674 // create_directories didn't create the directory, it had to have existed already
678 void FileCommit(FILE *file
)
680 fflush(file
); // harmless if redundantly called
682 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
683 FlushFileBuffers(hFile
);
685 #if defined(__linux__) || defined(__NetBSD__)
686 fdatasync(fileno(file
));
687 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
688 fcntl(fileno(file
), F_FULLFSYNC
, 0);
695 bool TruncateFile(FILE *file
, unsigned int length
) {
697 return _chsize(_fileno(file
), length
) == 0;
699 return ftruncate(fileno(file
), length
) == 0;
704 * this function tries to raise the file descriptor limit to the requested number.
705 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
707 int RaiseFileDescriptorLimit(int nMinFD
) {
711 struct rlimit limitFD
;
712 if (getrlimit(RLIMIT_NOFILE
, &limitFD
) != -1) {
713 if (limitFD
.rlim_cur
< (rlim_t
)nMinFD
) {
714 limitFD
.rlim_cur
= nMinFD
;
715 if (limitFD
.rlim_cur
> limitFD
.rlim_max
)
716 limitFD
.rlim_cur
= limitFD
.rlim_max
;
717 setrlimit(RLIMIT_NOFILE
, &limitFD
);
718 getrlimit(RLIMIT_NOFILE
, &limitFD
);
720 return limitFD
.rlim_cur
;
722 return nMinFD
; // getrlimit failed, assume it's fine
727 * this function tries to make a particular range of a file allocated (corresponding to disk space)
728 * it is advisory, and the range specified in the arguments will never contain live data
730 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
) {
732 // Windows-specific version
733 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
734 LARGE_INTEGER nFileSize
;
735 int64_t nEndPos
= (int64_t)offset
+ length
;
736 nFileSize
.u
.LowPart
= nEndPos
& 0xFFFFFFFF;
737 nFileSize
.u
.HighPart
= nEndPos
>> 32;
738 SetFilePointerEx(hFile
, nFileSize
, 0, FILE_BEGIN
);
740 #elif defined(MAC_OSX)
741 // OSX specific version
743 fst
.fst_flags
= F_ALLOCATECONTIG
;
744 fst
.fst_posmode
= F_PEOFPOSMODE
;
746 fst
.fst_length
= (off_t
)offset
+ length
;
747 fst
.fst_bytesalloc
= 0;
748 if (fcntl(fileno(file
), F_PREALLOCATE
, &fst
) == -1) {
749 fst
.fst_flags
= F_ALLOCATEALL
;
750 fcntl(fileno(file
), F_PREALLOCATE
, &fst
);
752 ftruncate(fileno(file
), fst
.fst_length
);
753 #elif defined(__linux__)
754 // Version using posix_fallocate
755 off_t nEndPos
= (off_t
)offset
+ length
;
756 posix_fallocate(fileno(file
), 0, nEndPos
);
759 // TODO: just write one byte per block
760 static const char buf
[65536] = {};
761 fseek(file
, offset
, SEEK_SET
);
763 unsigned int now
= 65536;
766 fwrite(buf
, 1, now
, file
); // allowed to fail; this function is advisory anyway
772 void ShrinkDebugFile()
774 // Amount of debug.log to save at end when shrinking (must fit in memory)
775 constexpr size_t RECENT_DEBUG_HISTORY_SIZE
= 10 * 1000000;
776 // Scroll debug.log if it's getting too big
777 fs::path pathLog
= GetDataDir() / "debug.log";
778 FILE* file
= fsbridge::fopen(pathLog
, "r");
779 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
780 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
781 if (file
&& fs::file_size(pathLog
) > 11 * (RECENT_DEBUG_HISTORY_SIZE
/ 10))
783 // Restart the file with some of the end
784 std::vector
<char> vch(RECENT_DEBUG_HISTORY_SIZE
, 0);
785 fseek(file
, -((long)vch
.size()), SEEK_END
);
786 int nBytes
= fread(vch
.data(), 1, vch
.size(), file
);
789 file
= fsbridge::fopen(pathLog
, "w");
792 fwrite(vch
.data(), 1, nBytes
, file
);
796 else if (file
!= nullptr)
801 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
)
803 char pszPath
[MAX_PATH
] = "";
805 if(SHGetSpecialFolderPathA(nullptr, pszPath
, nFolder
, fCreate
))
807 return fs::path(pszPath
);
810 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
815 void runCommand(const std::string
& strCommand
)
817 if (strCommand
.empty()) return;
818 int nErr
= ::system(strCommand
.c_str());
820 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand
, nErr
);
823 void RenameThread(const char* name
)
825 #if defined(PR_SET_NAME)
826 // Only the first 15 characters are used (16 - NUL terminator)
827 ::prctl(PR_SET_NAME
, name
, 0, 0, 0);
828 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
829 pthread_set_name_np(pthread_self(), name
);
831 #elif defined(MAC_OSX)
832 pthread_setname_np(name
);
834 // Prevent warnings for unused parameters...
839 void SetupEnvironment()
841 #ifdef HAVE_MALLOPT_ARENA_MAX
842 // glibc-specific: On 32-bit systems set the number of arenas to 1.
843 // By default, since glibc 2.10, the C library will create up to two heap
844 // arenas per core. This is known to cause excessive virtual address space
845 // usage in our usage. Work around it by setting the maximum number of
847 if (sizeof(void*) == 4) {
848 mallopt(M_ARENA_MAX
, 1);
851 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
852 // may be invalid, in which case the "C" locale is used as fallback.
853 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
855 std::locale(""); // Raises a runtime error if current locale is invalid
856 } catch (const std::runtime_error
&) {
857 setenv("LC_ALL", "C", 1);
860 // The path locale is lazy initialized and to avoid deinitialization errors
861 // in multithreading environments, it is set explicitly by the main thread.
862 // A dummy locale is used to extract the internal default locale, used by
863 // fs::path, which is then used to explicitly imbue the path.
864 std::locale loc
= fs::path::imbue(std::locale::classic());
865 fs::path::imbue(loc
);
868 bool SetupNetworking()
871 // Initialize Windows Sockets
873 int ret
= WSAStartup(MAKEWORD(2,2), &wsadata
);
874 if (ret
!= NO_ERROR
|| LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 2)
882 #if BOOST_VERSION >= 105600
883 return boost::thread::physical_concurrency();
884 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
885 return boost::thread::hardware_concurrency();
889 std::string
CopyrightHolders(const std::string
& strPrefix
)
891 std::string strCopyrightHolders
= strPrefix
+ strprintf(_(COPYRIGHT_HOLDERS
), _(COPYRIGHT_HOLDERS_SUBSTITUTION
));
893 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
894 if (strprintf(COPYRIGHT_HOLDERS
, COPYRIGHT_HOLDERS_SUBSTITUTION
).find("Bitcoin Core") == std::string::npos
) {
895 strCopyrightHolders
+= "\n" + strPrefix
+ "The Bitcoin Core developers";
897 return strCopyrightHolders
;
900 // Obtain the application startup time (used for uptime calculation)
901 int64_t GetStartupTime()