Remove unused Boost includes
[bitcoinplatinum.git] / src / util.cpp
blobd00b05c4c543c81a10e7649f25244a986a0814dc
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"
8 #endif
10 #include "util.h"
12 #include "chainparamsbase.h"
13 #include "fs.h"
14 #include "random.h"
15 #include "serialize.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 #ifdef HAVE_MALLOPT_ARENA_MAX
76 #include <malloc.h>
77 #endif
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>
88 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
89 const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
91 ArgsManager gArgs;
92 bool fPrintToConsole = false;
93 bool fPrintToDebugLog = true;
95 bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
96 bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
97 bool fLogIPs = DEFAULT_LOGIPS;
98 std::atomic<bool> fReopenDebugLog(false);
99 CTranslationInterface translationInterface;
101 /** Log categories bitfield. */
102 std::atomic<uint32_t> logCategories(0);
104 /** Init OpenSSL library multithreading support */
105 static std::unique_ptr<CCriticalSection[]> ppmutexOpenSSL;
106 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
108 if (mode & CRYPTO_LOCK) {
109 ENTER_CRITICAL_SECTION(ppmutexOpenSSL[i]);
110 } else {
111 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL[i]);
115 // Singleton for wrapping OpenSSL setup/teardown.
116 class CInit
118 public:
119 CInit()
121 // Init OpenSSL library multithreading support
122 ppmutexOpenSSL.reset(new CCriticalSection[CRYPTO_num_locks()]);
123 CRYPTO_set_locking_callback(locking_callback);
125 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
126 // We don't use them so we don't require the config. However some of our libs may call functions
127 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
128 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
129 // that the config appears to have been loaded and there are no modules/engines available.
130 OPENSSL_no_config();
132 #ifdef WIN32
133 // Seed OpenSSL PRNG with current contents of the screen
134 RAND_screen();
135 #endif
137 // Seed OpenSSL PRNG with performance counter
138 RandAddSeed();
140 ~CInit()
142 // Securely erase the memory used by the PRNG
143 RAND_cleanup();
144 // Shutdown OpenSSL library multithreading support
145 CRYPTO_set_locking_callback(NULL);
146 // Clear the set of locks now to maintain symmetry with the constructor.
147 ppmutexOpenSSL.reset();
150 instance_of_cinit;
153 * LogPrintf() has been broken a couple of times now
154 * by well-meaning people adding mutexes in the most straightforward way.
155 * It breaks because it may be called by global destructors during shutdown.
156 * Since the order of destruction of static/global objects is undefined,
157 * defining a mutex as a global object doesn't work (the mutex gets
158 * destroyed, and then some later destructor calls OutputDebugStringF,
159 * maybe indirectly, and you get a core dump at shutdown trying to lock
160 * the mutex).
163 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
166 * We use boost::call_once() to make sure mutexDebugLog and
167 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
169 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
170 * are leaked on exit. This is ugly, but will be cleaned up by
171 * the OS/libc. When the shutdown sequence is fully audited and
172 * tested, explicit destruction of these objects can be implemented.
174 static FILE* fileout = NULL;
175 static boost::mutex* mutexDebugLog = NULL;
176 static std::list<std::string>* vMsgsBeforeOpenLog;
178 static int FileWriteStr(const std::string &str, FILE *fp)
180 return fwrite(str.data(), 1, str.size(), fp);
183 static void DebugPrintInit()
185 assert(mutexDebugLog == NULL);
186 mutexDebugLog = new boost::mutex();
187 vMsgsBeforeOpenLog = new std::list<std::string>;
190 void OpenDebugLog()
192 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
193 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
195 assert(fileout == NULL);
196 assert(vMsgsBeforeOpenLog);
197 fs::path pathDebug = GetDataDir() / "debug.log";
198 fileout = fsbridge::fopen(pathDebug, "a");
199 if (fileout) {
200 setbuf(fileout, NULL); // unbuffered
201 // dump buffered messages from before we opened the log
202 while (!vMsgsBeforeOpenLog->empty()) {
203 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
204 vMsgsBeforeOpenLog->pop_front();
208 delete vMsgsBeforeOpenLog;
209 vMsgsBeforeOpenLog = NULL;
212 struct CLogCategoryDesc
214 uint32_t flag;
215 std::string category;
218 const CLogCategoryDesc LogCategories[] =
220 {BCLog::NONE, "0"},
221 {BCLog::NET, "net"},
222 {BCLog::TOR, "tor"},
223 {BCLog::MEMPOOL, "mempool"},
224 {BCLog::HTTP, "http"},
225 {BCLog::BENCH, "bench"},
226 {BCLog::ZMQ, "zmq"},
227 {BCLog::DB, "db"},
228 {BCLog::RPC, "rpc"},
229 {BCLog::ESTIMATEFEE, "estimatefee"},
230 {BCLog::ADDRMAN, "addrman"},
231 {BCLog::SELECTCOINS, "selectcoins"},
232 {BCLog::REINDEX, "reindex"},
233 {BCLog::CMPCTBLOCK, "cmpctblock"},
234 {BCLog::RAND, "rand"},
235 {BCLog::PRUNE, "prune"},
236 {BCLog::PROXY, "proxy"},
237 {BCLog::MEMPOOLREJ, "mempoolrej"},
238 {BCLog::LIBEVENT, "libevent"},
239 {BCLog::COINDB, "coindb"},
240 {BCLog::QT, "qt"},
241 {BCLog::LEVELDB, "leveldb"},
242 {BCLog::ALL, "1"},
243 {BCLog::ALL, "all"},
246 bool GetLogCategory(uint32_t *f, const std::string *str)
248 if (f && str) {
249 if (*str == "") {
250 *f = BCLog::ALL;
251 return true;
253 for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
254 if (LogCategories[i].category == *str) {
255 *f = LogCategories[i].flag;
256 return true;
260 return false;
263 std::string ListLogCategories()
265 std::string ret;
266 int outcount = 0;
267 for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
268 // Omit the special cases.
269 if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL) {
270 if (outcount != 0) ret += ", ";
271 ret += LogCategories[i].category;
272 outcount++;
275 return ret;
278 std::vector<CLogCategoryActive> ListActiveLogCategories()
280 std::vector<CLogCategoryActive> ret;
281 for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
282 // Omit the special cases.
283 if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL) {
284 CLogCategoryActive catActive;
285 catActive.category = LogCategories[i].category;
286 catActive.active = LogAcceptCategory(LogCategories[i].flag);
287 ret.push_back(catActive);
290 return ret;
294 * fStartedNewLine is a state variable held by the calling context that will
295 * suppress printing of the timestamp when multiple calls are made that don't
296 * end in a newline. Initialize it to true, and hold it, in the calling context.
298 static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine)
300 std::string strStamped;
302 if (!fLogTimestamps)
303 return str;
305 if (*fStartedNewLine) {
306 int64_t nTimeMicros = GetTimeMicros();
307 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
308 if (fLogTimeMicros)
309 strStamped += strprintf(".%06d", nTimeMicros%1000000);
310 int64_t mocktime = GetMockTime();
311 if (mocktime) {
312 strStamped += " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime) + ")";
314 strStamped += ' ' + str;
315 } else
316 strStamped = str;
318 if (!str.empty() && str[str.size()-1] == '\n')
319 *fStartedNewLine = true;
320 else
321 *fStartedNewLine = false;
323 return strStamped;
326 int LogPrintStr(const std::string &str)
328 int ret = 0; // Returns total number of characters written
329 static std::atomic_bool fStartedNewLine(true);
331 std::string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
333 if (fPrintToConsole)
335 // print to console
336 ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
337 fflush(stdout);
339 else if (fPrintToDebugLog)
341 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
342 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
344 // buffer if we haven't opened the log yet
345 if (fileout == NULL) {
346 assert(vMsgsBeforeOpenLog);
347 ret = strTimestamped.length();
348 vMsgsBeforeOpenLog->push_back(strTimestamped);
350 else
352 // reopen the log file, if requested
353 if (fReopenDebugLog) {
354 fReopenDebugLog = false;
355 fs::path pathDebug = GetDataDir() / "debug.log";
356 if (fsbridge::freopen(pathDebug,"a",fileout) != NULL)
357 setbuf(fileout, NULL); // unbuffered
360 ret = FileWriteStr(strTimestamped, fileout);
363 return ret;
366 /** Interpret string as boolean, for argument parsing */
367 static bool InterpretBool(const std::string& strValue)
369 if (strValue.empty())
370 return true;
371 return (atoi(strValue) != 0);
374 /** Turn -noX into -X=0 */
375 static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
377 if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
379 strKey = "-" + strKey.substr(3);
380 strValue = InterpretBool(strValue) ? "0" : "1";
384 void ArgsManager::ParseParameters(int argc, const char* const argv[])
386 LOCK(cs_args);
387 mapArgs.clear();
388 mapMultiArgs.clear();
390 for (int i = 1; i < argc; i++)
392 std::string str(argv[i]);
393 std::string strValue;
394 size_t is_index = str.find('=');
395 if (is_index != std::string::npos)
397 strValue = str.substr(is_index+1);
398 str = str.substr(0, is_index);
400 #ifdef WIN32
401 boost::to_lower(str);
402 if (boost::algorithm::starts_with(str, "/"))
403 str = "-" + str.substr(1);
404 #endif
406 if (str[0] != '-')
407 break;
409 // Interpret --foo as -foo.
410 // If both --foo and -foo are set, the last takes effect.
411 if (str.length() > 1 && str[1] == '-')
412 str = str.substr(1);
413 InterpretNegativeSetting(str, strValue);
415 mapArgs[str] = strValue;
416 mapMultiArgs[str].push_back(strValue);
420 std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg)
422 LOCK(cs_args);
423 return mapMultiArgs.at(strArg);
426 bool ArgsManager::IsArgSet(const std::string& strArg)
428 LOCK(cs_args);
429 return mapArgs.count(strArg);
432 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault)
434 LOCK(cs_args);
435 if (mapArgs.count(strArg))
436 return mapArgs[strArg];
437 return strDefault;
440 int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault)
442 LOCK(cs_args);
443 if (mapArgs.count(strArg))
444 return atoi64(mapArgs[strArg]);
445 return nDefault;
448 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault)
450 LOCK(cs_args);
451 if (mapArgs.count(strArg))
452 return InterpretBool(mapArgs[strArg]);
453 return fDefault;
456 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
458 LOCK(cs_args);
459 if (mapArgs.count(strArg))
460 return false;
461 ForceSetArg(strArg, strValue);
462 return true;
465 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
467 if (fValue)
468 return SoftSetArg(strArg, std::string("1"));
469 else
470 return SoftSetArg(strArg, std::string("0"));
473 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
475 LOCK(cs_args);
476 mapArgs[strArg] = strValue;
477 mapMultiArgs[strArg].push_back(strValue);
482 static const int screenWidth = 79;
483 static const int optIndent = 2;
484 static const int msgIndent = 7;
486 std::string HelpMessageGroup(const std::string &message) {
487 return std::string(message) + std::string("\n\n");
490 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
491 return std::string(optIndent,' ') + std::string(option) +
492 std::string("\n") + std::string(msgIndent,' ') +
493 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
494 std::string("\n\n");
497 static std::string FormatException(const std::exception* pex, const char* pszThread)
499 #ifdef WIN32
500 char pszModule[MAX_PATH] = "";
501 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
502 #else
503 const char* pszModule = "bitcoin";
504 #endif
505 if (pex)
506 return strprintf(
507 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
508 else
509 return strprintf(
510 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
513 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
515 std::string message = FormatException(pex, pszThread);
516 LogPrintf("\n\n************************\n%s\n", message);
517 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
520 fs::path GetDefaultDataDir()
522 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
523 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
524 // Mac: ~/Library/Application Support/Bitcoin
525 // Unix: ~/.bitcoin
526 #ifdef WIN32
527 // Windows
528 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
529 #else
530 fs::path pathRet;
531 char* pszHome = getenv("HOME");
532 if (pszHome == NULL || strlen(pszHome) == 0)
533 pathRet = fs::path("/");
534 else
535 pathRet = fs::path(pszHome);
536 #ifdef MAC_OSX
537 // Mac
538 return pathRet / "Library/Application Support/Bitcoin";
539 #else
540 // Unix
541 return pathRet / ".bitcoin";
542 #endif
543 #endif
546 static fs::path pathCached;
547 static fs::path pathCachedNetSpecific;
548 static CCriticalSection csPathCached;
550 const fs::path &GetDataDir(bool fNetSpecific)
553 LOCK(csPathCached);
555 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
557 // This can be called during exceptions by LogPrintf(), so we cache the
558 // value so we don't have to do memory allocations after that.
559 if (!path.empty())
560 return path;
562 if (IsArgSet("-datadir")) {
563 path = fs::system_complete(GetArg("-datadir", ""));
564 if (!fs::is_directory(path)) {
565 path = "";
566 return path;
568 } else {
569 path = GetDefaultDataDir();
571 if (fNetSpecific)
572 path /= BaseParams().DataDir();
574 fs::create_directories(path);
576 return path;
579 void ClearDatadirCache()
581 LOCK(csPathCached);
583 pathCached = fs::path();
584 pathCachedNetSpecific = fs::path();
587 fs::path GetConfigFile(const std::string& confPath)
589 fs::path pathConfigFile(confPath);
590 if (!pathConfigFile.is_complete())
591 pathConfigFile = GetDataDir(false) / pathConfigFile;
593 return pathConfigFile;
596 void ArgsManager::ReadConfigFile(const std::string& confPath)
598 fs::ifstream streamConfig(GetConfigFile(confPath));
599 if (!streamConfig.good())
600 return; // No bitcoin.conf file is OK
603 LOCK(cs_args);
604 std::set<std::string> setOptions;
605 setOptions.insert("*");
607 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
609 // Don't overwrite existing settings so command line settings override bitcoin.conf
610 std::string strKey = std::string("-") + it->string_key;
611 std::string strValue = it->value[0];
612 InterpretNegativeSetting(strKey, strValue);
613 if (mapArgs.count(strKey) == 0)
614 mapArgs[strKey] = strValue;
615 mapMultiArgs[strKey].push_back(strValue);
618 // If datadir is changed in .conf file:
619 ClearDatadirCache();
622 #ifndef WIN32
623 fs::path GetPidFile()
625 fs::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME));
626 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
627 return pathPidFile;
630 void CreatePidFile(const fs::path &path, pid_t pid)
632 FILE* file = fsbridge::fopen(path, "w");
633 if (file)
635 fprintf(file, "%d\n", pid);
636 fclose(file);
639 #endif
641 bool RenameOver(fs::path src, fs::path dest)
643 #ifdef WIN32
644 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
645 MOVEFILE_REPLACE_EXISTING) != 0;
646 #else
647 int rc = std::rename(src.string().c_str(), dest.string().c_str());
648 return (rc == 0);
649 #endif /* WIN32 */
653 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
654 * Specifically handles case where path p exists, but it wasn't possible for the user to
655 * write to the parent directory.
657 bool TryCreateDirectory(const fs::path& p)
661 return fs::create_directory(p);
662 } catch (const fs::filesystem_error&) {
663 if (!fs::exists(p) || !fs::is_directory(p))
664 throw;
667 // create_directory didn't create the directory, it had to have existed already
668 return false;
671 void FileCommit(FILE *file)
673 fflush(file); // harmless if redundantly called
674 #ifdef WIN32
675 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
676 FlushFileBuffers(hFile);
677 #else
678 #if defined(__linux__) || defined(__NetBSD__)
679 fdatasync(fileno(file));
680 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
681 fcntl(fileno(file), F_FULLFSYNC, 0);
682 #else
683 fsync(fileno(file));
684 #endif
685 #endif
688 bool TruncateFile(FILE *file, unsigned int length) {
689 #if defined(WIN32)
690 return _chsize(_fileno(file), length) == 0;
691 #else
692 return ftruncate(fileno(file), length) == 0;
693 #endif
697 * this function tries to raise the file descriptor limit to the requested number.
698 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
700 int RaiseFileDescriptorLimit(int nMinFD) {
701 #if defined(WIN32)
702 return 2048;
703 #else
704 struct rlimit limitFD;
705 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
706 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
707 limitFD.rlim_cur = nMinFD;
708 if (limitFD.rlim_cur > limitFD.rlim_max)
709 limitFD.rlim_cur = limitFD.rlim_max;
710 setrlimit(RLIMIT_NOFILE, &limitFD);
711 getrlimit(RLIMIT_NOFILE, &limitFD);
713 return limitFD.rlim_cur;
715 return nMinFD; // getrlimit failed, assume it's fine
716 #endif
720 * this function tries to make a particular range of a file allocated (corresponding to disk space)
721 * it is advisory, and the range specified in the arguments will never contain live data
723 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
724 #if defined(WIN32)
725 // Windows-specific version
726 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
727 LARGE_INTEGER nFileSize;
728 int64_t nEndPos = (int64_t)offset + length;
729 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
730 nFileSize.u.HighPart = nEndPos >> 32;
731 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
732 SetEndOfFile(hFile);
733 #elif defined(MAC_OSX)
734 // OSX specific version
735 fstore_t fst;
736 fst.fst_flags = F_ALLOCATECONTIG;
737 fst.fst_posmode = F_PEOFPOSMODE;
738 fst.fst_offset = 0;
739 fst.fst_length = (off_t)offset + length;
740 fst.fst_bytesalloc = 0;
741 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
742 fst.fst_flags = F_ALLOCATEALL;
743 fcntl(fileno(file), F_PREALLOCATE, &fst);
745 ftruncate(fileno(file), fst.fst_length);
746 #elif defined(__linux__)
747 // Version using posix_fallocate
748 off_t nEndPos = (off_t)offset + length;
749 posix_fallocate(fileno(file), 0, nEndPos);
750 #else
751 // Fallback version
752 // TODO: just write one byte per block
753 static const char buf[65536] = {};
754 fseek(file, offset, SEEK_SET);
755 while (length > 0) {
756 unsigned int now = 65536;
757 if (length < now)
758 now = length;
759 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
760 length -= now;
762 #endif
765 void ShrinkDebugFile()
767 // Amount of debug.log to save at end when shrinking (must fit in memory)
768 constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
769 // Scroll debug.log if it's getting too big
770 fs::path pathLog = GetDataDir() / "debug.log";
771 FILE* file = fsbridge::fopen(pathLog, "r");
772 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
773 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
774 if (file && fs::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
776 // Restart the file with some of the end
777 std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
778 fseek(file, -((long)vch.size()), SEEK_END);
779 int nBytes = fread(vch.data(), 1, vch.size(), file);
780 fclose(file);
782 file = fsbridge::fopen(pathLog, "w");
783 if (file)
785 fwrite(vch.data(), 1, nBytes, file);
786 fclose(file);
789 else if (file != NULL)
790 fclose(file);
793 #ifdef WIN32
794 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
796 char pszPath[MAX_PATH] = "";
798 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
800 return fs::path(pszPath);
803 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
804 return fs::path("");
806 #endif
808 void runCommand(const std::string& strCommand)
810 int nErr = ::system(strCommand.c_str());
811 if (nErr)
812 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
815 void RenameThread(const char* name)
817 #if defined(PR_SET_NAME)
818 // Only the first 15 characters are used (16 - NUL terminator)
819 ::prctl(PR_SET_NAME, name, 0, 0, 0);
820 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
821 pthread_set_name_np(pthread_self(), name);
823 #elif defined(MAC_OSX)
824 pthread_setname_np(name);
825 #else
826 // Prevent warnings for unused parameters...
827 (void)name;
828 #endif
831 void SetupEnvironment()
833 #ifdef HAVE_MALLOPT_ARENA_MAX
834 // glibc-specific: On 32-bit systems set the number of arenas to 1.
835 // By default, since glibc 2.10, the C library will create up to two heap
836 // arenas per core. This is known to cause excessive virtual address space
837 // usage in our usage. Work around it by setting the maximum number of
838 // arenas to 1.
839 if (sizeof(void*) == 4) {
840 mallopt(M_ARENA_MAX, 1);
842 #endif
843 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
844 // may be invalid, in which case the "C" locale is used as fallback.
845 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
846 try {
847 std::locale(""); // Raises a runtime error if current locale is invalid
848 } catch (const std::runtime_error&) {
849 setenv("LC_ALL", "C", 1);
851 #endif
852 // The path locale is lazy initialized and to avoid deinitialization errors
853 // in multithreading environments, it is set explicitly by the main thread.
854 // A dummy locale is used to extract the internal default locale, used by
855 // fs::path, which is then used to explicitly imbue the path.
856 std::locale loc = fs::path::imbue(std::locale::classic());
857 fs::path::imbue(loc);
860 bool SetupNetworking()
862 #ifdef WIN32
863 // Initialize Windows Sockets
864 WSADATA wsadata;
865 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
866 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
867 return false;
868 #endif
869 return true;
872 int GetNumCores()
874 #if BOOST_VERSION >= 105600
875 return boost::thread::physical_concurrency();
876 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
877 return boost::thread::hardware_concurrency();
878 #endif
881 std::string CopyrightHolders(const std::string& strPrefix)
883 std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
885 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
886 if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) {
887 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
889 return strCopyrightHolders;