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