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