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