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