Merge #9578: Add missing mempool lock for CalculateMemPoolAncestors
[bitcoinplatinum.git] / src / util.cpp
blobba157625d8055a1f934bb2e691fad3f5ab976ad6
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 "random.h"
14 #include "serialize.h"
15 #include "sync.h"
16 #include "utilstrencodings.h"
17 #include "utiltime.h"
19 #include <stdarg.h>
21 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
22 #include <pthread.h>
23 #include <pthread_np.h>
24 #endif
26 #ifndef WIN32
27 // for posix_fallocate
28 #ifdef __linux__
30 #ifdef _POSIX_C_SOURCE
31 #undef _POSIX_C_SOURCE
32 #endif
34 #define _POSIX_C_SOURCE 200112L
36 #endif // __linux__
38 #include <algorithm>
39 #include <fcntl.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
43 #else
45 #ifdef _MSC_VER
46 #pragma warning(disable:4786)
47 #pragma warning(disable:4804)
48 #pragma warning(disable:4805)
49 #pragma warning(disable:4717)
50 #endif
52 #ifdef _WIN32_WINNT
53 #undef _WIN32_WINNT
54 #endif
55 #define _WIN32_WINNT 0x0501
57 #ifdef _WIN32_IE
58 #undef _WIN32_IE
59 #endif
60 #define _WIN32_IE 0x0501
62 #define WIN32_LEAN_AND_MEAN 1
63 #ifndef NOMINMAX
64 #define NOMINMAX
65 #endif
67 #include <io.h> /* for _commit */
68 #include <shlobj.h>
69 #endif
71 #ifdef HAVE_SYS_PRCTL_H
72 #include <sys/prctl.h>
73 #endif
75 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
76 #include <boost/algorithm/string/join.hpp>
77 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
78 #include <boost/filesystem.hpp>
79 #include <boost/filesystem/fstream.hpp>
80 #include <boost/foreach.hpp>
81 #include <boost/program_options/detail/config_file.hpp>
82 #include <boost/program_options/parsers.hpp>
83 #include <boost/thread.hpp>
84 #include <openssl/crypto.h>
85 #include <openssl/rand.h>
86 #include <openssl/conf.h>
88 // Work around clang compilation problem in Boost 1.46:
89 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
90 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
91 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
92 namespace boost {
94 namespace program_options {
95 std::string to_internal(const std::string&);
98 } // namespace boost
100 using namespace std;
102 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
103 const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
105 CCriticalSection cs_args;
106 map<string, string> mapArgs;
107 static map<string, vector<string> > _mapMultiArgs;
108 const map<string, vector<string> >& mapMultiArgs = _mapMultiArgs;
109 bool fDebug = false;
110 bool fPrintToConsole = false;
111 bool fPrintToDebugLog = true;
113 bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
114 bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
115 bool fLogIPs = DEFAULT_LOGIPS;
116 std::atomic<bool> fReopenDebugLog(false);
117 CTranslationInterface translationInterface;
119 /** Init OpenSSL library multithreading support */
120 static CCriticalSection** ppmutexOpenSSL;
121 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
123 if (mode & CRYPTO_LOCK) {
124 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
125 } else {
126 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
130 // Init
131 class CInit
133 public:
134 CInit()
136 // Init OpenSSL library multithreading support
137 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
138 for (int i = 0; i < CRYPTO_num_locks(); i++)
139 ppmutexOpenSSL[i] = new CCriticalSection();
140 CRYPTO_set_locking_callback(locking_callback);
142 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
143 // We don't use them so we don't require the config. However some of our libs may call functions
144 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
145 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
146 // that the config appears to have been loaded and there are no modules/engines available.
147 OPENSSL_no_config();
149 #ifdef WIN32
150 // Seed OpenSSL PRNG with current contents of the screen
151 RAND_screen();
152 #endif
154 // Seed OpenSSL PRNG with performance counter
155 RandAddSeed();
157 ~CInit()
159 // Securely erase the memory used by the PRNG
160 RAND_cleanup();
161 // Shutdown OpenSSL library multithreading support
162 CRYPTO_set_locking_callback(NULL);
163 for (int i = 0; i < CRYPTO_num_locks(); i++)
164 delete ppmutexOpenSSL[i];
165 OPENSSL_free(ppmutexOpenSSL);
168 instance_of_cinit;
171 * LogPrintf() has been broken a couple of times now
172 * by well-meaning people adding mutexes in the most straightforward way.
173 * It breaks because it may be called by global destructors during shutdown.
174 * Since the order of destruction of static/global objects is undefined,
175 * defining a mutex as a global object doesn't work (the mutex gets
176 * destroyed, and then some later destructor calls OutputDebugStringF,
177 * maybe indirectly, and you get a core dump at shutdown trying to lock
178 * the mutex).
181 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
184 * We use boost::call_once() to make sure mutexDebugLog and
185 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
187 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
188 * are leaked on exit. This is ugly, but will be cleaned up by
189 * the OS/libc. When the shutdown sequence is fully audited and
190 * tested, explicit destruction of these objects can be implemented.
192 static FILE* fileout = NULL;
193 static boost::mutex* mutexDebugLog = NULL;
194 static list<string> *vMsgsBeforeOpenLog;
196 static int FileWriteStr(const std::string &str, FILE *fp)
198 return fwrite(str.data(), 1, str.size(), fp);
201 static void DebugPrintInit()
203 assert(mutexDebugLog == NULL);
204 mutexDebugLog = new boost::mutex();
205 vMsgsBeforeOpenLog = new list<string>;
208 void OpenDebugLog()
210 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
211 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
213 assert(fileout == NULL);
214 assert(vMsgsBeforeOpenLog);
215 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
216 fileout = fopen(pathDebug.string().c_str(), "a");
217 if (fileout) setbuf(fileout, NULL); // unbuffered
219 // dump buffered messages from before we opened the log
220 while (!vMsgsBeforeOpenLog->empty()) {
221 FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
222 vMsgsBeforeOpenLog->pop_front();
225 delete vMsgsBeforeOpenLog;
226 vMsgsBeforeOpenLog = NULL;
229 bool LogAcceptCategory(const char* category)
231 if (category != NULL)
233 if (!fDebug)
234 return false;
236 // Give each thread quick access to -debug settings.
237 // This helps prevent issues debugging global destructors,
238 // where mapMultiArgs might be deleted before another
239 // global destructor calls LogPrint()
240 static boost::thread_specific_ptr<set<string> > ptrCategory;
241 if (ptrCategory.get() == NULL)
243 if (mapMultiArgs.count("-debug")) {
244 const vector<string>& categories = mapMultiArgs.at("-debug");
245 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
246 // thread_specific_ptr automatically deletes the set when the thread ends.
247 } else
248 ptrCategory.reset(new set<string>());
250 const set<string>& setCategories = *ptrCategory.get();
252 // if not debugging everything and not debugging specific category, LogPrint does nothing.
253 if (setCategories.count(string("")) == 0 &&
254 setCategories.count(string("1")) == 0 &&
255 setCategories.count(string(category)) == 0)
256 return false;
258 return true;
262 * fStartedNewLine is a state variable held by the calling context that will
263 * suppress printing of the timestamp when multiple calls are made that don't
264 * end in a newline. Initialize it to true, and hold it, in the calling context.
266 static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine)
268 string strStamped;
270 if (!fLogTimestamps)
271 return str;
273 if (*fStartedNewLine) {
274 int64_t nTimeMicros = GetLogTimeMicros();
275 strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
276 if (fLogTimeMicros)
277 strStamped += strprintf(".%06d", nTimeMicros%1000000);
278 strStamped += ' ' + str;
279 } else
280 strStamped = str;
282 if (!str.empty() && str[str.size()-1] == '\n')
283 *fStartedNewLine = true;
284 else
285 *fStartedNewLine = false;
287 return strStamped;
290 int LogPrintStr(const std::string &str)
292 int ret = 0; // Returns total number of characters written
293 static std::atomic_bool fStartedNewLine(true);
295 string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
297 if (fPrintToConsole)
299 // print to console
300 ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
301 fflush(stdout);
303 else if (fPrintToDebugLog)
305 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
306 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
308 // buffer if we haven't opened the log yet
309 if (fileout == NULL) {
310 assert(vMsgsBeforeOpenLog);
311 ret = strTimestamped.length();
312 vMsgsBeforeOpenLog->push_back(strTimestamped);
314 else
316 // reopen the log file, if requested
317 if (fReopenDebugLog) {
318 fReopenDebugLog = false;
319 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
320 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
321 setbuf(fileout, NULL); // unbuffered
324 ret = FileWriteStr(strTimestamped, fileout);
327 return ret;
330 /** Interpret string as boolean, for argument parsing */
331 static bool InterpretBool(const std::string& strValue)
333 if (strValue.empty())
334 return true;
335 return (atoi(strValue) != 0);
338 /** Turn -noX into -X=0 */
339 static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
341 if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
343 strKey = "-" + strKey.substr(3);
344 strValue = InterpretBool(strValue) ? "0" : "1";
348 void ParseParameters(int argc, const char* const argv[])
350 LOCK(cs_args);
351 mapArgs.clear();
352 _mapMultiArgs.clear();
354 for (int i = 1; i < argc; i++)
356 std::string str(argv[i]);
357 std::string strValue;
358 size_t is_index = str.find('=');
359 if (is_index != std::string::npos)
361 strValue = str.substr(is_index+1);
362 str = str.substr(0, is_index);
364 #ifdef WIN32
365 boost::to_lower(str);
366 if (boost::algorithm::starts_with(str, "/"))
367 str = "-" + str.substr(1);
368 #endif
370 if (str[0] != '-')
371 break;
373 // Interpret --foo as -foo.
374 // If both --foo and -foo are set, the last takes effect.
375 if (str.length() > 1 && str[1] == '-')
376 str = str.substr(1);
377 InterpretNegativeSetting(str, strValue);
379 mapArgs[str] = strValue;
380 _mapMultiArgs[str].push_back(strValue);
384 bool IsArgSet(const std::string& strArg)
386 LOCK(cs_args);
387 return mapArgs.count(strArg);
390 std::string GetArg(const std::string& strArg, const std::string& strDefault)
392 LOCK(cs_args);
393 if (mapArgs.count(strArg))
394 return mapArgs[strArg];
395 return strDefault;
398 int64_t GetArg(const std::string& strArg, int64_t nDefault)
400 LOCK(cs_args);
401 if (mapArgs.count(strArg))
402 return atoi64(mapArgs[strArg]);
403 return nDefault;
406 bool GetBoolArg(const std::string& strArg, bool fDefault)
408 LOCK(cs_args);
409 if (mapArgs.count(strArg))
410 return InterpretBool(mapArgs[strArg]);
411 return fDefault;
414 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
416 LOCK(cs_args);
417 if (mapArgs.count(strArg))
418 return false;
419 mapArgs[strArg] = strValue;
420 return true;
423 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
425 if (fValue)
426 return SoftSetArg(strArg, std::string("1"));
427 else
428 return SoftSetArg(strArg, std::string("0"));
431 void ForceSetArg(const std::string& strArg, const std::string& strValue)
433 LOCK(cs_args);
434 mapArgs[strArg] = strValue;
439 static const int screenWidth = 79;
440 static const int optIndent = 2;
441 static const int msgIndent = 7;
443 std::string HelpMessageGroup(const std::string &message) {
444 return std::string(message) + std::string("\n\n");
447 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
448 return std::string(optIndent,' ') + std::string(option) +
449 std::string("\n") + std::string(msgIndent,' ') +
450 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
451 std::string("\n\n");
454 static std::string FormatException(const std::exception* pex, const char* pszThread)
456 #ifdef WIN32
457 char pszModule[MAX_PATH] = "";
458 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
459 #else
460 const char* pszModule = "bitcoin";
461 #endif
462 if (pex)
463 return strprintf(
464 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
465 else
466 return strprintf(
467 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
470 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
472 std::string message = FormatException(pex, pszThread);
473 LogPrintf("\n\n************************\n%s\n", message);
474 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
477 boost::filesystem::path GetDefaultDataDir()
479 namespace fs = boost::filesystem;
480 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
481 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
482 // Mac: ~/Library/Application Support/Bitcoin
483 // Unix: ~/.bitcoin
484 #ifdef WIN32
485 // Windows
486 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
487 #else
488 fs::path pathRet;
489 char* pszHome = getenv("HOME");
490 if (pszHome == NULL || strlen(pszHome) == 0)
491 pathRet = fs::path("/");
492 else
493 pathRet = fs::path(pszHome);
494 #ifdef MAC_OSX
495 // Mac
496 return pathRet / "Library/Application Support/Bitcoin";
497 #else
498 // Unix
499 return pathRet / ".bitcoin";
500 #endif
501 #endif
504 static boost::filesystem::path pathCached;
505 static boost::filesystem::path pathCachedNetSpecific;
506 static CCriticalSection csPathCached;
508 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
510 namespace fs = boost::filesystem;
512 LOCK(csPathCached);
514 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
516 // This can be called during exceptions by LogPrintf(), so we cache the
517 // value so we don't have to do memory allocations after that.
518 if (!path.empty())
519 return path;
521 if (IsArgSet("-datadir")) {
522 path = fs::system_complete(GetArg("-datadir", ""));
523 if (!fs::is_directory(path)) {
524 path = "";
525 return path;
527 } else {
528 path = GetDefaultDataDir();
530 if (fNetSpecific)
531 path /= BaseParams().DataDir();
533 fs::create_directories(path);
535 return path;
538 void ClearDatadirCache()
540 LOCK(csPathCached);
542 pathCached = boost::filesystem::path();
543 pathCachedNetSpecific = boost::filesystem::path();
546 boost::filesystem::path GetConfigFile(const std::string& confPath)
548 boost::filesystem::path pathConfigFile(confPath);
549 if (!pathConfigFile.is_complete())
550 pathConfigFile = GetDataDir(false) / pathConfigFile;
552 return pathConfigFile;
555 void ReadConfigFile(const std::string& confPath)
557 boost::filesystem::ifstream streamConfig(GetConfigFile(confPath));
558 if (!streamConfig.good())
559 return; // No bitcoin.conf file is OK
562 LOCK(cs_args);
563 set<string> setOptions;
564 setOptions.insert("*");
566 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
568 // Don't overwrite existing settings so command line settings override bitcoin.conf
569 string strKey = string("-") + it->string_key;
570 string strValue = it->value[0];
571 InterpretNegativeSetting(strKey, strValue);
572 if (mapArgs.count(strKey) == 0)
573 mapArgs[strKey] = strValue;
574 _mapMultiArgs[strKey].push_back(strValue);
577 // If datadir is changed in .conf file:
578 ClearDatadirCache();
581 #ifndef WIN32
582 boost::filesystem::path GetPidFile()
584 boost::filesystem::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME));
585 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
586 return pathPidFile;
589 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
591 FILE* file = fopen(path.string().c_str(), "w");
592 if (file)
594 fprintf(file, "%d\n", pid);
595 fclose(file);
598 #endif
600 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
602 #ifdef WIN32
603 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
604 MOVEFILE_REPLACE_EXISTING) != 0;
605 #else
606 int rc = std::rename(src.string().c_str(), dest.string().c_str());
607 return (rc == 0);
608 #endif /* WIN32 */
612 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
613 * Specifically handles case where path p exists, but it wasn't possible for the user to
614 * write to the parent directory.
616 bool TryCreateDirectory(const boost::filesystem::path& p)
620 return boost::filesystem::create_directory(p);
621 } catch (const boost::filesystem::filesystem_error&) {
622 if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
623 throw;
626 // create_directory didn't create the directory, it had to have existed already
627 return false;
630 void FileCommit(FILE *file)
632 fflush(file); // harmless if redundantly called
633 #ifdef WIN32
634 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
635 FlushFileBuffers(hFile);
636 #else
637 #if defined(__linux__) || defined(__NetBSD__)
638 fdatasync(fileno(file));
639 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
640 fcntl(fileno(file), F_FULLFSYNC, 0);
641 #else
642 fsync(fileno(file));
643 #endif
644 #endif
647 bool TruncateFile(FILE *file, unsigned int length) {
648 #if defined(WIN32)
649 return _chsize(_fileno(file), length) == 0;
650 #else
651 return ftruncate(fileno(file), length) == 0;
652 #endif
656 * this function tries to raise the file descriptor limit to the requested number.
657 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
659 int RaiseFileDescriptorLimit(int nMinFD) {
660 #if defined(WIN32)
661 return 2048;
662 #else
663 struct rlimit limitFD;
664 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
665 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
666 limitFD.rlim_cur = nMinFD;
667 if (limitFD.rlim_cur > limitFD.rlim_max)
668 limitFD.rlim_cur = limitFD.rlim_max;
669 setrlimit(RLIMIT_NOFILE, &limitFD);
670 getrlimit(RLIMIT_NOFILE, &limitFD);
672 return limitFD.rlim_cur;
674 return nMinFD; // getrlimit failed, assume it's fine
675 #endif
679 * this function tries to make a particular range of a file allocated (corresponding to disk space)
680 * it is advisory, and the range specified in the arguments will never contain live data
682 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
683 #if defined(WIN32)
684 // Windows-specific version
685 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
686 LARGE_INTEGER nFileSize;
687 int64_t nEndPos = (int64_t)offset + length;
688 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
689 nFileSize.u.HighPart = nEndPos >> 32;
690 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
691 SetEndOfFile(hFile);
692 #elif defined(MAC_OSX)
693 // OSX specific version
694 fstore_t fst;
695 fst.fst_flags = F_ALLOCATECONTIG;
696 fst.fst_posmode = F_PEOFPOSMODE;
697 fst.fst_offset = 0;
698 fst.fst_length = (off_t)offset + length;
699 fst.fst_bytesalloc = 0;
700 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
701 fst.fst_flags = F_ALLOCATEALL;
702 fcntl(fileno(file), F_PREALLOCATE, &fst);
704 ftruncate(fileno(file), fst.fst_length);
705 #elif defined(__linux__)
706 // Version using posix_fallocate
707 off_t nEndPos = (off_t)offset + length;
708 posix_fallocate(fileno(file), 0, nEndPos);
709 #else
710 // Fallback version
711 // TODO: just write one byte per block
712 static const char buf[65536] = {};
713 fseek(file, offset, SEEK_SET);
714 while (length > 0) {
715 unsigned int now = 65536;
716 if (length < now)
717 now = length;
718 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
719 length -= now;
721 #endif
724 void ShrinkDebugFile()
726 // Amount of debug.log to save at end when shrinking (must fit in memory)
727 constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
728 // Scroll debug.log if it's getting too big
729 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
730 FILE* file = fopen(pathLog.string().c_str(), "r");
731 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
732 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
733 if (file && boost::filesystem::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
735 // Restart the file with some of the end
736 std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
737 fseek(file, -((long)vch.size()), SEEK_END);
738 int nBytes = fread(vch.data(), 1, vch.size(), file);
739 fclose(file);
741 file = fopen(pathLog.string().c_str(), "w");
742 if (file)
744 fwrite(vch.data(), 1, nBytes, file);
745 fclose(file);
748 else if (file != NULL)
749 fclose(file);
752 #ifdef WIN32
753 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
755 namespace fs = boost::filesystem;
757 char pszPath[MAX_PATH] = "";
759 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
761 return fs::path(pszPath);
764 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
765 return fs::path("");
767 #endif
769 void runCommand(const std::string& strCommand)
771 int nErr = ::system(strCommand.c_str());
772 if (nErr)
773 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
776 void RenameThread(const char* name)
778 #if defined(PR_SET_NAME)
779 // Only the first 15 characters are used (16 - NUL terminator)
780 ::prctl(PR_SET_NAME, name, 0, 0, 0);
781 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
782 pthread_set_name_np(pthread_self(), name);
784 #elif defined(MAC_OSX)
785 pthread_setname_np(name);
786 #else
787 // Prevent warnings for unused parameters...
788 (void)name;
789 #endif
792 void SetupEnvironment()
794 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
795 // may be invalid, in which case the "C" locale is used as fallback.
796 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
797 try {
798 std::locale(""); // Raises a runtime error if current locale is invalid
799 } catch (const std::runtime_error&) {
800 setenv("LC_ALL", "C", 1);
802 #endif
803 // The path locale is lazy initialized and to avoid deinitialization errors
804 // in multithreading environments, it is set explicitly by the main thread.
805 // A dummy locale is used to extract the internal default locale, used by
806 // boost::filesystem::path, which is then used to explicitly imbue the path.
807 std::locale loc = boost::filesystem::path::imbue(std::locale::classic());
808 boost::filesystem::path::imbue(loc);
811 bool SetupNetworking()
813 #ifdef WIN32
814 // Initialize Windows Sockets
815 WSADATA wsadata;
816 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
817 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
818 return false;
819 #endif
820 return true;
823 int GetNumCores()
825 #if BOOST_VERSION >= 105600
826 return boost::thread::physical_concurrency();
827 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
828 return boost::thread::hardware_concurrency();
829 #endif
832 std::string CopyrightHolders(const std::string& strPrefix)
834 std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
836 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
837 if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) {
838 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
840 return strCopyrightHolders;