Merge branch '0.4.x' into 0.5.0.x
[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 #endif
15 #include <map>
16 #include <vector>
17 #include <string>
18
19 #include <boost/thread.hpp>
20 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
21 #include <boost/date_time/gregorian/gregorian_types.hpp>
22 #include <boost/date_time/posix_time/posix_time_types.hpp>
23
24 #include <openssl/sha.h>
25 #include <openssl/ripemd.h>
26
27
28 #if defined(_MSC_VER) || defined(__BORLANDC__)
29 typedef __int64  int64;
30 typedef unsigned __int64  uint64;
31 #else
32 typedef long long  int64;
33 typedef unsigned long long  uint64;
34 #endif
35 #if defined(_MSC_VER) && _MSC_VER < 1300
36 #define for  if (false) ; else for
37 #endif
38 #ifndef _MSC_VER
39 #define __forceinline  inline
40 #endif
41
42 #define loop                for (;;)
43 #define BEGIN(a)            ((char*)&(a))
44 #define END(a)              ((char*)&((&(a))[1]))
45 #define UBEGIN(a)           ((unsigned char*)&(a))
46 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
47 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
48 #define printf              OutputDebugStringF
49
50 #ifdef snprintf
51 #undef snprintf
52 #endif
53 #define snprintf my_snprintf
54
55 #ifndef PRI64d
56 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
57 #define PRI64d  "I64d"
58 #define PRI64u  "I64u"
59 #define PRI64x  "I64x"
60 #else
61 #define PRI64d  "lld"
62 #define PRI64u  "llu"
63 #define PRI64x  "llx"
64 #endif
65 #endif
66
67 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
68 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
69
70 // Align by increasing pointer, must have extra space at end of buffer
71 template <size_t nBytes, typename T>
72 T* alignup(T* p)
73 {
74     union
75     {
76         T* ptr;
77         size_t n;
78     } u;
79     u.ptr = p;
80     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
81     return u.ptr;
82 }
83
84 #ifdef WIN32
85 #define MSG_NOSIGNAL        0
86 #define MSG_DONTWAIT        0
87 #ifndef UINT64_MAX
88 #define UINT64_MAX          _UI64_MAX
89 #define INT64_MAX           _I64_MAX
90 #define INT64_MIN           _I64_MIN
91 #endif
92 #ifndef S_IRUSR
93 #define S_IRUSR             0400
94 #define S_IWUSR             0200
95 #endif
96 #define unlink              _unlink
97 typedef int socklen_t;
98 #else
99 #define WSAGetLastError()   errno
100 #define WSAEINVAL           EINVAL
101 #define WSAEALREADY         EALREADY
102 #define WSAEWOULDBLOCK      EWOULDBLOCK
103 #define WSAEMSGSIZE         EMSGSIZE
104 #define WSAEINTR            EINTR
105 #define WSAEINPROGRESS      EINPROGRESS
106 #define WSAEADDRINUSE       EADDRINUSE
107 #define WSAENOTSOCK         EBADF
108 #define INVALID_SOCKET      (SOCKET)(~0)
109 #define SOCKET_ERROR        -1
110 typedef u_int SOCKET;
111 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
112 #define strlwr(psz)         to_lower(psz)
113 #define _strlwr(psz)        to_lower(psz)
114 #define MAX_PATH            1024
115 #define Beep(n1,n2)         (0)
116 inline void Sleep(int64 n)
117 {
118     /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
119       So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
120     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
121 }
122 #endif
123
124 inline int myclosesocket(SOCKET& hSocket)
125 {
126     if (hSocket == INVALID_SOCKET)
127         return WSAENOTSOCK;
128 #ifdef WIN32
129     int ret = closesocket(hSocket);
130 #else
131     int ret = close(hSocket);
132 #endif
133     hSocket = INVALID_SOCKET;
134     return ret;
135 }
136 #define closesocket(s)      myclosesocket(s)
137 #if !defined(QT_GUI)
138 inline const char* _(const char* psz)
139 {
140     return psz;
141 }
142 #endif
143
144
145
146
147
148
149
150
151
152 extern std::map<std::string, std::string> mapArgs;
153 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
154 extern bool fDebug;
155 extern bool fPrintToConsole;
156 extern bool fPrintToDebugger;
157 extern char pszSetDataDir[MAX_PATH];
158 extern bool fRequestShutdown;
159 extern bool fShutdown;
160 extern bool fDaemon;
161 extern bool fServer;
162 extern bool fCommandLine;
163 extern std::string strMiscWarning;
164 extern bool fTestNet;
165 extern bool fNoListen;
166 extern bool fLogTimestamps;
167
168 void RandAddSeed();
169 void RandAddSeedPerfmon();
170 int OutputDebugStringF(const char* pszFormat, ...);
171 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
172 std::string strprintf(const std::string &format, ...);
173 bool error(const std::string &format, ...);
174 void LogException(std::exception* pex, const char* pszThread);
175 void PrintException(std::exception* pex, const char* pszThread);
176 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
177 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
178 std::string FormatMoney(int64 n, bool fPlus=false);
179 bool ParseMoney(const std::string& str, int64& nRet);
180 bool ParseMoney(const char* pszIn, int64& nRet);
181 std::vector<unsigned char> ParseHex(const char* psz);
182 std::vector<unsigned char> ParseHex(const std::string& str);
183 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
184 std::string DecodeBase64(const std::string& str);
185 std::string EncodeBase64(const unsigned char* pch, size_t len);
186 std::string EncodeBase64(const std::string& str);
187 void ParseParameters(int argc, char* argv[]);
188 const char* wxGetTranslation(const char* psz);
189 bool WildcardMatch(const char* psz, const char* mask);
190 bool WildcardMatch(const std::string& str, const std::string& mask);
191 int GetFilesize(FILE* file);
192 void GetDataDir(char* pszDirRet);
193 std::string GetConfigFile();
194 std::string GetPidFile();
195 void CreatePidFile(std::string pidFile, pid_t pid);
196 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
197 #ifdef WIN32
198 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
199 #endif
200 std::string GetDefaultDataDir();
201 std::string GetDataDir();
202 void ShrinkDebugFile();
203 int GetRandInt(int nMax);
204 uint64 GetRand(uint64 nMax);
205 int64 GetTime();
206 void SetMockTime(int64 nMockTimeIn);
207 int64 GetAdjustedTime();
208 void AddTimeData(unsigned int ip, int64 nTime);
209 std::string FormatFullVersion();
210
211
212
213
214
215
216
217
218
219
220
221
222
223 // Wrapper to automatically initialize mutex
224 class CCriticalSection
225 {
226 protected:
227     boost::interprocess::interprocess_recursive_mutex mutex;
228 public:
229     explicit CCriticalSection() { }
230     ~CCriticalSection() { }
231     void Enter(const char* pszName, const char* pszFile, int nLine);
232     void Leave();
233     bool TryEnter(const char* pszName, const char* pszFile, int nLine);
234 };
235
236 // Automatically leave critical section when leaving block, needed for exception safety
237 class CCriticalBlock
238 {
239 protected:
240     CCriticalSection* pcs;
241
242 public:
243     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
244     {
245         pcs = &csIn;
246         pcs->Enter(pszName, pszFile, nLine);
247     }
248     ~CCriticalBlock()
249     {
250         pcs->Leave();
251     }
252 };
253
254 // WARNING: This will catch continue and break!
255 // break is caught with an assertion, but there's no way to detect continue.
256 // I'd rather be careful than suffer the other more error prone syntax.
257 // The compiler will optimise away all this loop junk.
258 #define CRITICAL_BLOCK(cs)     \
259     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
260         for (CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce; fcriticalblockonce=false)
261
262 #define ENTER_CRITICAL_SECTION(cs) \
263     (cs).Enter(#cs, __FILE__, __LINE__)
264
265 #define LEAVE_CRITICAL_SECTION(cs) \
266     (cs).Leave()
267
268 class CTryCriticalBlock
269 {
270 protected:
271     CCriticalSection* pcs;
272
273 public:
274     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
275     {
276         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
277     }
278     ~CTryCriticalBlock()
279     {
280         if (pcs)
281         {
282             pcs->Leave();
283         }
284     }
285     bool Entered() { return pcs != NULL; }
286 };
287
288 #define TRY_CRITICAL_BLOCK(cs)     \
289     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
290         for (CTryCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()); fcriticalblockonce=false)
291
292
293
294
295
296
297 // This is exactly like std::string, but with a custom allocator.
298 // (secure_allocator<> is defined in serialize.h)
299 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
300
301
302
303
304
305 inline std::string i64tostr(int64 n)
306 {
307     return strprintf("%"PRI64d, n);
308 }
309
310 inline std::string itostr(int n)
311 {
312     return strprintf("%d", n);
313 }
314
315 inline int64 atoi64(const char* psz)
316 {
317 #ifdef _MSC_VER
318     return _atoi64(psz);
319 #else
320     return strtoll(psz, NULL, 10);
321 #endif
322 }
323
324 inline int64 atoi64(const std::string& str)
325 {
326 #ifdef _MSC_VER
327     return _atoi64(str.c_str());
328 #else
329     return strtoll(str.c_str(), NULL, 10);
330 #endif
331 }
332
333 inline int atoi(const std::string& str)
334 {
335     return atoi(str.c_str());
336 }
337
338 inline int roundint(double d)
339 {
340     return (int)(d > 0 ? d + 0.5 : d - 0.5);
341 }
342
343 inline int64 roundint64(double d)
344 {
345     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
346 }
347
348 inline int64 abs64(int64 n)
349 {
350     return (n >= 0 ? n : -n);
351 }
352
353 template<typename T>
354 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
355 {
356     if (itbegin == itend)
357         return "";
358     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
359     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
360     std::string str;
361     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
362     for (const unsigned char* p = pbegin; p != pend; p++)
363         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
364     return str;
365 }
366
367 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
368 {
369     return HexStr(vch.begin(), vch.end(), fSpaces);
370 }
371
372 template<typename T>
373 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
374 {
375     if (itbegin == itend)
376         return "";
377     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
378     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
379     std::string str = (f0x ? "0x" : "");
380     str.reserve(str.size() + (pend-pbegin) * 2);
381     for (const unsigned char* p = pend-1; p >= pbegin; p--)
382         str += strprintf("%02x", *p);
383     return str;
384 }
385
386 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
387 {
388     return HexNumStr(vch.begin(), vch.end(), f0x);
389 }
390
391 template<typename T>
392 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
393 {
394     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
395 }
396
397 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
398 {
399     printf(pszFormat, HexStr(vch, fSpaces).c_str());
400 }
401
402 inline int64 GetPerformanceCounter()
403 {
404     int64 nCounter = 0;
405 #ifdef WIN32
406     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
407 #else
408     timeval t;
409     gettimeofday(&t, NULL);
410     nCounter = t.tv_sec * 1000000 + t.tv_usec;
411 #endif
412     return nCounter;
413 }
414
415 inline int64 GetTimeMillis()
416 {
417     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
418             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
419 }
420
421 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
422 {
423     time_t n = nTime;
424     struct tm* ptmTime = gmtime(&n);
425     char pszTime[200];
426     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
427     return pszTime;
428 }
429
430 template<typename T>
431 void skipspaces(T& it)
432 {
433     while (isspace(*it))
434         ++it;
435 }
436
437 inline bool IsSwitchChar(char c)
438 {
439 #ifdef WIN32
440     return c == '-' || c == '/';
441 #else
442     return c == '-';
443 #endif
444 }
445
446 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
447 {
448     if (mapArgs.count(strArg))
449         return mapArgs[strArg];
450     return strDefault;
451 }
452
453 inline int64 GetArg(const std::string& strArg, int64 nDefault)
454 {
455     if (mapArgs.count(strArg))
456         return atoi64(mapArgs[strArg]);
457     return nDefault;
458 }
459
460 inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
461 {
462     if (mapArgs.count(strArg))
463     {
464         if (mapArgs[strArg].empty())
465             return true;
466         return (atoi(mapArgs[strArg]) != 0);
467     }
468     return fDefault;
469 }
470
471 /**
472  * Set an argument if it doesn't already have a value
473  *
474  * @param strArg Argument to set (e.g. "-foo")
475  * @param strValue Value (e.g. "1")
476  * @return true if argument gets set, false if it already had a value
477  */
478 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
479
480 /**
481  * Set a boolean argument if it doesn't already have a value
482  *
483  * @param strArg Argument to set (e.g. "-foo")
484  * @param fValue Value (e.g. false)
485  * @return true if argument gets set, false if it already had a value
486  */
487 bool SoftSetArg(const std::string& strArg, bool fValue);
488
489
490
491
492
493
494
495
496
497 inline void heapchk()
498 {
499 #ifdef WIN32
500     /// for debugging
501     //if (_heapchk() != _HEAPOK)
502     //    DebugBreak();
503 #endif
504 }
505
506 // Randomize the stack to help protect against buffer overrun exploits
507 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
508     {                                           \
509         static char nLoops;                     \
510         if (nLoops <= 0)                        \
511             nLoops = GetRand(20) + 1;           \
512         if (nLoops-- > 1)                       \
513         {                                       \
514             ThreadFn;                           \
515             return;                             \
516         }                                       \
517     }
518
519 #define CATCH_PRINT_EXCEPTION(pszFn)     \
520     catch (std::exception& e) {          \
521         PrintException(&e, (pszFn));     \
522     } catch (...) {                      \
523         PrintException(NULL, (pszFn));   \
524     }
525
526
527
528
529
530
531
532
533
534
535 template<typename T1>
536 inline uint256 Hash(const T1 pbegin, const T1 pend)
537 {
538     static unsigned char pblank[1];
539     uint256 hash1;
540     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
541     uint256 hash2;
542     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
543     return hash2;
544 }
545
546 template<typename T1, typename T2>
547 inline uint256 Hash(const T1 p1begin, const T1 p1end,
548                     const T2 p2begin, const T2 p2end)
549 {
550     static unsigned char pblank[1];
551     uint256 hash1;
552     SHA256_CTX ctx;
553     SHA256_Init(&ctx);
554     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
555     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
556     SHA256_Final((unsigned char*)&hash1, &ctx);
557     uint256 hash2;
558     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
559     return hash2;
560 }
561
562 template<typename T1, typename T2, typename T3>
563 inline uint256 Hash(const T1 p1begin, const T1 p1end,
564                     const T2 p2begin, const T2 p2end,
565                     const T3 p3begin, const T3 p3end)
566 {
567     static unsigned char pblank[1];
568     uint256 hash1;
569     SHA256_CTX ctx;
570     SHA256_Init(&ctx);
571     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
572     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
573     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
574     SHA256_Final((unsigned char*)&hash1, &ctx);
575     uint256 hash2;
576     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
577     return hash2;
578 }
579
580 template<typename T>
581 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
582 {
583     // Most of the time is spent allocating and deallocating CDataStream's
584     // buffer.  If this ever needs to be optimized further, make a CStaticStream
585     // class with its buffer on the stack.
586     CDataStream ss(nType, nVersion);
587     ss.reserve(10000);
588     ss << obj;
589     return Hash(ss.begin(), ss.end());
590 }
591
592 inline uint160 Hash160(const std::vector<unsigned char>& vch)
593 {
594     uint256 hash1;
595     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
596     uint160 hash2;
597     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
598     return hash2;
599 }
600
601
602 // Median filter over a stream of values
603 // Returns the median of the last N numbers
604 template <typename T> class CMedianFilter
605 {
606 private:
607     std::vector<T> vValues;
608     std::vector<T> vSorted;
609     int nSize;
610 public:
611     CMedianFilter(int size, T initial_value):
612         nSize(size)
613     {
614         vValues.reserve(size);
615         vValues.push_back(initial_value);
616         vSorted = vValues;
617     }
618     
619     void input(T value)
620     {
621         if(vValues.size() == nSize)
622         {
623             vValues.erase(vValues.begin());
624         }
625         vValues.push_back(value);
626
627         vSorted.resize(vValues.size());
628         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
629         std::sort(vSorted.begin(), vSorted.end());
630     }
631
632     T median() const
633     {
634         int size = vSorted.size();
635         assert(size>0);
636         if(size & 1) // Odd number of elements
637         {
638             return vSorted[size/2];
639         }
640         else // Even number of elements
641         {
642             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
643         }
644     }
645 };
646
647
648
649
650
651
652
653
654
655
656 // Note: It turns out we might have been able to use boost::thread
657 // by using TerminateThread(boost::thread.native_handle(), 0);
658 #ifdef WIN32
659 typedef HANDLE pthread_t;
660
661 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
662 {
663     DWORD nUnused = 0;
664     HANDLE hthread =
665         CreateThread(
666             NULL,                        // default security
667             0,                           // inherit stack size from parent
668             (LPTHREAD_START_ROUTINE)pfn, // function pointer
669             parg,                        // argument
670             0,                           // creation option, start immediately
671             &nUnused);                   // thread identifier
672     if (hthread == NULL)
673     {
674         printf("Error: CreateThread() returned %d\n", GetLastError());
675         return (pthread_t)0;
676     }
677     if (!fWantHandle)
678     {
679         CloseHandle(hthread);
680         return (pthread_t)-1;
681     }
682     return hthread;
683 }
684
685 inline void SetThreadPriority(int nPriority)
686 {
687     SetThreadPriority(GetCurrentThread(), nPriority);
688 }
689 #else
690 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
691 {
692     pthread_t hthread = 0;
693     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
694     if (ret != 0)
695     {
696         printf("Error: pthread_create() returned %d\n", ret);
697         return (pthread_t)0;
698     }
699     if (!fWantHandle)
700     {
701         pthread_detach(hthread);
702         return (pthread_t)-1;
703     }
704     return hthread;
705 }
706
707 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
708 #define THREAD_PRIORITY_BELOW_NORMAL    2
709 #define THREAD_PRIORITY_NORMAL          0
710 #define THREAD_PRIORITY_ABOVE_NORMAL    0
711
712 inline void SetThreadPriority(int nPriority)
713 {
714     // It's unclear if it's even possible to change thread priorities on Linux,
715     // but we really and truly need it for the generation threads.
716 #ifdef PRIO_THREAD
717     setpriority(PRIO_THREAD, 0, nPriority);
718 #else
719     setpriority(PRIO_PROCESS, 0, nPriority);
720 #endif
721 }
722
723 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
724 {
725     return (pthread_cancel(hthread) == 0);
726 }
727
728 inline void ExitThread(size_t nExitCode)
729 {
730     pthread_exit((void*)nExitCode);
731 }
732 #endif
733
734
735
736
737
738 inline bool AffinityBugWorkaround(void(*pfn)(void*))
739 {
740 #ifdef WIN32
741     // Sometimes after a few hours affinity gets stuck on one processor
742     DWORD_PTR dwProcessAffinityMask = -1;
743     DWORD_PTR dwSystemAffinityMask = -1;
744     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
745     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
746     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
747     if (dwPrev2 != dwProcessAffinityMask)
748     {
749         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
750         if (!CreateThread(pfn, NULL))
751             printf("Error: CreateThread() failed\n");
752         return true;
753     }
754 #endif
755     return false;
756 }
757
758 inline uint32_t ByteReverse(uint32_t value)
759 {
760     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
761     return (value<<16) | (value>>16);
762 }
763
764 #endif