CMSDK  2.0.1
Utils.h
1 #if !defined(_UTILS_H_)
2 #define _UTILS_H_
3 
4 #include <math.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <time.h>
8 #include <fcntl.h> /* For O_* constants */
9 #include <sys/stat.h> /* For mode constants */
10 #include <sys/types.h>
11 #include <stdarg.h>
12 #include <iomanip>
13 
14 #include "Types.h"
15 #include "Base64.h"
16 
17 #ifdef WINDOWS
18  #include <io.h>
19 // #include <windows.h>
20  #include <winsock2.h>
21  #include <iphlpapi.h>
22  #include <iptypes.h>
23  #include "Psapi.h"
24  #include "direntwin.h"
25  #include <process.h>
26  // #include <Dbghelp.h> // needed for program trace only, link with Dbghelp.lib
27 #else
28  #include <semaphore.h>
29  #include <dlfcn.h>
30  #include <errno.h>
31  #include <sys/utsname.h>
32  #include <sys/time.h>
33  #include <pthread.h>
34  #include <signal.h>
35  #include <sys/prctl.h>
36  #include <unistd.h>
37  #include <time.h>
38  #include <sys/mman.h>
39  #include <sys/syscall.h>
40  #include <sys/sysinfo.h>
41  #include <sys/socket.h>
42  #include <netdb.h>
43  #include <net/if.h>
44  #include <sys/ioctl.h>
45  #include <dirent.h>
46  #include <netinet/tcp.h>
47  #include <sys/wait.h>
48  #include <execinfo.h>
49  #include <sys/resource.h>
50 // #include <curses.h>
51 #endif
52 
53 #define WINSHMEMSPACE "Local"
54 //#define WINSHMEMSPACE "Global"
55 
56 #define MAXKEYNAMELEN 256
57 #define MAXVALUENAMELEN 1024
58 #define MAXCONTENTLEN 4196
59 #define MAXCOMMANDLINELEN 1024
60 #define MAXFILENAMELEN 256
61 #define MAXSHMEMNAMELEN 1024
62 #define MAXSCRIPTLEN 10*1024
63 
64 #define THREAD_NONE 0
65 #define THREAD_TERMINATED 1
66 #define THREAD_INIT 2
67 #define THREAD_RUNNING 3
68 #define THREAD_PAUSED 4
69 #define THREAD_INTERRUPTED 5
70 
71 #define THREAD_STATS_OFF 0
72 #define THREAD_STATS_AUTO 1
73 #define THREAD_STATS_ADHOC 2
74 
75 #ifdef WINDOWS
76 // #define Mutex HANDLE
77 // #define NMutex HANDLE
78 // #define Semaphore HANDLE
79  #define ThreadHandle HANDLE
80 // #define THREAD_FUNCTION static DWORD WINAPI
81 // #define THREAD_FUNCTION DWORD WINAPI
82  #define THREAD_RET DWORD
83  typedef LPTHREAD_START_ROUTINE THREAD_FUNCTION;
84  #define THREAD_FUNCTION_CALL WINAPI
85  #define THREAD_ARG LPVOID
86  #define thread_ret_val(ret) return ret;
87  #define DllExport __declspec(dllexport)
88  #define MUTEX_INVALID NULL
89  #define SOCKETWOULDBLOCK WSAEWOULDBLOCK
90  #define SOCKETTRYAGAIN WSAEWOULDBLOCK
91  #define abs64 _abs64
92 #else
93 // #define Mutex pthread_mutex_t
94 // #define NMutex sem_t *
95 // #define Semaphore sem_t*
96  #define ThreadHandle pthread_t
97 // #define THREAD_FUNCTION void*(*)(void*)
98  #define THREAD_RET void *
99  typedef THREAD_RET (*THREAD_FUNCTION)(void *);
100  #define THREAD_FUNCTION_CALL
101  #define THREAD_ARG void*
102  #define thread_ret_val(ret) pthread_exit((THREAD_RET)(intptr_t)ret);
103  #define stricmp strcasecmp
104  #define MUTEX_INVALID 0
105  #define SOCKET int
106  typedef struct sockaddr SOCKADDR;
107  #define SOCKET_ERROR -1
108  #define INVALID_SOCKET -1
109  #define closesocket(X) close(X)
110  #define SOCKETWOULDBLOCK EINPROGRESS
111  #define SOCKETTRYAGAIN EAGAIN
112  #define abs64 llabs
113  #define MUTEXMEMSIZE 64
114  #define EVENTMEMSIZE 256
115  #define _strcmpi strcasecmp
116  #define _strnicmp strnicmp
117  #define DllExport
118 #endif
119 
120 #ifndef SD_BOTH
121  #define SD_BOTH 2
122 #endif
123 
124 #define OSCPU_UNKNOWN 0
125 #define OSCPU_X86 1
126 #define OSCPU_AMD64 2
127 #define OSCPU_IA64 3
128 
129 #define ERROR64 0xFFFFFFFFFFFFFFFFL
130 #define ERROR32 0xFFFFFFFF
131 #define ERROR16 0xFFFF
132 #define ERROR8 0xFF
133 
134 #include "PsyTime.h"
135 
136 namespace cmlabs {
137 
139 // INIT/EXIT //
141 
143 public:
144  CleanShutdown();
145  ~CleanShutdown();
146 };
147 
148 bool ClearUtilsMaps();
149 
151 // Logging //
153 
154 #define LOG_NOTOPIC 0
155 #define LOG_SYSTEM 1
156 #define LOG_NETWORK 2
157 #define LOG_MEMORY 3
158 #define LOG_PROCESS 4
159 #define LOG_TOPIC5 5
160 #define LOG_TOPIC6 6
161 #define LOG_TOPIC7 7
162 #define LOG_TOPIC8 8
163 #define LOG_TOPIC9 9
164 #define LOG_TOPIC10 10
165 #define LOG_TOPIC11 11
166 #define LOG_MAXCOUNT 12
167 
168 #define LOGPRINT 1
169 #define LOGDEBUG 2
170 
171 std::string GetDataTypeName(uint32 datatype);
172 uint32 GetDataTypeID(const char* typeName);
173 
174 // #define GETLOGTEXT(l) (char*)l+sizeof(LogEntry)
175 struct LogEntry {
176  uint32 size; //
177  uint32 cid; // LOGENTRYID
178  uint64 time; //
179  uint32 source; //
180  uint8 subject; //
181  uint8 level; //
182  uint8 type; //
183  const char* getText(uint32& len);
184  bool setText(char* text, uint32 len);
185  std::string toJSON();
186  std::string toXML();
187 };
188 
189 class LogReceiver {
190 public:
191  LogReceiver() {}
192 // virtual bool logPrint(uint32 source, uint8 subject, uint8 level, std::string text, uint64 time) = 0;
193 // virtual bool logDebug(uint32 source, uint8 subject, uint8 level, std::string text, uint64 time) = 0;
194  virtual bool logEntry(LogEntry* entry) = 0;
195 };
196 
197 class LogSystem {
198 public:
199  LogSystem();
200  ~LogSystem();
201 
202  static LogSystem* LogSingleton;
203  static bool SetLogReceiver(LogReceiver* rec);
204 
205  static bool SetLogFileOutput(const char* logfile, bool printOut = true);
206  static bool SetLogLevelDebug(uint8 level);
207  static bool SetLogLevelDebug(uint8 subject, uint8 level);
208  static bool SetLogLevelVerbose(uint8 level);
209  static bool SetLogLevelVerbose(uint8 subject, uint8 level);
210 
211  static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... );
212  static bool LogSystemDebug(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... );
213 
214  uint8 logLevelVerbose[LOG_MAXCOUNT];
215  uint8 logLevelDebug[LOG_MAXCOUNT];
216  LogReceiver* logReceiverObj;
217  char* logfile;
218  bool printToStdOut;
219 };
220 
221 #define LogPrint LogSystem::LogSystemPrint
222 #define LogDebug LogSystem::LogSystemDebug
223 
224 namespace utils {
225 
231 bool UtilsTest();
232 
233 // bool GetSystemName(uint32 id, const char* title, char* name, uint32 size);
234 
235 
236 
238 // Mutexes //
240 
241 #ifdef WINDOWS
242  #define SharedMemoryFileHandleMapType std::map<char*, HANDLE>
243 #else
244  #define SharedMemoryFileHandleMapType std::map<void*, std::string>
245 #endif
246 static SharedMemoryFileHandleMapType* SharedMemoryFileHandleMap = NULL;
247 
248 static uint16 SharedSystemInstance = 0;
249 
250 bool SetSharedSystemInstance(uint32 inst);
251 uint32 GetSharedSystemInstance();
252 
253 typedef bool (* DrumBeatFunc)(uint32 id, uint32 count);
254 
255 struct DrumBeatInfo {
256  uint32 id;
257  uint64 createdTime;
258  uint64 started;
259  uint32 interval;
260  DrumBeatFunc func;
261  uint32 count;
262  #ifdef WINDOWS
263  HANDLE handle;
264  #else
265  timer_t handle;
266  #endif
267 };
268 
269 static std::map<uint32, DrumBeatInfo>* DrumBeatMap = NULL;
270 
271 bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart = false);
272 bool StartDrumBeat(uint32 id);
273 bool StopDrumBeat(uint32 id);
274 bool EndDrumBeat(uint32 id);
275 
276 class Mutex {
277 public:
278  Mutex();
279  Mutex(const char* name, bool force = false);
280  ~Mutex();
281  bool enter();
282  bool enter(uint32 timeout, const char* errorMsg = NULL);
283  bool leave();
284 // bool destroy();
285 protected:
286  char *name;
287  bool created;
288  uint32 osid;
289  uint32 total;
290  uint32 count;
291  #ifdef WINDOWS
292  HANDLE mutex;
293  #else
294  //sem_t* semaphore;
295  pthread_mutex_t* mutex;
296  #endif
297 };
298 
299 class Semaphore {
300 public:
301  Semaphore(uint32 maxCount = 100);
302  Semaphore(const char* name, uint32 maxCount = 100);
303  ~Semaphore();
304  bool wait();
305  bool wait(uint32 timeout);
306  bool signal();
307 // bool destroy();
308  char *name;
309 protected:
310  #ifdef WINDOWS
311  HANDLE semaphore;
312  #else
313  sem_t* semaphore;
314  #endif
315 };
316 
317 class Event {
318 public:
319  Event();
320  Event(const char* name);
321  ~Event();
322  bool waitNext();
323  bool waitNext(uint32 timeout);
324  bool signal();
325 // bool destroy();
326 protected:
327  char *name;
328  #ifdef WINDOWS
329  HANDLE event;
330  #else
331  pthread_cond_t* event;
332  pthread_mutex_t* mutex;
333  #endif
334 };
335 
336 bool EnterMutex(const char* name, uint32 ms, bool autocreate = true);
337 bool LeaveMutex(const char* name);
338 bool DestroyMutex(const char* name);
339 
340 Semaphore* GetSemaphore(const char* name, bool autocreate = true);
341 bool WaitForSemaphore(const char* name, uint32 ms, bool autocreate = true);
342 bool SignalSemaphore(const char* name);
343 bool DestroySemaphore(const char* name);
344 
345 bool WaitNextEvent(const char* name, uint32 ms, bool autocreate = true);
346 bool SignalEvent(const char* name);
347 bool DestroyEvent(const char* name);
348 
349 static Mutex* SharedMemoryMutexMapMutex = NULL;
350 static std::map<std::string, Mutex*>* SharedMemoryMutexMap = NULL;
351 typedef std::pair<std::string, Mutex*> SharedMemoryMutexMapPair;
352 static Mutex* SharedMemorySemaphoreMapMutex = NULL;
353 static std::map<std::string, Semaphore*>* SharedMemorySemaphoreMap = NULL;
354 typedef std::pair<std::string, Semaphore*> SharedMemorySemaphoreMapPair;
355 static Mutex* SharedMemoryEventMapMutex = NULL;
356 static std::map<std::string, Event*>* SharedMemoryEventMap = NULL;
357 typedef std::pair<std::string, Event*> SharedMemoryEventMapPair;
358 
359 #ifdef WINDOWS
360 struct ProcessData {
361  PROCESS_INFORMATION procInfo;
362  STARTUPINFO si;
363 };
364 static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
365 typedef std::pair <uint32, ProcessData*> Proc_Pair;
366 static HANDLE ghJob = NULL;
367 #endif
368 
370  uint32 globalID;
371  uint32 id;
372  uint64 start;
373  uint64 end;
374  uint32 interval;
375  #ifdef WINDOWS
376  HANDLE handle;
377  #else
378  timer_t handle;
379  #endif
380 };
381 
382 struct TimerTrigger {
383  uint32 id;
384  uint64 time;
385 };
386 
387 class Timer {
388 public:
389  static std::map<uint32, Timer*>* timers;
390 
391  Timer();
392  ~Timer();
393 
394  bool addTimer(uint32 id, uint32 interval, uint64 start = 0, uint64 end = 0);
395  bool triggerTimer(uint32 id);
396  bool waitForTimer(uint32 timeout, uint32& id, uint64& time);
397  bool removeTimer(uint32 id);
398 
399 private:
400  uint32 globalID;
401  Mutex mutex;
402  Semaphore semaphore;
403  std::queue<TimerTrigger*> triggers;
404  std::map<uint32, TimerSchedule*> schedules;
405  std::list<TimerSchedule*> oldSchedules;
406 };
407 
408 #ifdef WINDOWS
409  void CALLBACK TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired);
410 #else
411  static void TimerCallback(int sig, siginfo_t *siginfo, void *context);
412 #endif
413 bool UnitTest_Timer();
414 bool UnitTest_Utils();
415 
417 // Wait Queue //
419 
420 template <typename T>
421 class WaitQueue {
422 public:
423  WaitQueue() {}
424  virtual ~WaitQueue() {}
425 
426  bool add(T entry) {
427  if (!mutex.enter(200, __FUNCTION__))
428  return false;
429  internalQueue.push(entry);
430  semaphore.signal();
431  mutex.leave();
432  return true;
433  }
434  uint32 getCount() {
435  uint32 size;
436  if (!mutex.enter(200, __FUNCTION__))
437  return 0;
438  size = (uint32)internalQueue.size();
439  mutex.leave();
440  return size;
441  }
442  bool peekFirst(T& first) {
443  if (!mutex.enter(200, __FUNCTION__))
444  return false;
445  if (!internalQueue.size()) {
446  mutex.leave();
447  return false;
448  }
449  first = internalQueue.front();
450  mutex.leave();
451  return true;
452  }
453  bool takeFirst(T& first) {
454  if (!mutex.enter(200, __FUNCTION__))
455  return false;
456  if (!internalQueue.size()) {
457  mutex.leave();
458  return false;
459  }
460  first = internalQueue.front();
461  internalQueue.pop();
462  mutex.leave();
463  return true;
464  }
465  bool waitForAndPeekFirst(T& first, uint32 timeoutMS) {
466  if (!mutex.enter(200, __FUNCTION__))
467  return false;
468  if (internalQueue.size()) {
469  first = internalQueue.front();
470  mutex.leave();
471  return true;
472  }
473  mutex.leave();
474  if (!semaphore.wait(timeoutMS))
475  return false;
476  if (!mutex.enter(200, __FUNCTION__))
477  return false;
478  if (internalQueue.size()) {
479  first = internalQueue.front();
480  mutex.leave();
481  return true;
482  }
483  else {
484  mutex.leave();
485  return false;
486  }
487  }
488  bool waitForAndTakeFirst(T& first, uint32 timeoutMS) {
489  if (!mutex.enter(200, __FUNCTION__))
490  return false;
491  if (internalQueue.size()) {
492  first = internalQueue.front();
493  internalQueue.pop();
494  mutex.leave();
495  return true;
496  }
497  mutex.leave();
498  if (!semaphore.wait(timeoutMS))
499  return false;
500  if (!mutex.enter(200, __FUNCTION__))
501  return false;
502  if (internalQueue.size()) {
503  first = internalQueue.front();
504  internalQueue.pop();
505  mutex.leave();
506  return true;
507  }
508  else {
509  mutex.leave();
510  return false;
511  }
512  }
513  virtual bool clear() {
514  if (!mutex.enter(200, __FUNCTION__))
515  return false;
516  std::queue<T> empty;
517  std::swap(internalQueue, empty);
518  mutex.leave();
519  return true;
520  }
521 
522 protected:
523  Mutex mutex;
524  Semaphore semaphore;
525  std::queue<T> internalQueue;
526 };
527 
528 template <typename T>
529 class WaitQueuePointer : public WaitQueue<T> {
530 public:
531  WaitQueuePointer() {}
532  virtual ~WaitQueuePointer() { clear(); }
533 
534  T waitForAndTakeFirst(uint32 timeoutMS) {
535  T first;
536  if (WaitQueue<T>::waitForAndTakeFirst(first, timeoutMS))
537  return first;
538  else
539  return NULL;
540  }
541 
542  virtual bool clear() {
543  if (!WaitQueue<T>::mutex.enter(200, __FUNCTION__))
544  return false;
545  while (WaitQueue<T>::internalQueue.size()) {
546  delete(WaitQueue<T>::internalQueue.front());
548  }
549  WaitQueue<T>::mutex.leave();
550  return true;
551  }
552 };
553 
554 
556 // Time Queue //
558 
559 template <typename T>
561  uint64 time;
562  T entry;
563 };
564 
565 template <typename T>
566 class TimeQueue {
567 public:
568  TimeQueue() {}
569  virtual ~TimeQueue() {}
570 
571  bool add(uint64 time, T entry) {
572  if (!mutex.enter(200, __FUNCTION__))
573  return false;
574  TimeQueueEntry<T> newEntry;
575  newEntry.time = time;
576  newEntry.entry = entry;
577  typename std::list< TimeQueueEntry<T> >::iterator i = internalList.begin(),
578  e = internalList.end();
579  while (i != e) {
580  if (time < (*i).time) {
581  internalList.insert(i, newEntry);
582  mutex.leave();
583  return true;
584  }
585  i++;
586  }
587  internalList.push_back(newEntry);
588  mutex.leave();
589  return true;
590  }
591  uint32 getCount() {
592  uint32 size;
593  if (!mutex.enter(200, __FUNCTION__))
594  return 0;
595  size = (uint32)internalList.size();
596  mutex.leave();
597  return size;
598  }
599  bool getNextEntryDue(T& entry) {
600  if (!mutex.enter(200, __FUNCTION__))
601  return false;
602  if (!internalList.size()) {
603  mutex.leave();
604  return false;
605  }
606  uint64 now = GetTimeNow();
607  TimeQueueEntry<T> first = internalList.front();
608  if (first.time < now) {
609  internalList.pop_front();
610  entry = first.entry;
611  mutex.leave();
612  return true;
613  }
614  mutex.leave();
615  return false;
616  }
617  virtual bool clear() {
618  if (!mutex.enter(200, __FUNCTION__))
619  return false;
620  std::list< TimeQueueEntry<T> > empty;
621  std::swap(internalList, empty);
622  mutex.leave();
623  return true;
624  }
625 
626 protected:
627  Mutex mutex;
628  std::list< TimeQueueEntry<T> > internalList;
629 };
630 
631 template <typename T>
632 class TimeQueuePointer : public TimeQueue<T> {
633 public:
634  TimeQueuePointer() {}
635  virtual ~TimeQueuePointer() { clear(); }
636 
637  T getNextEntryDue() {
638  T first;
640  return first;
641  else
642  return NULL;
643  }
644 
645  virtual bool clear() {
646  if (!TimeQueue<T>::mutex.enter(200, __FUNCTION__))
647  return false;
648  typename std::list< TimeQueueEntry<T> >::iterator i = TimeQueue<T>::internalList.begin(),
649  e = TimeQueue<T>::internalList.end();
650  while (i != e) {
651  delete((*i).entry);
652  i++;
653  }
655  TimeQueue<T>::mutex.leave();
656  return true;
657  }
658 };
659 
660 
662 // Shared Memory //
664 
665 // Create named shared memory segment
666 char* CreateSharedMemorySegment(const char* name, uint64 size, bool force = false);
667 // Get named shared memory segment
668 char* OpenSharedMemorySegment(const char* name, uint64 size);
669 // Close named shared memory segment
670 bool CloseSharedMemorySegment(char* data, uint64 size);
671 // Destroy named shared memory segment
672 // bool DestroySharedMemorySegment(char* data, uint32 size);
673 
675 // Bit Operations //
677 
678 // Calc byte size of bitfield with uint32 boundary
679 uint32 Calc32BitFieldSize(uint32 bitsize);
680 // Reset bitfield set all as free
681 bool Reset32BitField(char* bitfield, uint32 bytesize);
682 // Get first zero bit in field of size bits, starting from data loc
683 bool GetFirstFreeBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
684 // Get first block of num zero bit in field of size bits, starting from data loc
685 bool GetFirstFreeBitLocN(const char* bitfield, uint32 bytesize, uint32 num, uint32& loc);
686 // Set the nth bit to value in field of size bits, starting from data loc
687 bool SetBit(uint32 loc, bit value, char* bitfield, uint32 bytesize);
688 // Set the block of num bits starting with nth bit to value in field of size bits, starting from data loc
689 bool SetBitN(uint32 loc, uint32 num, bit value, char* bitfield, uint32 bytesize);
690 // Get the nth bit in field of size bits, starting from data loc
691 bool GetBit(uint32 loc, const char* bitfield, uint32 bytesize, bit& val);
692 // Get location of last bit in use, starting from data loc
693 bool GetLastOccupiedBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
694 
695 
696 
697 // Return string representing the bitfield
698 std::string GetBitFieldAsString(const char* bitfield, uint32 bytesize, uint32 size);
699 // Print string representing the bitfield
700 std::string PrintBitFieldString(const char* bitfield, uint32 bytesize, uint32 size, const char* title);
701 
702 
704 // Threading //
706 
707 std::string PrintProgramTrace(uint32 startLine = 0, uint32 endLine = 0);
708 std::list<std::string> GetProgramTrace();
709 
710 int32 AtomicIncrement32(int32 volatile &v);
711 int64 AtomicIncrement64(int64 volatile &v);
712 int32 AtomicDecrement32(int32 volatile &v);
713 int64 AtomicDecrement64(int64 volatile &v);
714 
715 bool Sleep(uint32 ms);
716 
717 bool CreateThread(THREAD_FUNCTION func, void* args, ThreadHandle& thread, uint32 &osID);
718 
719 bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS = 0);
720 
721 bool CheckForThreadFinished(ThreadHandle hThread);
722 
723 bool TerminateThread(ThreadHandle hThread);
724 
725 bool PauseThread(ThreadHandle hThread);
726 
727 bool ContinueThread(ThreadHandle hThread);
728 
729 bool GetCurrentThreadUniqueID(uint32 &tid);
730 
731 bool GetCurrentThreadOSID(uint32 &tid);
732 
733 bool GetCurrentThread(ThreadHandle& thread);
734 
735 bool IsThreadRunning(ThreadHandle hThread);
736 
737 uint32 GetThreadStatColAbility();
738 
739 #if defined WINDOWS
740  #define FileTimeToUint64(ft) (((uint64)(ft.dwHighDateTime))<<32)|((uint64)ft.dwLowDateTime)
741 #endif
742 
743 // For Windows only until pthreads supports getrusage from other threads
744 bool GetCPUTicks(ThreadHandle hThread, uint64& ticks);
745 
746 bool GetCPUTicks(uint64& ticks);
747 
748 bool GetProcessCPUTicks(uint64& ticks);
749 
750 bool GetProcessCPUTicks(uint32 osProcID, uint64& ticks);
751 
752 bool GetProcAndOSCPUUsage(double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
753 
754 bool GetProcAndOSCPUUsage(uint32 osProcID, double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
755 
756 bool GetOSCPUUsage(double& percentUse);
757 
758 bool GetThreadPriority(ThreadHandle hThread, uint16 priority);
759 
760 bool SetThreadPriority(ThreadHandle hThread, uint16 priority);
761 
762 int ToOSPriority(int pri);
763 
764 int FromOSPriority(int pri);
765 
766 bool SignalThread(ThreadHandle hThread, int32 signal);
767 
769 // Desktop //
771 
772 bool GetDesktopSize(uint32& width, uint32& height);
773 
774 bool RenameConsoleWindow(const char* name, bool prepend = false);
775 
776 bool MoveConsoleWindow(int32 x = -1, int32 y = -1, int32 w = -1, int32 h = -1);
777 
779 // Processes //
781 
782 #define PROC_ERROR 0
783 #define PROC_TERMINATED 1
784 #define PROC_NOTSTARTED 2
785 #define PROC_RUNNING 3
786 #define PROC_TIMEOUT 4
787 
788 #define NUM_PIPES 2
789 #define PARENT_WRITE_PIPE 0
790 #define PARENT_READ_PIPE 1
791 /* always in a pipe[], pipe[0] is for read and
792  pipe[1] is for write */
793 #define READ_FD 0
794 #define WRITE_FD 1
795 #define PARENT_READ_FD ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
796 #define PARENT_WRITE_FD ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
797 #define CHILD_READ_FD ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
798 #define CHILD_WRITE_FD ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
799 
800 #define PROCBUFSIZE 4096
801 
802 int RunOSCommand(const char* cmdline, const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString);
803 uint32 NewProcess(const char* cmdline, const char* initdir = NULL, const char* title = NULL,
804  int16 x = -1, int16 y = -1, int16 w = -1, int16 h = -1);
805 uint8 GetProcessStatus(uint32 proc, int &returncode);
806 bool EndProcess(uint32 proc);
807 uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode);
808 uint32 GetLocalProcessID();
809 
811 // DLL Libraries //
813 
814 #ifdef WINDOWS
815  #define DLLHandle HINSTANCE
816 #else // WINDOWS
817  #define DLLHandle void*
818 #endif // WINDOWS
819 
820 typedef int (* LibraryFunction)();
821 
822 class CommandLineInfo;
824 public:
825  static CommandLineInfo* CommandLineInfoSingleton;
826  CommandLineInfo() {}
827  std::string CommandLineString;
828  std::string CommandLineExec;
829  std::string CommandLineExecOnly;
830  std::string CommandLineExecPath;
831  std::vector<std::string> CommandLineItems;
832  std::map<std::string, std::string> CommandLineArgs;
833 };
834 
835 
836 
837 bool SetCommandLine(int argc, char* argv[]);
838 std::string GetCommandLine();
839 std::string GetCommandLinePath();
840 std::string GetCommandLineExecutable();
841 std::string GetCommandLineExecutableOnly();
842 uint32 GetCommandLineArgCount();
843 std::string GetCommandLineArg(uint16 n);
844 std::string GetCommandLineArg(const char* key);
845 
846 class Library {
847 public:
848  static std::string patchLibraryFilename(const char* filename, const char* path = NULL);
849 
850  Library();
851  ~Library();
852  bool load(const char* filename);
853  LibraryFunction getFunction(const char* funcName);
854 private:
855  DLLHandle handle;
856 };
857 
858 Library* OpenLibrary(const char* libName);
859 
861 // OS System //
863 
864 const char* GetComputerName();
865 
866 uint64 GetProcessMemoryUsage();
868 
869 uint16 GetCPUCount();
870 
871 uint16 GetCPUArchitecture();
872 
873 uint64 GetCPUSpeed();
874 
875 uint64 GetSystemMemorySize();
876 
877 bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM);
878 
879 const char* GetSystemArchitecture();
880 
881 const char* GetSystemOSName();
882 
883 bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build, char* text, uint16 textSize);
884 
885 //bool RunOSTextCommand(const char* cmd, char* result, uint32 size);
886 
887 //extern char OSLocalHostName[1024];
888 //extern char OSArchitectureName[1024];
889 //extern char OSName[1024];
890 
891 
893 // Sockets //
895 
896 #ifdef WINDOWS
897  bool CheckNetworkInit();
898  #define CHECKNETWORKINIT utils::CheckNetworkInit();
899 #else
900  #define CHECKNETWORKINIT
901  #define WSAEWOULDBLOCK EAGAIN
902 #endif
903 
904 bool GetSocketError(int wsaError, char* errorString, uint16 errorStringMaxSize, bool* isRecoverable);
905 
906 int GetLastOSErrorNumber();
907 std::string GetLastOSErrorMessage();
908 
909 bool WaitForSocketReadability(SOCKET s, int32 timeout);
910 bool WaitForSocketWriteability(SOCKET s, int32 timeout);
911 
912 bool SetSocketNonBlockingMode(SOCKET s);
913 bool SetSocketBlockingMode(SOCKET s);
914 
916  uint32 address;
917  uint64 mac;
918  char name[MAXKEYNAMELEN+1];
919  char friendlyName[MAXKEYNAMELEN+1];
920 };
921 
922 bool LookupIPAddress(const char* name, uint32& address);
923 bool LookupHostname(uint32 address, char* name, uint32 maxSize);
924 std::string GetLocalHostnameString();
925 bool GetLocalHostname(char* name, uint32 maxSize);
926 bool IsLocalIPAddress(const char* addr);
927 bool IsLocalIPAddress(uint32& address);
928 bool GetLocalIPAddress(uint32& address);
929 uint32* GetLocalIPAddresses(uint32& count);
930 bool GetLocalMACAddress(uint64& address);
931 uint64* GetLocalMACAddresses(uint32& count);
932 NetworkInterfaces* GetLocalInterfaces(uint32& count);
933 bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort);
934 
935 #define LOCALHOSTIP 16777343 // 127.0.0.1 as 32-bit dec
936 #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
937 #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
938 
939 #define GETIPPORT(a) *(uint16*)((char*)&a + sizeof(uint32))
940 #define GETIPADDRESS(a) *(uint32*)&a
941 #define GETIPADDRESSPORT(a,p) (((uint32)a)) | (((uint64)p)<<32)
942 #define GETIPADDRESSQUAD(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3]
943 #define GETIPADDRESSQUADPORT(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3], ((uint16*)&a)[2]
944 
945 #ifdef WINDOWS
946  std::string GetRegistryKeyInfo(const char* key, HKEY &hKeyRoot);
947  std::string GetRegistryParentKeyInfo(const char* key, HKEY &hKeyRoot);
948 #endif // WINDOWS
949 uint32 ReadRegistryDWORD(const char* key, const char* entry);
950 uint64 ReadRegistryQWORD(const char* key, const char* entry);
951 std::string ReadRegistryString(const char* key, const char* entry);
952 bool WriteRegistryDWORD(const char* key, const char* entry, uint32 value);
953 bool WriteRegistryQWORD(const char* key, const char* entry, uint64 value);
954 bool WriteRegistryString(const char* key, const char* entry, const char* value);
955 bool DeleteRegistryEntry(const char* key, const char* entry);
956 bool DeleteRegistryKey(const char* key);
957 bool DeleteRegistryTree(const char* root, const char* key);
958 //bool CopyRegistryKey(const char* key, const char* newName);
959 bool CopyRegistryTree(const char* entry, const char* newName);
960 //bool RenameRegistryKey(const char* key, const char* newName);
961 //bool RenameRegistryTree(const char* entry, const char* newName);
962 
963 
964 
965 bool UtilsTest();
966 void PrintBinary(void* p, uint32 size, bool asInt, const char* title);
967 const char* stristr(const char *str, const char *substr, uint32 len = 0);
968 bool GetNextLineEnd(const char *str, uint32 size, uint32& len, uint32& crSize);
969 uint32 TextReplaceCharsInPlace(char* str, uint32 size, char find, char replace);
970 bool TextEndsWith(const char* str, const char* end, bool caseSensitive = true);
971 bool TextStartsWith(const char* str, const char* start, bool caseSensitive = true);
972 uint32 strcpyavail(char* dst, const char* src, uint32 maxlen, bool copyAvailable);
973 const char* laststrstr(const char* str1, const char* str2);
974 const char* laststristr(const char* str1, const char* str2);
975 
976 uint32 StringSingleReplace(std::string& text, std::string key, std::string value, bool onlyFirst);
977 uint32 StringMultiReplace(std::string& text, std::map<std::string, std::string>& map, bool onlyFirst);
978 uint32 StringScriptReplace(std::string& text, std::string name, std::list< std::map<std::string, std::string> >& list);
979 
980 std::string TextCapitalise(const char* text);
981 std::string TextUppercase(const char* text);
982 std::string TextLowercase(const char* text);
983 std::string TextIndent(const char* text, const char* indent);
984 std::string TextUnindent(const char* text);
985 std::string TextTrimQuotes(const char* text);
986 std::string TextTrim(const char* text);
987 std::multimap<std::string, std::string> TextMultiMapSplit(const char* text, const char* outersplit, const char* innersplit);
988 std::map<std::string, std::string> TextMapSplit(const char* text, const char* outersplit, const char* innersplit);
989 std::string TextJoin(std::vector<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
990 std::string TextJoin(std::list<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
991 std::string TextJoin(std::map<std::string, std::string> &map, const char* innersplit, const char* outersplit, bool keyquotes, bool valquotes);
992 std::string TextJoinJSON(std::map<std::string, std::string> &map);
993 std::string TextJoinXML(std::map<std::string, std::string> &map, const char* innernodeName, const char* outernodeName);
994 std::vector<std::string> TextListSplit(const char* text, const char* split, bool keepEmpty = true, bool autoTrim = false);
995 std::vector<std::string> TextListSplitLines(const char* text, bool keepEmpty = true, bool autoTrim = false);
996 std::vector<std::string> TextListBreakLines(const char* text, uint32 maxLineLength = 80);
997 std::string TextListBreakLines(const char* text, uint32 maxLineLength, const char* breakstr);
998 std::string TextVectorConcat(std::vector<std::string>, const char* sep, bool allowEmpty = true);
999 std::vector<std::string> TextCommandlineSplit(const char* cmdline);
1000 char** SplitCommandline(const char* cmdline, int& argc);
1001 wchar_t** SplitCommandlineW(const char* cmdline, int& argc);
1002 bool DeleteCommandline(char** argv, int argc);
1003 
1004 std::string StringFormat(const char *format, ...);
1005 char* StringFormat(uint32& size, const char *format, ...);
1006 bool StringFormatInto(char* dst, uint32 maxsize, const char *format, ...);
1007 char* StringFormatVA(uint32& size, const char *format, va_list args);
1008 
1009 unsigned char Hex2Char(const char* str);
1010 unsigned char Dec2Char(const char* str);
1011 int CRC32(const char *addr, uint32 length, int32 crc = 0);
1012 
1013 int8 CompareFloats(float64 a, float64 b);
1014 
1015 struct FileDetails {
1016  bool doesExist;
1017  bool isDirectory;
1018  bool isReadable;
1019  bool isWritable;
1020  bool isExecutable;
1021 
1022  uint32 size;
1023  uint64 lastAccessTime;
1024  uint64 lastModifyTime;
1025  uint64 creationTime;
1026 };
1027 
1028 #define NOSUCHFILE 0
1029 #define STANDARDFILE 1
1030 #define STANDARDDIR 2
1031 
1032 std::string ReadAFileString(std::string filename);
1033 char* ReadAFile(const char* filename, uint32& length, bool binary = false);
1034 char* ReadAFile(const char* dir, const char* filename, uint32& length, bool binary = false);
1035 bool WriteAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1036 bool WriteAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1037 bool AppendToAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1038 bool AppendToAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1039 char* GetFileList(const char* dirname, const char* ext, uint32& count, bool fullpath, uint32 maxNameLen = 256);
1040 FileDetails GetFileDetails(const char* filename);
1041 std::string GetFilePath(const char* filename);
1042 const char* GetFileBasename(const char* filename);
1043 bool DeleteAFile(const char* filename, bool force);
1044 bool DeleteAFile(const char* dir, const char* filename, bool force);
1045 bool DeleteADir(const char* dirname, bool force);
1046 bool CreateADir(const char* dirname);
1047 bool DoesADirExist(const char* dirname);
1048 bool DoesAFileExist(const char* filename);
1049 bool DeleteFilesInADir(const char* dirname, bool force);
1050 bool ChangeAFileAttr(const char* filename, bool read, bool write);
1051 bool MoveAFile(const char* oldfilename, const char* newfilename, bool force = false);
1052 bool MoveAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1053 bool CopyAFile(const char* oldfilename, const char* newfilename, bool force = false);
1054 bool CopyAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1055 
1056 char* Int2Ascii(int64 value, char* result, uint16 size, uint8 base);
1057 char* Uint2Ascii(uint64 value, char* result, uint16 size, uint8 base);
1058 unsigned char* Ascii2UTF16LE(const char* ascii, uint32 len, uint32& size);
1059 
1060 bool IsTextNumeric(const char* ascii, uint32 start = 0, uint32 end = 0);
1061 int64 Ascii2Int64(const char* ascii, uint32 start = 0, uint32 end = 0);
1062 uint64 Ascii2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
1063 uint64 AsciiHex2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
1064 int32 Ascii2Int32(const char* ascii, uint32 start = 0, uint32 end = 0);
1065 uint32 Ascii2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
1066 uint32 AsciiHex2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
1067 float64 Ascii2Float64(const char* ascii, uint32 start = 0, uint32 end = 0);
1068 
1069 char* TextSubstringCopy(const char* ascii, uint32 start, uint32 end);
1070 
1071 std::string DecodeJSON(std::string str);
1072 std::string EncodeJSON(std::string str);
1073 
1074 bool SeedRandomValues(uint32 seedvalue = 0);
1075 double RandomValue();
1076 double RandomValue(double to);
1077 double RandomValue(double from, double to);
1078 double RandomValue(double from, double to, double interval);
1079 int64 RandomInt(int64 from = 0, int64 to = 100);
1080 
1081 //std::string BytifySize(int32 val);
1082 std::string BytifySize(double val);
1083 //std::string BytifySizes(int32 val1, int32 val2);
1084 std::string BytifySizes(double val1, double val2);
1085 //std::string BytifyRate(int32 val);
1086 std::string BytifyRate(double val);
1087 //std::string BytifyRates(int32 val1, int32 val2);
1088 std::string BytifyRates(double val1, double val2);
1089  // end of utils
1091 
1092 } // namespace utils
1093 } // namespace cmlabs
1094 
1095 #endif //_UTILS_H_
1096 
Definition: Utils.h:255
uint64 GetPeakProcessMemoryUsage()
Definition: Utils.cpp:3927
Definition: Utils.h:175
Definition: Utils.h:560
Definition: Bitmap.h:7
Definition: Utils.h:421
Definition: Utils.h:1015
Definition: Utils.h:823
Definition: Utils.h:846
Definition: Utils.h:317
Definition: Utils.h:387
Definition: Utils.h:197
Definition: Utils.h:299
Definition: Utils.h:369
Definition: Utils.h:529
Definition: Utils.h:276
Definition: Utils.h:382
Definition: Utils.h:566
Definition: Utils.h:632
Definition: Utils.h:189
Definition: Utils.h:915
Definition: Utils.h:142
compute CRC32 hash, based on Intel&#39;s Slicing-by-8 algorithm
Definition: crc32.h:41