]> Git Repo - VerusCoin.git/blame - src/util.h
Merge pull request #1083 from laanwj/2012_04_connectionicon
[VerusCoin.git] / src / util.h
CommitLineData
1f2e0df8 1// Copyright (c) 2009-2010 Satoshi Nakamoto
88216419 2// Copyright (c) 2009-2012 The Bitcoin developers
1f2e0df8
WL
3// Distributed under the MIT/X11 software license, see the accompanying
4// file license.txt or http://www.opensource.org/licenses/mit-license.php.
5#ifndef BITCOIN_UTIL_H
6#define BITCOIN_UTIL_H
7
8#include "uint256.h"
9
6853e627 10#ifndef WIN32
1f2e0df8 11#include <sys/types.h>
6644d98d
WL
12#include <sys/time.h>
13#include <sys/resource.h>
52d3a481
WL
14#else
15typedef int pid_t; /* define for windows compatiblity */
85663f2c 16#endif
1f2e0df8
WL
17#include <map>
18#include <vector>
19#include <string>
20
21#include <boost/thread.hpp>
22#include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
712fd182
PW
23#include <boost/interprocess/sync/scoped_lock.hpp>
24#include <boost/interprocess/sync/interprocess_condition.hpp>
25#include <boost/interprocess/sync/lock_options.hpp>
1f2e0df8
WL
26#include <boost/date_time/gregorian/gregorian_types.hpp>
27#include <boost/date_time/posix_time/posix_time_types.hpp>
28
6644d98d
WL
29#include <openssl/sha.h>
30#include <openssl/ripemd.h>
31
67a42f92 32#include "netbase.h"
1f2e0df8 33
bde280b9
WL
34typedef long long int64;
35typedef unsigned long long uint64;
36
1f2e0df8
WL
37#define loop for (;;)
38#define BEGIN(a) ((char*)&(a))
39#define END(a) ((char*)&((&(a))[1]))
40#define UBEGIN(a) ((unsigned char*)&(a))
41#define UEND(a) ((unsigned char*)&((&(a))[1]))
42#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
43#define printf OutputDebugStringF
44
45#ifdef snprintf
46#undef snprintf
47#endif
48#define snprintf my_snprintf
49
50#ifndef PRI64d
bd846c0e 51#if defined(_MSC_VER) || defined(__MSVCRT__)
1f2e0df8
WL
52#define PRI64d "I64d"
53#define PRI64u "I64u"
54#define PRI64x "I64x"
55#else
56#define PRI64d "lld"
57#define PRI64u "llu"
58#define PRI64x "llx"
59#endif
60#endif
61
62// This is needed because the foreach macro can't get over the comma in pair<t1, t2>
9aef9bca 63#define PAIRTYPE(t1, t2) std::pair<t1, t2>
1f2e0df8 64
1f2e0df8
WL
65// Align by increasing pointer, must have extra space at end of buffer
66template <size_t nBytes, typename T>
67T* alignup(T* p)
68{
69 union
70 {
71 T* ptr;
72 size_t n;
73 } u;
74 u.ptr = p;
75 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
76 return u.ptr;
77}
78
6853e627 79#ifdef WIN32
1f2e0df8
WL
80#define MSG_NOSIGNAL 0
81#define MSG_DONTWAIT 0
26ce92b3 82
1f2e0df8
WL
83#ifndef S_IRUSR
84#define S_IRUSR 0400
85#define S_IWUSR 0200
86#endif
87#define unlink _unlink
1f2e0df8 88#else
1f2e0df8
WL
89#define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
90#define strlwr(psz) to_lower(psz)
91#define _strlwr(psz) to_lower(psz)
92#define MAX_PATH 1024
bde280b9 93inline void Sleep(int64 n)
1f2e0df8 94{
82a10c81
GM
95 /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
96 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
97 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
1f2e0df8
WL
98}
99#endif
100
1f2e0df8
WL
101
102
103
104
105
106
107
108
109extern std::map<std::string, std::string> mapArgs;
110extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
111extern bool fDebug;
112extern bool fPrintToConsole;
113extern bool fPrintToDebugger;
114extern char pszSetDataDir[MAX_PATH];
115extern bool fRequestShutdown;
116extern bool fShutdown;
117extern bool fDaemon;
118extern bool fServer;
119extern bool fCommandLine;
120extern std::string strMiscWarning;
121extern bool fTestNet;
122extern bool fNoListen;
123extern bool fLogTimestamps;
124
125void RandAddSeed();
126void RandAddSeedPerfmon();
127int OutputDebugStringF(const char* pszFormat, ...);
128int my_snprintf(char* buffer, size_t limit, const char* format, ...);
52d3a481
WL
129
130/* It is not allowed to use va_start with a pass-by-reference argument.
131 (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
132 macro to keep similar semantics.
133*/
134std::string real_strprintf(const std::string &format, int dummy, ...);
135#define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
136
137bool error(const char *format, ...);
1f2e0df8
WL
138void LogException(std::exception* pex, const char* pszThread);
139void PrintException(std::exception* pex, const char* pszThread);
140void PrintExceptionContinue(std::exception* pex, const char* pszThread);
141void ParseString(const std::string& str, char c, std::vector<std::string>& v);
bde280b9
WL
142std::string FormatMoney(int64 n, bool fPlus=false);
143bool ParseMoney(const std::string& str, int64& nRet);
144bool ParseMoney(const char* pszIn, int64& nRet);
1f2e0df8
WL
145std::vector<unsigned char> ParseHex(const char* psz);
146std::vector<unsigned char> ParseHex(const std::string& str);
922e8e29 147bool IsHex(const std::string& str);
4b603f1c
PW
148std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
149std::string DecodeBase64(const std::string& str);
150std::string EncodeBase64(const unsigned char* pch, size_t len);
151std::string EncodeBase64(const std::string& str);
3ae07355 152void ParseParameters(int argc, const char*const argv[]);
1f2e0df8
WL
153bool WildcardMatch(const char* psz, const char* mask);
154bool WildcardMatch(const std::string& str, const std::string& mask);
155int GetFilesize(FILE* file);
156void GetDataDir(char* pszDirRet);
157std::string GetConfigFile();
158std::string GetPidFile();
159void CreatePidFile(std::string pidFile, pid_t pid);
3f8cb2c5 160bool ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
6853e627 161#ifdef WIN32
822f2e3d 162std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
1f2e0df8
WL
163#endif
164std::string GetDefaultDataDir();
165std::string GetDataDir();
166void ShrinkDebugFile();
167int GetRandInt(int nMax);
bde280b9
WL
168uint64 GetRand(uint64 nMax);
169int64 GetTime();
170void SetMockTime(int64 nMockTimeIn);
171int64 GetAdjustedTime();
1f2e0df8 172std::string FormatFullVersion();
f8ded588 173std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
67a42f92 174void AddTimeData(const CNetAddr& ip, int64 nTime);
1f2e0df8
WL
175
176
177
178
179
180
181
182
183
184
185
712fd182
PW
186/** Wrapped boost mutex: supports recursive locking, but no waiting */
187typedef boost::interprocess::interprocess_recursive_mutex CCriticalSection;
1f2e0df8 188
712fd182
PW
189/** Wrapped boost mutex: supports waiting but not recursive locking */
190typedef boost::interprocess::interprocess_mutex CWaitableCriticalSection;
1f2e0df8 191
712fd182 192#ifdef DEBUG_LOCKORDER
f342dac1 193void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
712fd182
PW
194void LeaveCritical();
195#else
f342dac1 196void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {}
712fd182
PW
197void static inline LeaveCritical() {}
198#endif
865ed8a1 199
712fd182
PW
200/** Wrapper around boost::interprocess::scoped_lock */
201template<typename Mutex>
202class CMutexLock
203{
204private:
205 boost::interprocess::scoped_lock<Mutex> lock;
1f2e0df8 206public:
712fd182
PW
207
208 void Enter(const char* pszName, const char* pszFile, int nLine)
865ed8a1 209 {
712fd182
PW
210 if (!lock.owns())
211 {
212 EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()));
213#ifdef DEBUG_LOCKCONTENTION
214 if (!lock.try_lock())
215 {
216 printf("LOCKCONTENTION: %s\n", pszName);
217 printf("Locker: %s:%d\n", pszFile, nLine);
218 }
219#endif
220 lock.lock();
221 }
865ed8a1 222 }
3083cf10 223
712fd182 224 void Leave()
3083cf10 225 {
712fd182
PW
226 if (lock.owns())
227 {
228 lock.unlock();
229 LeaveCritical();
230 }
3083cf10
CG
231 }
232
712fd182 233 bool TryEnter(const char* pszName, const char* pszFile, int nLine)
865ed8a1 234 {
712fd182
PW
235 if (!lock.owns())
236 {
f342dac1 237 EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()), true);
712fd182
PW
238 lock.try_lock();
239 if (!lock.owns())
240 LeaveCritical();
241 }
242 return lock.owns();
865ed8a1 243 }
88bc5f94 244
712fd182
PW
245 CMutexLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) : lock(mutexIn, boost::interprocess::defer_lock)
246 {
247 if (fTry)
248 TryEnter(pszName, pszFile, nLine);
249 else
250 Enter(pszName, pszFile, nLine);
251 }
865ed8a1 252
712fd182 253 ~CMutexLock()
865ed8a1 254 {
712fd182
PW
255 if (lock.owns())
256 LeaveCritical();
865ed8a1 257 }
3083cf10 258
712fd182 259 operator bool()
3083cf10 260 {
712fd182 261 return lock.owns();
3083cf10
CG
262 }
263
712fd182 264 boost::interprocess::scoped_lock<Mutex> &GetLock()
865ed8a1 265 {
712fd182 266 return lock;
865ed8a1 267 }
1f2e0df8
WL
268};
269
712fd182
PW
270typedef CMutexLock<CCriticalSection> CCriticalBlock;
271typedef CMutexLock<CWaitableCriticalSection> CWaitableCriticalBlock;
272typedef boost::interprocess::interprocess_condition CConditionVariable;
273
274/** Wait for a given condition inside a WAITABLE_CRITICAL_BLOCK */
275#define WAIT(name,condition) \
276 do { while(!(condition)) { (name).wait(waitablecriticalblock.GetLock()); } } while(0)
277
278/** Notify waiting threads that a condition may hold now */
279#define NOTIFY(name) \
280 do { (name).notify_one(); } while(0)
281
282#define NOTIFY_ALL(name) \
283 do { (name).notify_all(); } while(0)
284
f8dcd5ca
PW
285#define LOCK(cs) CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__)
286#define LOCK2(cs1,cs2) CCriticalBlock criticalblock1(cs1, #cs1, __FILE__, __LINE__),criticalblock2(cs2, #cs2, __FILE__, __LINE__)
287#define TRY_LOCK(cs,name) CCriticalBlock name(cs, #cs, __FILE__, __LINE__, true)
288#define WAITABLE_LOCK(cs) CWaitableCriticalBlock waitablecriticalblock(cs, #cs, __FILE__, __LINE__)
712fd182
PW
289
290#define ENTER_CRITICAL_SECTION(cs) \
291 { \
292 EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \
293 (cs).lock(); \
294 }
295
296#define LEAVE_CRITICAL_SECTION(cs) \
297 { \
298 (cs).unlock(); \
299 LeaveCritical(); \
300 }
301
712fd182
PW
302
303// This is exactly like std::string, but with a custom allocator.
304// (secure_allocator<> is defined in serialize.h)
305typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
306
1f2e0df8
WL
307
308
309
310
bde280b9 311inline std::string i64tostr(int64 n)
1f2e0df8
WL
312{
313 return strprintf("%"PRI64d, n);
314}
315
316inline std::string itostr(int n)
317{
318 return strprintf("%d", n);
319}
320
bde280b9 321inline int64 atoi64(const char* psz)
1f2e0df8
WL
322{
323#ifdef _MSC_VER
324 return _atoi64(psz);
325#else
326 return strtoll(psz, NULL, 10);
327#endif
328}
329
bde280b9 330inline int64 atoi64(const std::string& str)
1f2e0df8
WL
331{
332#ifdef _MSC_VER
333 return _atoi64(str.c_str());
334#else
335 return strtoll(str.c_str(), NULL, 10);
336#endif
337}
338
339inline int atoi(const std::string& str)
340{
341 return atoi(str.c_str());
342}
343
344inline int roundint(double d)
345{
346 return (int)(d > 0 ? d + 0.5 : d - 0.5);
347}
348
bde280b9 349inline int64 roundint64(double d)
1f2e0df8 350{
bde280b9 351 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
1f2e0df8
WL
352}
353
bde280b9 354inline int64 abs64(int64 n)
1f2e0df8
WL
355{
356 return (n >= 0 ? n : -n);
357}
358
359template<typename T>
360std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
361{
362 if (itbegin == itend)
363 return "";
364 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
365 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
366 std::string str;
367 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
368 for (const unsigned char* p = pbegin; p != pend; p++)
369 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
370 return str;
371}
372
373inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
374{
375 return HexStr(vch.begin(), vch.end(), fSpaces);
376}
377
1f2e0df8
WL
378template<typename T>
379void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
380{
381 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
382}
383
384inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
385{
386 printf(pszFormat, HexStr(vch, fSpaces).c_str());
387}
388
bde280b9 389inline int64 GetPerformanceCounter()
1f2e0df8 390{
bde280b9 391 int64 nCounter = 0;
6853e627 392#ifdef WIN32
1f2e0df8
WL
393 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
394#else
395 timeval t;
396 gettimeofday(&t, NULL);
397 nCounter = t.tv_sec * 1000000 + t.tv_usec;
398#endif
399 return nCounter;
400}
401
bde280b9 402inline int64 GetTimeMillis()
1f2e0df8
WL
403{
404 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
405 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
406}
407
bde280b9 408inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
1f2e0df8
WL
409{
410 time_t n = nTime;
411 struct tm* ptmTime = gmtime(&n);
412 char pszTime[200];
413 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
414 return pszTime;
415}
416
417template<typename T>
418void skipspaces(T& it)
419{
420 while (isspace(*it))
421 ++it;
422}
423
424inline bool IsSwitchChar(char c)
425{
6853e627 426#ifdef WIN32
1f2e0df8
WL
427 return c == '-' || c == '/';
428#else
429 return c == '-';
430#endif
431}
432
3ae07355
GA
433/**
434 * Return string argument or default value
435 *
436 * @param strArg Argument to get (e.g. "-foo")
437 * @param default (e.g. "1")
438 * @return command-line argument or default value
439 */
440std::string GetArg(const std::string& strArg, const std::string& strDefault);
1f2e0df8 441
3ae07355
GA
442/**
443 * Return integer argument or default value
444 *
445 * @param strArg Argument to get (e.g. "-foo")
446 * @param default (e.g. 1)
447 * @return command-line argument (0 if invalid number) or default value
448 */
449int64 GetArg(const std::string& strArg, int64 nDefault);
1f2e0df8 450
3ae07355
GA
451/**
452 * Return boolean argument or default value
453 *
454 * @param strArg Argument to get (e.g. "-foo")
455 * @param default (true or false)
456 * @return command-line argument or default value
457 */
458bool GetBoolArg(const std::string& strArg, bool fDefault=false);
1f2e0df8 459
0fcf91ea
GA
460/**
461 * Set an argument if it doesn't already have a value
462 *
463 * @param strArg Argument to set (e.g. "-foo")
464 * @param strValue Value (e.g. "1")
465 * @return true if argument gets set, false if it already had a value
466 */
467bool SoftSetArg(const std::string& strArg, const std::string& strValue);
468
469/**
470 * Set a boolean argument if it doesn't already have a value
471 *
472 * @param strArg Argument to set (e.g. "-foo")
473 * @param fValue Value (e.g. false)
474 * @return true if argument gets set, false if it already had a value
475 */
7bf8b7c2 476bool SoftSetBoolArg(const std::string& strArg, bool fValue);
1f2e0df8
WL
477
478
479
480
481
482
483
484
485
1f2e0df8
WL
486// Randomize the stack to help protect against buffer overrun exploits
487#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
488 { \
489 static char nLoops; \
490 if (nLoops <= 0) \
491 nLoops = GetRand(20) + 1; \
492 if (nLoops-- > 1) \
493 { \
494 ThreadFn; \
495 return; \
496 } \
497 }
498
1f2e0df8
WL
499
500template<typename T1>
501inline uint256 Hash(const T1 pbegin, const T1 pend)
502{
503 static unsigned char pblank[1];
504 uint256 hash1;
505 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
506 uint256 hash2;
507 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
508 return hash2;
509}
510
511template<typename T1, typename T2>
512inline uint256 Hash(const T1 p1begin, const T1 p1end,
513 const T2 p2begin, const T2 p2end)
514{
515 static unsigned char pblank[1];
516 uint256 hash1;
517 SHA256_CTX ctx;
518 SHA256_Init(&ctx);
519 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
520 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
521 SHA256_Final((unsigned char*)&hash1, &ctx);
522 uint256 hash2;
523 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
524 return hash2;
525}
526
527template<typename T1, typename T2, typename T3>
528inline uint256 Hash(const T1 p1begin, const T1 p1end,
529 const T2 p2begin, const T2 p2end,
530 const T3 p3begin, const T3 p3end)
531{
532 static unsigned char pblank[1];
533 uint256 hash1;
534 SHA256_CTX ctx;
535 SHA256_Init(&ctx);
536 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
537 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
538 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
539 SHA256_Final((unsigned char*)&hash1, &ctx);
540 uint256 hash2;
541 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
542 return hash2;
543}
544
545template<typename T>
f8ded588 546uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
1f2e0df8
WL
547{
548 // Most of the time is spent allocating and deallocating CDataStream's
549 // buffer. If this ever needs to be optimized further, make a CStaticStream
550 // class with its buffer on the stack.
551 CDataStream ss(nType, nVersion);
552 ss.reserve(10000);
553 ss << obj;
554 return Hash(ss.begin(), ss.end());
555}
556
6644d98d 557inline uint160 Hash160(const std::vector<unsigned char>& vch)
1f2e0df8
WL
558{
559 uint256 hash1;
560 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
561 uint160 hash2;
562 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
563 return hash2;
564}
565
566
6b8de05d
PW
567/** Median filter over a stream of values.
568 * Returns the median of the last N numbers
569 */
a8b95ce6
WL
570template <typename T> class CMedianFilter
571{
572private:
573 std::vector<T> vValues;
574 std::vector<T> vSorted;
575 int nSize;
576public:
577 CMedianFilter(int size, T initial_value):
578 nSize(size)
579 {
580 vValues.reserve(size);
581 vValues.push_back(initial_value);
582 vSorted = vValues;
583 }
584
585 void input(T value)
586 {
587 if(vValues.size() == nSize)
588 {
589 vValues.erase(vValues.begin());
590 }
591 vValues.push_back(value);
592
593 vSorted.resize(vValues.size());
594 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
595 std::sort(vSorted.begin(), vSorted.end());
596 }
597
598 T median() const
599 {
600 int size = vSorted.size();
20091df7 601 assert(size>0);
a8b95ce6
WL
602 if(size & 1) // Odd number of elements
603 {
604 return vSorted[size/2];
605 }
606 else // Even number of elements
607 {
608 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
609 }
610 }
1c4aab92
MH
611
612 int size() const
613 {
614 return vValues.size();
615 }
616
617 std::vector<T> sorted () const
618 {
619 return vSorted;
620 }
a8b95ce6
WL
621};
622
1f2e0df8
WL
623
624
625
626
627
628
629
630
631
632// Note: It turns out we might have been able to use boost::thread
633// by using TerminateThread(boost::thread.native_handle(), 0);
6853e627 634#ifdef WIN32
1f2e0df8
WL
635typedef HANDLE pthread_t;
636
637inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
638{
639 DWORD nUnused = 0;
640 HANDLE hthread =
641 CreateThread(
642 NULL, // default security
643 0, // inherit stack size from parent
644 (LPTHREAD_START_ROUTINE)pfn, // function pointer
645 parg, // argument
646 0, // creation option, start immediately
647 &nUnused); // thread identifier
648 if (hthread == NULL)
649 {
650 printf("Error: CreateThread() returned %d\n", GetLastError());
651 return (pthread_t)0;
652 }
653 if (!fWantHandle)
654 {
655 CloseHandle(hthread);
656 return (pthread_t)-1;
657 }
658 return hthread;
659}
660
661inline void SetThreadPriority(int nPriority)
662{
663 SetThreadPriority(GetCurrentThread(), nPriority);
664}
665#else
666inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
667{
668 pthread_t hthread = 0;
669 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
670 if (ret != 0)
671 {
672 printf("Error: pthread_create() returned %d\n", ret);
673 return (pthread_t)0;
674 }
675 if (!fWantHandle)
67ed7d9d
J
676 {
677 pthread_detach(hthread);
1f2e0df8 678 return (pthread_t)-1;
67ed7d9d 679 }
1f2e0df8
WL
680 return hthread;
681}
682
683#define THREAD_PRIORITY_LOWEST PRIO_MAX
684#define THREAD_PRIORITY_BELOW_NORMAL 2
685#define THREAD_PRIORITY_NORMAL 0
686#define THREAD_PRIORITY_ABOVE_NORMAL 0
687
688inline void SetThreadPriority(int nPriority)
689{
690 // It's unclear if it's even possible to change thread priorities on Linux,
691 // but we really and truly need it for the generation threads.
692#ifdef PRIO_THREAD
693 setpriority(PRIO_THREAD, 0, nPriority);
694#else
695 setpriority(PRIO_PROCESS, 0, nPriority);
696#endif
697}
698
df401814 699inline void ExitThread(size_t nExitCode)
1f2e0df8
WL
700{
701 pthread_exit((void*)nExitCode);
702}
703#endif
704
705
706
707
708
709inline bool AffinityBugWorkaround(void(*pfn)(void*))
710{
6853e627 711#ifdef WIN32
1f2e0df8 712 // Sometimes after a few hours affinity gets stuck on one processor
b95e6376
VL
713 DWORD_PTR dwProcessAffinityMask = -1;
714 DWORD_PTR dwSystemAffinityMask = -1;
1f2e0df8
WL
715 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
716 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
717 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
718 if (dwPrev2 != dwProcessAffinityMask)
719 {
720 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
721 if (!CreateThread(pfn, NULL))
722 printf("Error: CreateThread() failed\n");
723 return true;
724 }
725#endif
726 return false;
727}
728
6ccff2cb
NS
729inline uint32_t ByteReverse(uint32_t value)
730{
b985efaa
LR
731 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
732 return (value<<16) | (value>>16);
6ccff2cb
NS
733}
734
1f2e0df8 735#endif
67a42f92 736
This page took 0.150209 seconds and 4 git commands to generate.