[tests] Remove accidental trailing semicolon
[bitcoinplatinum.git] / src / util.cpp
blob653a4f072ad60c151e91b62761d8ff17cfa3fcac
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/join.hpp>
81 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
82 #include <boost/foreach.hpp>
83 #include <boost/program_options/detail/config_file.hpp>
84 #include <boost/program_options/parsers.hpp>
85 #include <boost/thread.hpp>
86 #include <openssl/crypto.h>
87 #include <openssl/rand.h>
88 #include <openssl/conf.h>
91 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
92 const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
94 ArgsManager gArgs;
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]);
113 } else {
114 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL[i]);
118 // Singleton for wrapping OpenSSL setup/teardown.
119 class CInit
121 public:
122 CInit()
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.
133 OPENSSL_no_config();
135 #ifdef WIN32
136 // Seed OpenSSL PRNG with current contents of the screen
137 RAND_screen();
138 #endif
140 // Seed OpenSSL PRNG with performance counter
141 RandAddSeed();
143 ~CInit()
145 // Securely erase the memory used by the PRNG
146 RAND_cleanup();
147 // Shutdown OpenSSL library multithreading support
148 CRYPTO_set_locking_callback(NULL);
149 // Clear the set of locks now to maintain symmetry with the constructor.
150 ppmutexOpenSSL.reset();
153 instance_of_cinit;
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
163 * the mutex).
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 = NULL;
178 static boost::mutex* mutexDebugLog = NULL;
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 == NULL);
189 mutexDebugLog = new boost::mutex();
190 vMsgsBeforeOpenLog = new std::list<std::string>;
193 void OpenDebugLog()
195 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
196 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
198 assert(fileout == NULL);
199 assert(vMsgsBeforeOpenLog);
200 fs::path pathDebug = GetDataDir() / "debug.log";
201 fileout = fsbridge::fopen(pathDebug, "a");
202 if (fileout) {
203 setbuf(fileout, NULL); // unbuffered
204 // dump buffered messages from before we opened the log
205 while (!vMsgsBeforeOpenLog->empty()) {
206 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
207 vMsgsBeforeOpenLog->pop_front();
211 delete vMsgsBeforeOpenLog;
212 vMsgsBeforeOpenLog = NULL;
215 struct CLogCategoryDesc
217 uint32_t flag;
218 std::string category;
221 const CLogCategoryDesc LogCategories[] =
223 {BCLog::NONE, "0"},
224 {BCLog::NET, "net"},
225 {BCLog::TOR, "tor"},
226 {BCLog::MEMPOOL, "mempool"},
227 {BCLog::HTTP, "http"},
228 {BCLog::BENCH, "bench"},
229 {BCLog::ZMQ, "zmq"},
230 {BCLog::DB, "db"},
231 {BCLog::RPC, "rpc"},
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"},
243 {BCLog::QT, "qt"},
244 {BCLog::LEVELDB, "leveldb"},
245 {BCLog::ALL, "1"},
246 {BCLog::ALL, "all"},
249 bool GetLogCategory(uint32_t *f, const std::string *str)
251 if (f && str) {
252 if (*str == "") {
253 *f = BCLog::ALL;
254 return true;
256 for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
257 if (LogCategories[i].category == *str) {
258 *f = LogCategories[i].flag;
259 return true;
263 return false;
266 std::string ListLogCategories()
268 std::string ret;
269 int outcount = 0;
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;
275 outcount++;
278 return ret;
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);
293 return ret;
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;
305 if (!fLogTimestamps)
306 return str;
308 if (*fStartedNewLine) {
309 int64_t nTimeMicros = GetTimeMicros();
310 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
311 if (fLogTimeMicros)
312 strStamped += strprintf(".%06d", nTimeMicros%1000000);
313 int64_t mocktime = GetMockTime();
314 if (mocktime) {
315 strStamped += " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime) + ")";
317 strStamped += ' ' + str;
318 } else
319 strStamped = str;
321 if (!str.empty() && str[str.size()-1] == '\n')
322 *fStartedNewLine = true;
323 else
324 *fStartedNewLine = false;
326 return strStamped;
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);
336 if (fPrintToConsole)
338 // print to console
339 ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
340 fflush(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 == NULL) {
349 assert(vMsgsBeforeOpenLog);
350 ret = strTimestamped.length();
351 vMsgsBeforeOpenLog->push_back(strTimestamped);
353 else
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) != NULL)
360 setbuf(fileout, NULL); // unbuffered
363 ret = FileWriteStr(strTimestamped, fileout);
366 return ret;
369 /** Interpret string as boolean, for argument parsing */
370 static bool InterpretBool(const std::string& strValue)
372 if (strValue.empty())
373 return true;
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[])
389 LOCK(cs_args);
390 mapArgs.clear();
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);
403 #ifdef WIN32
404 boost::to_lower(str);
405 if (boost::algorithm::starts_with(str, "/"))
406 str = "-" + str.substr(1);
407 #endif
409 if (str[0] != '-')
410 break;
412 // Interpret --foo as -foo.
413 // If both --foo and -foo are set, the last takes effect.
414 if (str.length() > 1 && str[1] == '-')
415 str = str.substr(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)
425 LOCK(cs_args);
426 return mapMultiArgs.at(strArg);
429 bool ArgsManager::IsArgSet(const std::string& strArg)
431 LOCK(cs_args);
432 return mapArgs.count(strArg);
435 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault)
437 LOCK(cs_args);
438 if (mapArgs.count(strArg))
439 return mapArgs[strArg];
440 return strDefault;
443 int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault)
445 LOCK(cs_args);
446 if (mapArgs.count(strArg))
447 return atoi64(mapArgs[strArg]);
448 return nDefault;
451 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault)
453 LOCK(cs_args);
454 if (mapArgs.count(strArg))
455 return InterpretBool(mapArgs[strArg]);
456 return fDefault;
459 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
461 LOCK(cs_args);
462 if (mapArgs.count(strArg))
463 return false;
464 ForceSetArg(strArg, strValue);
465 return true;
468 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
470 if (fValue)
471 return SoftSetArg(strArg, std::string("1"));
472 else
473 return SoftSetArg(strArg, std::string("0"));
476 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
478 LOCK(cs_args);
479 mapArgs[strArg] = strValue;
480 mapMultiArgs[strArg].push_back(strValue);
485 static const int screenWidth = 79;
486 static const int optIndent = 2;
487 static const int msgIndent = 7;
489 std::string HelpMessageGroup(const std::string &message) {
490 return std::string(message) + std::string("\n\n");
493 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
494 return std::string(optIndent,' ') + std::string(option) +
495 std::string("\n") + std::string(msgIndent,' ') +
496 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
497 std::string("\n\n");
500 static std::string FormatException(const std::exception* pex, const char* pszThread)
502 #ifdef WIN32
503 char pszModule[MAX_PATH] = "";
504 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
505 #else
506 const char* pszModule = "bitcoin";
507 #endif
508 if (pex)
509 return strprintf(
510 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
511 else
512 return strprintf(
513 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
516 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
518 std::string message = FormatException(pex, pszThread);
519 LogPrintf("\n\n************************\n%s\n", message);
520 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
523 fs::path GetDefaultDataDir()
525 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
526 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
527 // Mac: ~/Library/Application Support/Bitcoin
528 // Unix: ~/.bitcoin
529 #ifdef WIN32
530 // Windows
531 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
532 #else
533 fs::path pathRet;
534 char* pszHome = getenv("HOME");
535 if (pszHome == NULL || strlen(pszHome) == 0)
536 pathRet = fs::path("/");
537 else
538 pathRet = fs::path(pszHome);
539 #ifdef MAC_OSX
540 // Mac
541 return pathRet / "Library/Application Support/Bitcoin";
542 #else
543 // Unix
544 return pathRet / ".bitcoin";
545 #endif
546 #endif
549 static fs::path pathCached;
550 static fs::path pathCachedNetSpecific;
551 static CCriticalSection csPathCached;
553 const fs::path &GetDataDir(bool fNetSpecific)
556 LOCK(csPathCached);
558 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
560 // This can be called during exceptions by LogPrintf(), so we cache the
561 // value so we don't have to do memory allocations after that.
562 if (!path.empty())
563 return path;
565 if (IsArgSet("-datadir")) {
566 path = fs::system_complete(GetArg("-datadir", ""));
567 if (!fs::is_directory(path)) {
568 path = "";
569 return path;
571 } else {
572 path = GetDefaultDataDir();
574 if (fNetSpecific)
575 path /= BaseParams().DataDir();
577 fs::create_directories(path);
579 return path;
582 void ClearDatadirCache()
584 LOCK(csPathCached);
586 pathCached = fs::path();
587 pathCachedNetSpecific = fs::path();
590 fs::path GetConfigFile(const std::string& confPath)
592 fs::path pathConfigFile(confPath);
593 if (!pathConfigFile.is_complete())
594 pathConfigFile = GetDataDir(false) / pathConfigFile;
596 return pathConfigFile;
599 void ArgsManager::ReadConfigFile(const std::string& confPath)
601 fs::ifstream streamConfig(GetConfigFile(confPath));
602 if (!streamConfig.good())
603 return; // No bitcoin.conf file is OK
606 LOCK(cs_args);
607 std::set<std::string> setOptions;
608 setOptions.insert("*");
610 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
612 // Don't overwrite existing settings so command line settings override bitcoin.conf
613 std::string strKey = std::string("-") + it->string_key;
614 std::string strValue = it->value[0];
615 InterpretNegativeSetting(strKey, strValue);
616 if (mapArgs.count(strKey) == 0)
617 mapArgs[strKey] = strValue;
618 mapMultiArgs[strKey].push_back(strValue);
621 // If datadir is changed in .conf file:
622 ClearDatadirCache();
625 #ifndef WIN32
626 fs::path GetPidFile()
628 fs::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME));
629 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
630 return pathPidFile;
633 void CreatePidFile(const fs::path &path, pid_t pid)
635 FILE* file = fsbridge::fopen(path, "w");
636 if (file)
638 fprintf(file, "%d\n", pid);
639 fclose(file);
642 #endif
644 bool RenameOver(fs::path src, fs::path dest)
646 #ifdef WIN32
647 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
648 MOVEFILE_REPLACE_EXISTING) != 0;
649 #else
650 int rc = std::rename(src.string().c_str(), dest.string().c_str());
651 return (rc == 0);
652 #endif /* WIN32 */
656 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
657 * Specifically handles case where path p exists, but it wasn't possible for the user to
658 * write to the parent directory.
660 bool TryCreateDirectory(const fs::path& p)
664 return fs::create_directory(p);
665 } catch (const fs::filesystem_error&) {
666 if (!fs::exists(p) || !fs::is_directory(p))
667 throw;
670 // create_directory didn't create the directory, it had to have existed already
671 return false;
674 void FileCommit(FILE *file)
676 fflush(file); // harmless if redundantly called
677 #ifdef WIN32
678 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
679 FlushFileBuffers(hFile);
680 #else
681 #if defined(__linux__) || defined(__NetBSD__)
682 fdatasync(fileno(file));
683 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
684 fcntl(fileno(file), F_FULLFSYNC, 0);
685 #else
686 fsync(fileno(file));
687 #endif
688 #endif
691 bool TruncateFile(FILE *file, unsigned int length) {
692 #if defined(WIN32)
693 return _chsize(_fileno(file), length) == 0;
694 #else
695 return ftruncate(fileno(file), length) == 0;
696 #endif
700 * this function tries to raise the file descriptor limit to the requested number.
701 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
703 int RaiseFileDescriptorLimit(int nMinFD) {
704 #if defined(WIN32)
705 return 2048;
706 #else
707 struct rlimit limitFD;
708 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
709 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
710 limitFD.rlim_cur = nMinFD;
711 if (limitFD.rlim_cur > limitFD.rlim_max)
712 limitFD.rlim_cur = limitFD.rlim_max;
713 setrlimit(RLIMIT_NOFILE, &limitFD);
714 getrlimit(RLIMIT_NOFILE, &limitFD);
716 return limitFD.rlim_cur;
718 return nMinFD; // getrlimit failed, assume it's fine
719 #endif
723 * this function tries to make a particular range of a file allocated (corresponding to disk space)
724 * it is advisory, and the range specified in the arguments will never contain live data
726 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
727 #if defined(WIN32)
728 // Windows-specific version
729 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
730 LARGE_INTEGER nFileSize;
731 int64_t nEndPos = (int64_t)offset + length;
732 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
733 nFileSize.u.HighPart = nEndPos >> 32;
734 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
735 SetEndOfFile(hFile);
736 #elif defined(MAC_OSX)
737 // OSX specific version
738 fstore_t fst;
739 fst.fst_flags = F_ALLOCATECONTIG;
740 fst.fst_posmode = F_PEOFPOSMODE;
741 fst.fst_offset = 0;
742 fst.fst_length = (off_t)offset + length;
743 fst.fst_bytesalloc = 0;
744 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
745 fst.fst_flags = F_ALLOCATEALL;
746 fcntl(fileno(file), F_PREALLOCATE, &fst);
748 ftruncate(fileno(file), fst.fst_length);
749 #elif defined(__linux__)
750 // Version using posix_fallocate
751 off_t nEndPos = (off_t)offset + length;
752 posix_fallocate(fileno(file), 0, nEndPos);
753 #else
754 // Fallback version
755 // TODO: just write one byte per block
756 static const char buf[65536] = {};
757 fseek(file, offset, SEEK_SET);
758 while (length > 0) {
759 unsigned int now = 65536;
760 if (length < now)
761 now = length;
762 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
763 length -= now;
765 #endif
768 void ShrinkDebugFile()
770 // Amount of debug.log to save at end when shrinking (must fit in memory)
771 constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
772 // Scroll debug.log if it's getting too big
773 fs::path pathLog = GetDataDir() / "debug.log";
774 FILE* file = fsbridge::fopen(pathLog, "r");
775 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
776 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
777 if (file && fs::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
779 // Restart the file with some of the end
780 std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
781 fseek(file, -((long)vch.size()), SEEK_END);
782 int nBytes = fread(vch.data(), 1, vch.size(), file);
783 fclose(file);
785 file = fsbridge::fopen(pathLog, "w");
786 if (file)
788 fwrite(vch.data(), 1, nBytes, file);
789 fclose(file);
792 else if (file != NULL)
793 fclose(file);
796 #ifdef WIN32
797 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
799 char pszPath[MAX_PATH] = "";
801 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
803 return fs::path(pszPath);
806 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
807 return fs::path("");
809 #endif
811 void runCommand(const std::string& strCommand)
813 int nErr = ::system(strCommand.c_str());
814 if (nErr)
815 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
818 void RenameThread(const char* name)
820 #if defined(PR_SET_NAME)
821 // Only the first 15 characters are used (16 - NUL terminator)
822 ::prctl(PR_SET_NAME, name, 0, 0, 0);
823 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
824 pthread_set_name_np(pthread_self(), name);
826 #elif defined(MAC_OSX)
827 pthread_setname_np(name);
828 #else
829 // Prevent warnings for unused parameters...
830 (void)name;
831 #endif
834 void SetupEnvironment()
836 #ifdef HAVE_MALLOPT_ARENA_MAX
837 // glibc-specific: On 32-bit systems set the number of arenas to 1.
838 // By default, since glibc 2.10, the C library will create up to two heap
839 // arenas per core. This is known to cause excessive virtual address space
840 // usage in our usage. Work around it by setting the maximum number of
841 // arenas to 1.
842 if (sizeof(void*) == 4) {
843 mallopt(M_ARENA_MAX, 1);
845 #endif
846 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
847 // may be invalid, in which case the "C" locale is used as fallback.
848 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
849 try {
850 std::locale(""); // Raises a runtime error if current locale is invalid
851 } catch (const std::runtime_error&) {
852 setenv("LC_ALL", "C", 1);
854 #endif
855 // The path locale is lazy initialized and to avoid deinitialization errors
856 // in multithreading environments, it is set explicitly by the main thread.
857 // A dummy locale is used to extract the internal default locale, used by
858 // fs::path, which is then used to explicitly imbue the path.
859 std::locale loc = fs::path::imbue(std::locale::classic());
860 fs::path::imbue(loc);
863 bool SetupNetworking()
865 #ifdef WIN32
866 // Initialize Windows Sockets
867 WSADATA wsadata;
868 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
869 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
870 return false;
871 #endif
872 return true;
875 int GetNumCores()
877 #if BOOST_VERSION >= 105600
878 return boost::thread::physical_concurrency();
879 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
880 return boost::thread::hardware_concurrency();
881 #endif
884 std::string CopyrightHolders(const std::string& strPrefix)
886 std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
888 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
889 if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) {
890 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
892 return strCopyrightHolders;