CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
Utils.h
Go to the documentation of this file.
1
10#if !defined(_UTILS_H_)
11#define _UTILS_H_
12
13#include <math.h>
14#include <stdio.h>
15#include <string.h>
16#include <time.h>
17#include <fcntl.h> /* For O_* constants */
18#include <sys/stat.h> /* For mode constants */
19#include <sys/types.h>
20#include <stdarg.h>
21#include <iomanip>
22
23#include "Types.h"
24#include "Base64.h"
25
26#ifdef WINDOWS
27 #include <io.h>
28// #include <windows.h>
29 #include <winsock2.h>
30 #include <ws2tcpip.h>
31 #include <iphlpapi.h>
32 #include <iptypes.h>
33 #include "Psapi.h"
34 #include "direntwin.h"
35 #include <process.h>
36 // #include <Dbghelp.h> // needed for program trace only, link with Dbghelp.lib
37#else
38 #ifndef __APPLE__
39 #include <semaphore.h>
40 #endif
41 #include <dlfcn.h>
42 #include <errno.h>
43 #include <sys/utsname.h>
44 #include <sys/time.h>
45 #include <pthread.h>
46 #include <signal.h>
47#ifdef __APPLE__
48 #include <mach/mach.h>
49 #include <mach/mach_time.h>
50 #include <dispatch/dispatch.h>
51#else
52 #include <sys/prctl.h>
53#endif
54 #include <unistd.h>
55 #include <time.h>
56 #include <sys/mman.h>
57 #include <sys/syscall.h>
58#ifndef __APPLE__
59 #include <sys/sysinfo.h>
60#endif
61 #include <sys/socket.h>
62 #include <netdb.h>
63 #include <net/if.h>
64 #include <sys/ioctl.h>
65 #include <dirent.h>
66 #include <netinet/tcp.h>
67 #include <sys/wait.h>
68 #include <execinfo.h>
69 #include <sys/resource.h>
70 #include <limits>
71// #include <curses.h>
72#endif
73
74#ifdef WINDOWS
75 #include <direct.h>
76 #define GetCurrentDirEx _getcwd
77#else
78 //#include <unistd.h>
79 #define GetCurrentDirEx getcwd
80#endif
81
82#define WINSHMEMSPACE "Local"
83//#define WINSHMEMSPACE "Global"
84
85#define MAXKEYNAMELEN 256
86#define MAXVALUENAMELEN 1024
87#define MAXCONTENTLEN 4196
88#define MAXCOMMANDLINELEN 1024
89#define MAXFILENAMELEN 256
90#define MAXSHMEMNAMELEN 1024
91#define MAXSCRIPTLEN 10*1024
92
93#define THREAD_NONE 0
94#define THREAD_TERMINATED 1
95#define THREAD_INIT 2
96#define THREAD_RUNNING 3
97#define THREAD_PAUSED 4
98#define THREAD_INTERRUPTED 5
99
100#define THREAD_STATS_OFF 0
101#define THREAD_STATS_AUTO 1
102#define THREAD_STATS_ADHOC 2
103
104#ifdef WINDOWS
105// #define Mutex HANDLE
106// #define NMutex HANDLE
107// #define Semaphore HANDLE
108 #define ThreadHandle HANDLE
109// #define THREAD_FUNCTION static DWORD WINAPI
110// #define THREAD_FUNCTION DWORD WINAPI
111 #define THREAD_RET DWORD
112 typedef LPTHREAD_START_ROUTINE THREAD_FUNCTION;
113 #define THREAD_FUNCTION_CALL WINAPI
114 #define THREAD_ARG LPVOID
115 #define thread_ret_val(ret) return ret;
116 #define DllExport __declspec(dllexport)
117 #define MUTEX_INVALID NULL
118 #define SOCKETWOULDBLOCK WSAEWOULDBLOCK
119 #define SOCKETTRYAGAIN WSAEWOULDBLOCK
120 #define abs64 _abs64
121#else
122// #define Mutex pthread_mutex_t
123// #define NMutex sem_t *
124// #define Semaphore sem_t*
125 #define ThreadHandle pthread_t
126// #define THREAD_FUNCTION void*(*)(void*)
127 #define THREAD_RET void *
128 typedef THREAD_RET (*THREAD_FUNCTION)(void *);
129 #define THREAD_FUNCTION_CALL
130 #define THREAD_ARG void*
131 #define thread_ret_val(ret) pthread_exit((THREAD_RET)(intptr_t)ret);
132 #define stricmp strcasecmp
133 #define MUTEX_INVALID 0
134 #define SOCKET int
135 typedef struct sockaddr SOCKADDR;
136 #define SOCKET_ERROR -1
137 #define INVALID_SOCKET -1
138 #define closesocket(X) close(X)
139 #define SOCKETWOULDBLOCK EINPROGRESS
140 #define SOCKETTRYAGAIN EAGAIN
141 #define abs64 llabs
142 #define MUTEXMEMSIZE 64
143 #define EVENTMEMSIZE 256
144 #define SEMAPHOREMEMSIZE 256
145 #define _strcmpi strcasecmp
146 #define _strnicmp strnicmp
147 #define DllExport
148#endif
149
150#ifndef SD_BOTH
151 #define SD_BOTH 2
152#endif
153
154#define OSCPU_UNKNOWN 0
155#define OSCPU_X86 1
156#define OSCPU_AMD64 2
157#define OSCPU_IA64 3
158
159#define ERROR64 0xFFFFFFFFFFFFFFFFL
160#define ERROR32 0xFFFFFFFF
161#define ERROR16 0xFFFF
162#define ERROR8 0xFF
163
164#include "PsyTime.h"
165
166namespace cmlabs {
167
169// INIT/EXIT //
171
179public:
184};
185
190bool ClearUtilsMaps();
191
193// Logging //
195
196#define LOG_NOTOPIC 0
197#define LOG_SYSTEM 1
198#define LOG_NETWORK 2
199#define LOG_MEMORY 3
200#define LOG_PROCESS 4
201#define LOG_TOPIC5 5
202#define LOG_TOPIC6 6
203#define LOG_TOPIC7 7
204#define LOG_TOPIC8 8
205#define LOG_TOPIC9 9
206#define LOG_TOPIC10 10
207#define LOG_TOPIC11 11
208#define LOG_MAXCOUNT 12
209
210#define LOGPRINT 1
211#define LOGDEBUG 2
212
216std::string GetDataTypeName(uint32 datatype);
220uint32 GetDataTypeID(const char* typeName);
221
222// #define GETLOGTEXT(l) (char*)l+sizeof(LogEntry)
228struct LogEntry {
229 uint32 size; //
230 uint32 cid; // LOGENTRYID
231 uint64 time; //
232 uint32 source; //
233 uint8 subject; //
234 uint8 level; //
235 uint8 type; //
239 const char* getText(uint32& len);
244 bool setText(char* text, uint32 len);
246 std::string toJSON();
248 std::string toXML();
249};
250
257public:
259// virtual bool logPrint(uint32 source, uint8 subject, uint8 level, std::string text, uint64 time) = 0;
260// virtual bool logDebug(uint32 source, uint8 subject, uint8 level, std::string text, uint64 time) = 0;
262 virtual bool logEntry(LogEntry* entry) = 0;
263};
264
273public:
274 LogSystem();
275 ~LogSystem();
276
280 static bool SetLogReceiver(LogReceiver* rec);
281
286 static bool SetLogFileOutput(const char* logfile, bool printOut = true);
288 static bool SetLogLevelDebug(uint8 level);
290 static bool SetLogLevelDebug(uint8 subject, uint8 level);
292 static bool SetLogLevelVerbose(uint8 level);
294 static bool SetLogLevelVerbose(uint8 subject, uint8 level);
295
302 static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... );
304 static bool LogSystemDebug(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... );
305
309 char* logfile;
311};
312
313#define LogPrint LogSystem::LogSystemPrint
314#define LogDebug LogSystem::LogSystemDebug
315
316namespace utils {
317
378
380bool UtilsTest();
381
382// bool GetSystemName(uint32 id, const char* title, char* name, uint32 size);
383
384
385
387// Mutexes //
389
390#ifdef WINDOWS
391 #define SharedMemoryFileHandleMapType std::map<char*, HANDLE>
392#else
393 #define SharedMemoryFileHandleMapType std::map<void*, std::string>
394#endif
396
397static uint16 SharedSystemInstance = 0;
398
404
408bool SetSharedSystemInstance(uint32 inst);
411
412// https://stackoverflow.com/questions/44807302/create-c-timer-in-macos/52905687#52905687
413
418typedef bool (* DrumBeatFunc)(uint32 id, uint32 count);
419
424 uint32 id;
426 uint64 started;
427 uint32 interval;
429 uint32 count;
430 #ifdef WINDOWS
431 HANDLE handle;
432 #else
433 #ifdef __APPLE__
434 dispatch_source_t handle;
435 #else
436 timer_t handle;
437 #endif
438 #endif
439};
440
441static std::map<uint32, DrumBeatInfo>* DrumBeatMap = NULL;
442
449bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart = false);
451bool StartDrumBeat(uint32 id);
453bool StopDrumBeat(uint32 id);
455bool EndDrumBeat(uint32 id);
456
463class Mutex {
464public:
466 Mutex();
470 Mutex(const char* name, bool force = false);
471 ~Mutex();
473 bool enter();
478 bool enter(uint32 timeout, const char* errorMsg = NULL);
480 bool leave();
481// bool destroy();
482protected:
483 char *name;
485 uint32 osid;
486 uint32 total;
487 uint32 count;
488 #ifdef WINDOWS
489 HANDLE mutex;
490 #else
491 //sem_t* semaphore;
492 pthread_mutex_t* mutex;
493 #endif
494};
495
496
503public:
505 Semaphore(uint32 maxCount = 100);
507 Semaphore(const char* name, uint32 maxCount = 100);
508 ~Semaphore();
510 bool wait();
512 bool wait(uint32 timeout);
514 bool signal();
515// bool destroy();
516 char *name;
517protected:
518 #ifdef WINDOWS
519 HANDLE semaphore;
520 #else
521 #ifdef __APPLE__
522 void* semaphore_impl; /* dispatch_semaphore_t when name==NULL, else char* to shared memory */
523 #else
524 sem_t* semaphore;
525 #endif
526 #endif
527};
528
533class Event {
534public:
536 Event();
538 Event(const char* name);
539 ~Event();
541 bool waitNext();
543 bool waitNext(uint32 timeout);
545 bool signal();
546// bool destroy();
547protected:
548 char *name;
549 #ifdef WINDOWS
550 HANDLE event;
551 #else
552 pthread_cond_t* event;
553 pthread_mutex_t* mutex;
554 #endif
555};
556
561bool EnterMutex(const char* name, uint32 ms, bool autocreate = true);
563bool LeaveMutex(const char* name);
565bool DestroyMutex(const char* name);
566
570Semaphore* GetSemaphore(const char* name, bool autocreate = true);
572bool WaitForSemaphore(const char* name, uint32 ms, bool autocreate = true);
574bool SignalSemaphore(const char* name);
576bool DestroySemaphore(const char* name);
577
579bool WaitNextEvent(const char* name, uint32 ms, bool autocreate = true);
581bool SignalEvent(const char* name);
583bool DestroyEvent(const char* name);
584
586
588static std::map<std::string, Mutex*>* SharedMemoryMutexMap = NULL;
589typedef std::pair<std::string, Mutex*> SharedMemoryMutexMapPair;
591static std::map<std::string, Semaphore*>* SharedMemorySemaphoreMap = NULL;
592typedef std::pair<std::string, Semaphore*> SharedMemorySemaphoreMapPair;
594static std::map<std::string, Event*>* SharedMemoryEventMap = NULL;
595typedef std::pair<std::string, Event*> SharedMemoryEventMapPair;
596
597#ifdef WINDOWS
598struct ProcessData {
599 ProcessData() { hOutRead = NULL; hErrRead = NULL; }
600 PROCESS_INFORMATION procInfo;
601 STARTUPINFO si;
602 HANDLE hOutRead;
603 HANDLE hErrRead;
604};
605static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
606typedef std::pair <uint32, ProcessData*> Proc_Pair;
607static HANDLE ghJob = NULL;
608#endif
609
612
615 uint32 globalID;
616 uint32 id;
617 uint64 start;
618 uint64 end;
619 uint32 interval;
620 #ifdef WINDOWS
621 HANDLE handle;
622 #else
623 #ifdef __APPLE__
624 dispatch_source_t handle;
625 #else
626 timer_t handle;
627 #endif
628 #endif
629};
630
633 uint32 id;
634 uint64 time;
635};
636
643class Timer {
644public:
646 static std::map<uint32, Timer*>* timers;
647
648 Timer();
649 ~Timer();
650
657 bool addTimer(uint32 id, uint32 interval, uint64 start = 0, uint64 end = 0);
659 bool triggerTimer(uint32 id);
665 bool waitForTimer(uint32 timeout, uint32& id, uint64& time);
667 bool removeTimer(uint32 id);
668
669private:
670 uint32 globalID;
671 Mutex mutex;
672 Semaphore semaphore;
673 std::queue<TimerTrigger*> triggers;
674 std::map<uint32, TimerSchedule*> schedules;
675 std::list<TimerSchedule*> oldSchedules;
676};
677
678#ifdef WINDOWS
680 void CALLBACK TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired);
681#else
683 static void TimerCallback(int sig, siginfo_t *siginfo, void *context);
684#endif
686bool UnitTest_Timer();
688bool UnitTest_Utils();
689
691// Wait Queue //
693
702template <typename T>
704public:
706 virtual ~WaitQueue() {}
707
709 bool add(T entry) {
710 if (!mutex.enter(200, __FUNCTION__))
711 return false;
712 internalQueue.push(entry);
713 semaphore.signal();
714 mutex.leave();
715 return true;
716 }
717
718 uint32 getCount() {
719 uint32 size;
720 if (!mutex.enter(200, __FUNCTION__))
721 return 0;
722 size = (uint32)internalQueue.size();
723 mutex.leave();
724 return size;
725 }
726
727 bool peekFirst(T& first) {
728 if (!mutex.enter(200, __FUNCTION__))
729 return false;
730 if (!internalQueue.size()) {
731 mutex.leave();
732 return false;
733 }
734 first = internalQueue.front();
735 mutex.leave();
736 return true;
737 }
738
739 bool takeFirst(T& first) {
740 if (!mutex.enter(200, __FUNCTION__))
741 return false;
742 if (!internalQueue.size()) {
743 mutex.leave();
744 return false;
745 }
746 first = internalQueue.front();
747 internalQueue.pop();
748 mutex.leave();
749 return true;
750 }
751
753 bool waitForAndPeekFirst(T& first, uint32 timeoutMS) {
754 if (!mutex.enter(200, __FUNCTION__))
755 return false;
756 if (internalQueue.size()) {
757 first = internalQueue.front();
758 mutex.leave();
759 return true;
760 }
761 mutex.leave();
762 if (!semaphore.wait(timeoutMS))
763 return false;
764 if (!mutex.enter(200, __FUNCTION__))
765 return false;
766 if (internalQueue.size()) {
767 first = internalQueue.front();
768 mutex.leave();
769 return true;
770 }
771 else {
772 mutex.leave();
773 return false;
774 }
775 }
776
779 bool waitForAndTakeFirst(T& first, uint32 timeoutMS) {
780 if (!mutex.enter(200, __FUNCTION__))
781 return false;
782 if (internalQueue.size()) {
783 first = internalQueue.front();
784 internalQueue.pop();
785 mutex.leave();
786 return true;
787 }
788 mutex.leave();
789 if (!semaphore.wait(timeoutMS))
790 return false;
791 if (!mutex.enter(200, __FUNCTION__))
792 return false;
793 if (internalQueue.size()) {
794 first = internalQueue.front();
795 internalQueue.pop();
796 mutex.leave();
797 return true;
798 }
799 else {
800 mutex.leave();
801 return false;
802 }
803 }
804
805 virtual bool clear() {
806 if (!mutex.enter(200, __FUNCTION__))
807 return false;
808 std::queue<T> empty;
809 std::swap(internalQueue, empty);
810 mutex.leave();
811 return true;
812 }
813
814protected:
817 std::queue<T> internalQueue;
818};
819
822template <typename T>
823class WaitQueuePointer : public WaitQueue<T> {
824public:
826 virtual ~WaitQueuePointer() { clear(); }
827
830 T waitForAndTakeFirst(uint32 timeoutMS) {
831 T first;
832 if (WaitQueue<T>::waitForAndTakeFirst(first, timeoutMS))
833 return first;
834 else
835 return NULL;
836 }
837
839 virtual bool clear() {
840 if (!WaitQueue<T>::mutex.enter(200, __FUNCTION__))
841 return false;
842 while (WaitQueue<T>::internalQueue.size()) {
843 delete(WaitQueue<T>::internalQueue.front());
845 }
846 WaitQueue<T>::mutex.leave();
847 return true;
848 }
849};
850
851
853// Time Queue //
855
857template <typename T>
859 uint64 time;
861};
862
865template <typename T>
867public:
869 virtual ~TimeQueue() {}
870
872 bool add(uint64 time, T entry) {
873 if (!mutex.enter(200, __FUNCTION__))
874 return false;
875 TimeQueueEntry<T> newEntry;
876 newEntry.time = time;
877 newEntry.entry = entry;
878 typename std::list< TimeQueueEntry<T> >::iterator i = internalList.begin(),
879 e = internalList.end();
880 while (i != e) {
881 if (time < (*i).time) {
882 internalList.insert(i, newEntry);
883 mutex.leave();
884 return true;
885 }
886 i++;
887 }
888 internalList.push_back(newEntry);
889 mutex.leave();
890 return true;
891 }
892
893 uint32 getCount() {
894 uint32 size;
895 if (!mutex.enter(200, __FUNCTION__))
896 return 0;
897 size = (uint32)internalList.size();
898 mutex.leave();
899 return size;
900 }
901
903 bool getNextEntryDue(T& entry) {
904 if (!mutex.enter(200, __FUNCTION__))
905 return false;
906 if (!internalList.size()) {
907 mutex.leave();
908 return false;
909 }
910 uint64 now = GetTimeNow();
911 TimeQueueEntry<T> first = internalList.front();
912 if (first.time < now) {
913 internalList.pop_front();
914 entry = first.entry;
915 mutex.leave();
916 return true;
917 }
918 mutex.leave();
919 return false;
920 }
921
922 virtual bool clear() {
923 if (!mutex.enter(200, __FUNCTION__))
924 return false;
925 std::list< TimeQueueEntry<T> > empty;
926 std::swap(internalList, empty);
927 mutex.leave();
928 return true;
929 }
930
931protected:
933 std::list< TimeQueueEntry<T> > internalList;
934};
935
938template <typename T>
939class TimeQueuePointer : public TimeQueue<T> {
940public:
942 virtual ~TimeQueuePointer() { clear(); }
943
946 T first;
948 return first;
949 else
950 return NULL;
951 }
952
954 virtual bool clear() {
955 if (!TimeQueue<T>::mutex.enter(200, __FUNCTION__))
956 return false;
957 typename std::list< TimeQueueEntry<T> >::iterator i = TimeQueue<T>::internalList.begin(),
959 while (i != e) {
960 delete((*i).entry);
961 i++;
962 }
964 TimeQueue<T>::mutex.leave();
965 return true;
966 }
967};
968
969
971// Shared Memory //
973
975
981
987char* CreateSharedMemorySegment(const char* name, uint64 size, bool force = false);
991char* OpenSharedMemorySegment(const char* name, uint64 size);
995bool CloseSharedMemorySegment(char* data, uint64 size);
996// Destroy named shared memory segment
997// bool DestroySharedMemorySegment(char* data, uint32 size);
998
1000
1005
1007uint64 ntoh64(const uint64 *input);
1009uint64 hton64(const uint64_t *input);
1010
1013uint32 Calc32BitFieldSize(uint32 bitsize);
1015bool Reset32BitField(char* bitfield, uint32 bytesize);
1019bool GetFirstFreeBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1023bool GetFirstFreeBitLocN(const char* bitfield, uint32 bytesize, uint32 num, uint32& loc);
1025bool SetBit(uint32 loc, bit value, char* bitfield, uint32 bytesize);
1028bool SetBitN(uint32 loc, uint32 num, bit value, char* bitfield, uint32 bytesize);
1030bool GetBit(uint32 loc, const char* bitfield, uint32 bytesize, bit& val);
1032bool GetLastOccupiedBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1033
1036std::string GetBitFieldAsString(const char* bitfield, uint32 bytesize, uint32 size);
1039std::string PrintBitFieldString(const char* bitfield, uint32 bytesize, uint32 size, const char* title);
1040
1042
1043
1045// Threading //
1047
1050
1054std::string PrintProgramTrace(uint32 startLine = 0, uint32 endLine = 0);
1056std::list<std::string> GetProgramTrace();
1057
1059int32 AtomicIncrement32(int32 volatile &v);
1061int64 AtomicIncrement64(int64 volatile &v);
1063int32 AtomicDecrement32(int32 volatile &v);
1065int64 AtomicDecrement64(int64 volatile &v);
1066
1068bool Sleep(uint32 ms);
1069
1076bool CreateThread(THREAD_FUNCTION func, void* args, ThreadHandle& thread, uint32 &osID);
1077
1079bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS = 0);
1080bool ReapThread(ThreadHandle& hThread);
1081bool TryReapThread(ThreadHandle& hThread);
1082
1085
1088bool TerminateThread(ThreadHandle hThread);
1089
1092bool PauseThread(ThreadHandle hThread);
1093
1095bool ContinueThread(ThreadHandle hThread);
1096
1098bool GetCurrentThreadUniqueID(uint32 &tid);
1099
1101bool GetCurrentThreadOSID(uint32 &tid);
1102
1104bool GetCurrentThread(ThreadHandle& thread);
1105
1107bool IsThreadRunning(ThreadHandle hThread);
1108
1112
1113#if defined WINDOWS
1114 #define FileTimeToUint64(ft) (((uint64)(ft.dwHighDateTime))<<32)|((uint64)ft.dwLowDateTime)
1115#endif
1116
1120bool GetCPUTicks(ThreadHandle hThread, uint64& ticks);
1121
1123bool GetCPUTicks(uint64& ticks);
1124
1126bool GetProcessCPUTicks(uint64& ticks);
1127
1129bool GetProcessCPUTicks(uint32 osProcID, uint64& ticks);
1130
1138bool GetProcAndOSCPUUsage(double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1139
1147bool GetProcAndOSCPUUsage(uint32 osProcID, double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1148
1150bool GetOSCPUUsage(double& percentUse);
1151
1153bool GetThreadPriority(ThreadHandle hThread, uint16 priority);
1154
1156bool SetThreadPriority(ThreadHandle hThread, uint16 priority);
1157
1159int ToOSPriority(int pri);
1160
1162int FromOSPriority(int pri);
1163
1165bool SignalThread(ThreadHandle hThread, int32 signal);
1166
1168
1170// Desktop //
1172
1175
1177bool GetDesktopSize(uint32& width, uint32& height);
1178
1180bool RenameConsoleWindow(const char* name, bool prepend = false);
1181
1183bool MoveConsoleWindow(int32 x = -1, int32 y = -1, int32 w = -1, int32 h = -1);
1184
1186
1188// Processes //
1190
1191#define PROC_ERROR 0
1192#define PROC_TERMINATED 1
1193#define PROC_NOTSTARTED 2
1194#define PROC_RUNNING 3
1195#define PROC_TIMEOUT 4
1196
1197#define NUM_PIPES 2
1198#define PARENT_WRITE_PIPE 0
1199#define PARENT_READ_PIPE 1
1200/* always in a pipe[], pipe[0] is for read and
1201 pipe[1] is for write */
1202#define READ_FD 0
1203#define WRITE_FD 1
1204#define PARENT_READ_FD ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
1205#define PARENT_WRITE_FD ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
1206#define CHILD_READ_FD ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
1207#define CHILD_WRITE_FD ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
1208
1209#define PROCBUFSIZE 4096
1210
1213
1221int RunOSCommand(const char* cmdline, const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString);
1226uint32 NewProcess(const char* cmdline, const char* initdir = NULL, const char* title = NULL,
1227 int16 x = -1, int16 y = -1, int16 w = -1, int16 h = -1);
1231uint8 GetProcessStatus(uint32 proc, int &returncode);
1233bool EndProcess(uint32 proc);
1234
1249uint32 NewProcessEx(const char* cmdline, const char* initdir, const char* title,
1250 const std::map<std::string, std::string>* env,
1251 bool captureOutput, bool ignoreOutput, bool newProcessGroup);
1256bool ReadProcessOutput(uint32 proc, std::string& out, std::string& err);
1261bool SendProcessBreak(uint32 proc, int sig);
1266uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode);
1268uint32 GetLocalProcessID();
1269
1271
1273// DLL Libraries //
1275
1276#ifdef WINDOWS
1277 #define DLLHandle HINSTANCE
1278#else // WINDOWS
1279 #define DLLHandle void*
1280#endif // WINDOWS
1281
1284
1286typedef int (* LibraryFunction)();
1287
1288class CommandLineInfo;
1292public:
1296 std::string CommandLineExec;
1299 std::vector<std::string> CommandLineItems;
1300 std::map<std::string, std::string> CommandLineArgs;
1301};
1302
1303
1304
1308bool SetCommandLine(int argc, char* argv[]);
1310std::string GetCommandLine();
1312std::string GetCommandLinePath();
1314std::string GetCommandLineExecutable();
1316std::string GetCommandLineExecutableOnly();
1318uint32 GetCommandLineArgCount();
1320std::string GetCommandLineArg(uint16 n);
1324std::string GetCommandLineArg(const char* key);
1328bool HasCommandLineArg(const char* key, std::string& value);
1329
1331class Library {
1332public:
1335 static std::string patchLibraryFilename(const char* filename, const char* path = NULL);
1336
1337 Library();
1338 ~Library();
1340 bool load(const char* filename);
1342 LibraryFunction getFunction(const char* funcName);
1343private:
1344 DLLHandle handle;
1345};
1346
1348Library* OpenLibrary(const char* libName);
1349
1351
1354
1356const char* GetComputerName();
1357
1359uint64 GetProcessMemoryUsage();
1362
1364uint16 GetCPUCount();
1365
1367uint16 GetCPUArchitecture();
1368
1370uint64 GetCPUSpeed();
1371
1373uint64 GetSystemMemorySize();
1374
1376bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM);
1377
1379const char* GetSystemArchitecture();
1380
1382const char* GetSystemOSName();
1383
1388bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build, char* text, uint16 textSize);
1389
1391
1392//bool RunOSTextCommand(const char* cmd, char* result, uint32 size);
1393
1394//extern char OSLocalHostName[1024];
1395//extern char OSArchitectureName[1024];
1396//extern char OSName[1024];
1397
1398
1400// Sockets //
1402
1408
1409#ifdef WINDOWS
1411 bool CheckNetworkInit();
1412 #define CHECKNETWORKINIT utils::CheckNetworkInit();
1413#else
1414 #define CHECKNETWORKINIT
1415 #define WSAEWOULDBLOCK EAGAIN
1416#endif
1417
1423bool GetSocketError(int wsaError, char* errorString, uint16 errorStringMaxSize, bool* isRecoverable);
1424
1428std::string GetLastOSErrorMessage();
1429
1431bool WaitForSocketReadability(SOCKET s, int32 timeout);
1433bool WaitForSocketWriteability(SOCKET s, int32 timeout);
1434
1439
1447
1449bool LookupIPAddress(const char* name, uint32& address);
1451bool LookupHostname(uint32 address, char* name, uint32 maxSize);
1453std::string GetLocalHostnameString();
1455bool GetLocalHostname(char* name, uint32 maxSize);
1457bool IsLocalIPAddress(const char* addr);
1459bool IsLocalIPAddress(uint32& address);
1461bool GetLocalIPAddress(uint32& address);
1463uint32* GetLocalIPAddresses(uint32& count);
1465bool GetLocalMACAddress(uint64& address);
1467uint64* GetLocalMACAddresses(uint32& count);
1471bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort);
1472
1473#define LOCALHOSTIP 16777343 // 127.0.0.1 as 32-bit dec
1474#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
1475#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
1476
1477#define GETIPPORT(a) *(uint16*)((char*)&a + sizeof(uint32))
1478#define GETIPADDRESS(a) *(uint32*)&a
1479#define GETIPADDRESSPORT(a,p) (((uint32)a)) | (((uint64)p)<<32)
1480#define GETIPADDRESSQUAD(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3]
1481#define GETIPADDRESSQUADPORT(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3], ((uint16*)&a)[2]
1482
1484
1489
1490#ifdef WINDOWS
1492 std::string GetRegistryKeyInfo(const char* key, HKEY &hKeyRoot);
1494 std::string GetRegistryParentKeyInfo(const char* key, HKEY &hKeyRoot);
1495#endif // WINDOWS
1497uint32 ReadRegistryDWORD(const char* key, const char* entry);
1499uint64 ReadRegistryQWORD(const char* key, const char* entry);
1501std::string ReadRegistryString(const char* key, const char* entry);
1503bool WriteRegistryDWORD(const char* key, const char* entry, uint32 value);
1505bool WriteRegistryQWORD(const char* key, const char* entry, uint64 value);
1507bool WriteRegistryString(const char* key, const char* entry, const char* value);
1509bool DeleteRegistryEntry(const char* key, const char* entry);
1511bool DeleteRegistryKey(const char* key);
1513bool DeleteRegistryTree(const char* root, const char* key);
1514//bool CopyRegistryKey(const char* key, const char* newName);
1516bool CopyRegistryTree(const char* entry, const char* newName);
1517//bool RenameRegistryKey(const char* key, const char* newName);
1518//bool RenameRegistryTree(const char* entry, const char* newName);
1519
1520
1521
1523
1527
1529bool UtilsTest();
1531void PrintBinary(void* p, uint32 size, bool asInt, const char* title);
1533const char* stristr(const char *str, const char *substr, uint32 len = 0);
1537bool GetNextLineEnd(const char *str, uint32 size, uint32& len, uint32& crSize);
1539uint32 TextReplaceCharsInPlace(char* str, uint32 size, char find, char replace);
1541bool TextEndsWith(const char* str, const char* end, bool caseSensitive = true);
1543bool TextStartsWith(const char* str, const char* start, bool caseSensitive = true);
1548uint32 strcpyavail(char* dst, const char* src, uint32 maxlen, bool copyAvailable);
1550const char* laststrstr(const char* str1, const char* str2);
1552const char* laststristr(const char* str1, const char* str2);
1553
1555
1558
1562uint32 StringSingleReplace(std::string& text, std::string key, std::string value, bool onlyFirst);
1564uint32 StringMultiReplace(std::string& text, std::map<std::string, std::string>& map, bool onlyFirst);
1568uint32 StringScriptReplace(std::string& text, std::string name, std::list< std::map<std::string, std::string> >& list);
1569
1571
1576
1578std::string TextCapitalise(const char* text);
1580std::string TextUppercase(const char* text);
1582std::string TextLowercase(const char* text);
1584std::string TextIndent(const char* text, const char* indent);
1586std::string TextUnindent(const char* text);
1588std::string TextTrimQuotes(const char* text);
1593std::string TextTrim(const char* text);
1602std::multimap<std::string, std::string> TextMultiMapSplit(const char* text, const char* outersplit, const char* innersplit);
1612std::map<std::string, std::string> TextMapSplit(const char* text, const char* outersplit, const char* innersplit);
1614std::string TextJoin(std::vector<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1616std::string TextJoin(std::list<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1619std::string TextJoin(std::map<std::string, std::string> &map, const char* innersplit, const char* outersplit, bool keyquotes, bool valquotes);
1621std::string TextJoinJSON(std::map<std::string, std::string> &map);
1623std::string TextJoinXML(std::map<std::string, std::string> &map, const char* innernodeName, const char* outernodeName);
1630std::vector<std::string> TextListSplit(const char* text, const char* split, bool keepEmpty = true, bool autoTrim = false);
1632std::vector<std::string> TextListSplitLines(const char* text, bool keepEmpty = true, bool autoTrim = false);
1634std::vector<std::string> TextListBreakLines(const char* text, uint32 maxLineLength = 80);
1636std::string TextListBreakLines(const char* text, uint32 maxLineLength, const char* breakstr);
1638std::string TextVectorConcat(std::vector<std::string>, const char* sep, bool allowEmpty = true);
1640std::vector<std::string> TextCommandlineSplit(const char* cmdline);
1642char** SplitCommandline(const char* cmdline, int& argc);
1644wchar_t** SplitCommandlineW(const char* cmdline, int& argc);
1646bool DeleteCommandline(char** argv, int argc);
1647
1649
1652
1661std::string StringFormat(const char *format, ...);
1663char* StringFormat(uint32& size, const char *format, ...);
1665bool StringFormatInto(char* dst, uint32 maxsize, const char *format, ...);
1667char* StringFormatVA(uint32& size, const char *format, va_list args);
1668
1670
1673
1675unsigned char Hex2Char(const char* str);
1677unsigned char Dec2Char(const char* str);
1687int CRC32(const char *addr, uint32 length, int32 crc = 0);
1688
1690int8 CompareFloats(float64 a, float64 b);
1691
1693
1698
1712
1713#define NOSUCHFILE 0
1714#define STANDARDFILE 1
1715#define STANDARDDIR 2
1716
1721std::string ReadAFileString(std::string filename);
1739char* ReadAFile(const char* filename, uint32& length, bool binary = false);
1741char* ReadAFile(const char* dir, const char* filename, uint32& length, bool binary = false);
1746bool WriteAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1748bool WriteAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1750bool AppendToAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1752bool AppendToAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1768char* GetFileList(const char* dirname, const char* ext, uint32& count, bool fullpath, uint32 maxNameLen = 256);
1770FileDetails GetFileDetails(const char* filename);
1772std::string GetFilePath(const char* filename);
1774const char* GetFileBasename(const char* filename);
1776std::string GetCurrentDir();
1778bool DeleteAFile(const char* filename, bool force);
1780bool DeleteAFile(const char* dir, const char* filename, bool force);
1782bool DeleteADir(const char* dirname, bool force);
1784bool CreateADir(const char* dirname);
1786bool DoesADirExist(const char* dirname);
1788bool DoesAFileExist(const char* filename);
1790bool DeleteFilesInADir(const char* dirname, bool force);
1792bool ChangeAFileAttr(const char* filename, bool read, bool write);
1794bool MoveAFile(const char* oldfilename, const char* newfilename, bool force = false);
1796bool MoveAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1798bool CopyAFile(const char* oldfilename, const char* newfilename, bool force = false);
1800bool CopyAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1801
1803
1818
1820char* Int2Ascii(int64 value, char* result, uint16 size, uint8 base);
1822char* Uint2Ascii(uint64 value, char* result, uint16 size, uint8 base);
1826unsigned char* Ascii2UTF16LE(const char* ascii, uint32 len, uint32& size);
1827
1829bool IsTextNumeric(const char* ascii, uint32 start = 0, uint32 end = 0);
1831int64 Ascii2Int64(const char* ascii, uint32 start = 0, uint32 end = 0);
1833uint64 Ascii2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
1835uint64 AsciiHex2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
1837int32 Ascii2Int32(const char* ascii, uint32 start = 0, uint32 end = 0);
1839uint32 Ascii2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
1841uint32 AsciiHex2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
1843float64 Ascii2Float64(const char* ascii, uint32 start = 0, uint32 end = 0);
1844
1846char* TextSubstringCopy(const char* ascii, uint32 start, uint32 end);
1847
1854std::string DecodeJSON(std::string str);
1859std::string EncodeJSON(std::string str);
1860
1862
1865
1871bool SeedRandomValues(uint32 seedvalue = 0);
1878double RandomValue();
1880double RandomValue(double to);
1882double RandomValue(double from, double to);
1884double RandomValue(double from, double to, double interval);
1886int64 RandomInt(int64 from = 0, int64 to = 100);
1887
1892std::string BytifySize(double val);
1894std::string BytifySizes(double val1, double val2);
1896std::string BytifyRate(double val);
1898std::string BytifyRates(double val1, double val2);
1899
1901 // end of utils
1903
1904} // namespace utils
1905} // namespace cmlabs
1906
1907#endif //_UTILS_H_
1908
Base64 encoding/decoding of arbitrary binary data (standard alphabet, '=' padding).
CMSDK time: µs-resolution 64-bit timestamps and the Time Mapping Constant (TMC).
Core fixed-width scalar typedefs and the PsyType / PsyContext hierarchical identifiers.
#define MAXKEYNAMELEN
Definition Utils.h:85
#define THREAD_RET
Definition Utils.h:127
#define DLLHandle
Definition Utils.h:1279
THREAD_RET(* THREAD_FUNCTION)(void *)
Definition Utils.h:128
#define ThreadHandle
Definition Utils.h:125
struct sockaddr SOCKADDR
Definition Utils.h:135
#define LOG_MAXCOUNT
Definition Utils.h:208
#define SOCKET
Definition Utils.h:134
CleanShutdown()
Default constructor; no side effects.
Definition Utils.cpp:35
~CleanShutdown()
Destroys all lazily-created global utility maps via ClearUtilsMaps().
Definition Utils.cpp:39
Callback interface for receiving log entries produced through LogSystem.
Definition Utils.h:256
virtual bool logEntry(LogEntry *entry)=0
Handle one log record.
char * logfile
Definition Utils.h:309
static bool SetLogFileOutput(const char *logfile, bool printOut=true)
Direct log output to a file.
Definition Utils.cpp:275
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
Definition Utils.cpp:169
bool printToStdOut
Definition Utils.h:310
uint8 logLevelVerbose[LOG_MAXCOUNT]
Definition Utils.h:306
static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring,...)
printf-style informational logging (usually invoked via the LogPrint macro).
Definition Utils.cpp:306
uint8 logLevelDebug[LOG_MAXCOUNT]
Definition Utils.h:307
static bool LogSystemDebug(uint32 source, uint8 subject, uint8 level, const char *formatstring,...)
printf-style debug logging (usually invoked via the LogDebug macro); same parameters as LogSystemPrin...
Definition Utils.cpp:354
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
Definition Utils.h:278
LogReceiver * logReceiverObj
Definition Utils.h:308
static bool SetLogLevelDebug(uint8 level)
Set the debug level threshold for all topics.
Definition Utils.cpp:180
static bool SetLogLevelVerbose(uint8 level)
Set the verbose (print) level threshold for all topics.
Definition Utils.cpp:204
Singleton snapshot of the parsed process command line (set via SetCommandLine()).
Definition Utils.h:1291
std::map< std::string, std::string > CommandLineArgs
Definition Utils.h:1300
static CommandLineInfo * CommandLineInfoSingleton
Definition Utils.h:1293
std::string CommandLineExecOnly
Definition Utils.h:1297
std::string CommandLineExecPath
Definition Utils.h:1298
std::vector< std::string > CommandLineItems
Definition Utils.h:1299
pthread_cond_t * event
Definition Utils.h:552
bool waitNext()
Block until the next signal() occurs.
Definition Utils.cpp:1578
Event()
Create an anonymous, process-local event.
Definition Utils.cpp:1495
bool signal()
Wake all threads currently waiting on this event.
Definition Utils.cpp:1602
pthread_mutex_t * mutex
Definition Utils.h:553
Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen).
Definition Utils.h:1331
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
Definition Utils.cpp:4715
static std::string patchLibraryFilename(const char *filename, const char *path=NULL)
Normalize a library name into a platform filename (adds lib prefix / .dll, .so, .dylib suffix and opt...
Definition Utils.cpp:4597
bool load(const char *filename)
Load a library.
Definition Utils.cpp:4627
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:463
Mutex()
Create an anonymous, process-local mutex.
Definition Utils.cpp:948
bool leave()
Release the mutex.
Definition Utils.cpp:1204
bool enter()
Block until the mutex is acquired.
Definition Utils.cpp:1059
pthread_mutex_t * mutex
Definition Utils.h:492
Counting semaphore, optionally named for cross-process use.
Definition Utils.h:502
Semaphore(uint32 maxCount=100)
Create an anonymous semaphore.
Definition Utils.cpp:1270
bool signal()
Increment (release) the semaphore, waking one waiter.
Definition Utils.cpp:1444
bool wait()
Block until the semaphore can be decremented.
Definition Utils.cpp:1375
bool getNextEntryDue(T &entry)
Pop the earliest entry if its due time has passed (non-blocking).
Definition Utils.h:903
uint32 getCount()
Number of scheduled entries.
Definition Utils.h:893
std::list< TimeQueueEntry< T > > internalList
Definition Utils.h:933
virtual bool clear()
Discard all scheduled entries.
Definition Utils.h:922
bool add(uint64 time, T entry)
Insert an entry sorted by its due time.
Definition Utils.h:872
T getNextEntryDue()
Pop the earliest due entry.
Definition Utils.h:945
virtual bool clear()
Delete every scheduled pointer and empty the queue.
Definition Utils.h:954
bool addTimer(uint32 id, uint32 interval, uint64 start=0, uint64 end=0)
Register a periodic timer.
Definition Utils.cpp:1672
static std::map< uint32, Timer * > * timers
Global registry mapping globalID to live Timer instances, used by the OS callbacks.
Definition Utils.h:646
bool triggerTimer(uint32 id)
Manually inject an expiry for timer id, as if it had fired now.
Definition Utils.cpp:1796
bool waitForTimer(uint32 timeout, uint32 &id, uint64 &time)
Wait for the next expiry of any registered timer.
Definition Utils.cpp:1818
bool removeTimer(uint32 id)
Unregister a timer and cancel its OS timer.
Definition Utils.cpp:1769
bool takeFirst(T &first)
Remove and return the front entry.
Definition Utils.h:739
bool waitForAndPeekFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and peek it without removal.
Definition Utils.h:753
bool add(T entry)
Append an entry and wake one waiting consumer.
Definition Utils.h:709
bool peekFirst(T &first)
Copy the front entry without removing it.
Definition Utils.h:727
std::queue< T > internalQueue
Definition Utils.h:817
bool waitForAndTakeFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and dequeue it.
Definition Utils.h:779
virtual bool clear()
Discard all queued entries.
Definition Utils.h:805
uint32 getCount()
Number of queued entries.
Definition Utils.h:718
T waitForAndTakeFirst(uint32 timeoutMS)
Convenience overload: dequeue with timeout, returning NULL instead of using an out-parameter.
Definition Utils.h:830
virtual bool clear()
Delete every queued pointer and empty the queue.
Definition Utils.h:839
Third-party (vendored): POSIX dirent (directory browsing) emulation for Win32 by Kevlin Henney (1997)...
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
Definition PsyTime.cpp:69
bool UnitTest_Utils()
Aggregate self test for miscellaneous utils functionality.
Definition Utils.cpp:1931
int64 AtomicDecrement64(int64 volatile &v)
Atomically decrement a 64-bit value.
Definition Utils.cpp:2820
uint32 NewProcess(const char *cmdline, const char *initdir=NULL, const char *title=NULL, int16 x=-1, int16 y=-1, int16 w=-1, int16 h=-1)
Launch a detached child process.
Definition Utils.cpp:4001
bool SetSharedSystemInstance(uint32 inst)
Set the instance number used to namespace shared OS objects, allowing several independent CMSDK syste...
Definition Utils.cpp:938
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
Definition Utils.cpp:3198
bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS=0)
Join a thread.
Definition Utils.cpp:3018
bool SignalSemaphore(const char *name)
Signal a named global semaphore.
Definition Utils.cpp:804
bool GetThreadPriority(ThreadHandle hThread, uint16 priority)
Query a thread's scheduling priority.
Definition Utils.cpp:3590
std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
Definition Utils.h:589
int FromOSPriority(int pri)
Map a native OS priority back to the CMSDK priority scale.
Definition Utils.cpp:3680
bool EndProcess(uint32 proc)
Forcibly terminate a child process.
Definition Utils.cpp:4188
std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
Definition Utils.h:592
static Mutex * SharedMemorySemaphoreMapMutex
Definition Utils.h:590
bool GetLastOccupiedBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the highest set (occupied) bit.
Definition Utils.cpp:2717
const char * laststrstr(const char *str1, const char *str2)
Find the last occurrence of str2 in str1.
Definition Utils.cpp:7441
std::pair< std::string, Event * > SharedMemoryEventMapPair
Definition Utils.h:595
bool DestroyEvent(const char *name)
Destroy a named global event.
Definition Utils.cpp:917
bool WaitForSemaphore(const char *name, uint32 ms, bool autocreate=true)
Wait on a named global semaphore.
Definition Utils.cpp:765
static SharedMemoryFileHandleMapType * SharedMemoryFileHandleMap
Definition Utils.h:395
bool TextStartsWith(const char *str, const char *start, bool caseSensitive=true)
Test whether str starts with start.
Definition Utils.cpp:7498
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:2830
bool SetThreadPriority(ThreadHandle hThread, uint16 priority)
Set a thread's scheduling priority.
Definition Utils.cpp:3613
bool WaitNextEvent(const char *name, uint32 ms, bool autocreate=true)
Wait for the next signal on a named global event.
bool GetProcAndOSCPUUsage(double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks)
Sample CPU usage of this process and of the whole OS since the previous call.
Definition Utils.cpp:3415
bool PauseThread(ThreadHandle hThread)
Suspend a thread's execution.
Definition Utils.cpp:3098
static std::map< std::string, Event * > * SharedMemoryEventMap
Definition Utils.h:594
bool MoveConsoleWindow(int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
Move/resize the console window.
Definition Utils.cpp:3762
bool IsThreadRunning(ThreadHandle hThread)
Check whether a thread is still alive.
Definition Utils.cpp:3168
bool CreateThread(THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
Start a new OS thread.
Definition Utils.cpp:2896
int32 AtomicDecrement32(int32 volatile &v)
Atomically decrement a 32-bit value.
Definition Utils.cpp:2810
static std::map< uint32, DrumBeatInfo > * DrumBeatMap
Definition Utils.h:441
bool SignalThread(ThreadHandle hThread, int32 signal)
Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).
Definition Utils.cpp:3704
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
Definition Utils.cpp:2287
int64 AtomicIncrement64(int64 volatile &v)
Atomically increment a 64-bit value.
Definition Utils.cpp:2800
uint32 GetSharedSystemInstance()
Get the current shared-system instance number.
Definition Utils.cpp:943
bool StopDrumBeat(uint32 id)
Stop a running drum beat without destroying it.
Definition Utils.cpp:581
uint32 NewProcessEx(const char *cmdline, const char *initdir, const char *title, const std::map< std::string, std::string > *env, bool captureOutput, bool ignoreOutput, bool newProcessGroup)
Launch a child with environment overrides and optional output capture.
Definition Utils.cpp:4222
bool EnterMutex(const char *name, uint32 ms, bool autocreate=true)
Acquire a named global mutex, creating it on first use.
Definition Utils.cpp:649
const char * laststristr(const char *str1, const char *str2)
Case-insensitive laststrstr().
Definition Utils.cpp:7466
static Mutex * SharedMemoryMutexMapMutex
Definition Utils.h:587
#define SharedMemoryFileHandleMapType
Definition Utils.h:393
bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false)
Create a periodic timer ("drum beat") that calls func every interval ms.
Definition Utils.cpp:482
bool ReapThread(ThreadHandle &hThread)
Definition Utils.cpp:2976
std::string PrintProgramTrace(uint32 startLine=0, uint32 endLine=0)
Format the current call stack as printable text.
Definition Utils.cpp:2840
uint8 GetProcessStatus(uint32 proc, int &returncode)
Poll a child started with NewProcess().
Definition Utils.cpp:4128
bool(* DrumBeatFunc)(uint32 id, uint32 count)
Callback invoked on every drum-beat tick.
Definition Utils.h:418
static Mutex * SharedMemoryEventMapMutex
Definition Utils.h:593
Semaphore * GetSemaphore(const char *name, bool autocreate=true)
Look up (and optionally create) a named semaphore in the global registry.
Definition Utils.cpp:726
bool LeaveMutex(const char *name)
Release a named global mutex previously acquired with EnterMutex().
Definition Utils.cpp:689
int RunOSCommand(const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString)
Run a command synchronously and capture its output.
Definition Utils.cpp:3808
char * CreateSharedMemorySegment(const char *name, uint64 size, bool force=false)
Create a named shared memory segment and map it into this process.
Definition Utils.cpp:2166
std::string PrintBitFieldString(const char *bitfield, uint32 bytesize, uint32 size, const char *title)
Like GetBitFieldAsString() but prefixed with title and formatted for printing.
Definition Utils.cpp:2761
std::string GetBitFieldAsString(const char *bitfield, uint32 bytesize, uint32 size)
Render the first size bits as a '0'/'1' string, for debugging.
Definition Utils.cpp:2742
uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode)
Wait for a child to exit.
Definition Utils.cpp:4395
uint32 GetLocalProcessID()
Get the OS process id of the current process.
Definition Utils.cpp:3799
bool EndDrumBeat(uint32 id)
Destroy a drum beat and release its OS timer.
Definition Utils.cpp:614
bool DestroySemaphore(const char *name)
Destroy a named global semaphore.
Definition Utils.cpp:836
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
Definition Utils.cpp:2402
bool TerminateThread(ThreadHandle hThread)
Forcibly kill a thread.
Definition Utils.cpp:3068
bool GetFirstFreeBitLocN(const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
Find the first run of num consecutive 0 bits.
Definition Utils.cpp:2496
bool GetCurrentThreadUniqueID(uint32 &tid)
Get a process-unique id for the calling thread.
Definition Utils.cpp:3118
int32 AtomicIncrement32(int32 volatile &v)
Atomically increment a 32-bit value.
Definition Utils.cpp:2790
bool GetDesktopSize(uint32 &width, uint32 &height)
Get the primary desktop resolution.
Definition Utils.cpp:3720
bool CheckForThreadFinished(ThreadHandle hThread)
Non-blocking check whether a thread has terminated.
Definition Utils.cpp:2942
bool DestroyMutex(const char *name)
Destroy a named global mutex and remove it from the registry.
Definition Utils.cpp:702
bool ContinueThread(ThreadHandle hThread)
Resume a thread paused with PauseThread().
Definition Utils.cpp:3107
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
Definition Utils.cpp:6293
std::list< std::string > GetProgramTrace()
Capture the current call stack.
Definition Utils.cpp:2855
uint64 hton64(const uint64_t *input)
Convert a 64-bit value from host to network byte order.
static uint16 SharedSystemInstance
Definition Utils.h:397
static void TimerCallback(int sig, siginfo_t *siginfo, void *context)
POSIX signal-based timer callback trampoline (SIGEV_SIGNAL); routes the expiry into the owning Timer'...
Definition Utils.cpp:1854
void PrintBinary(void *p, uint32 size, bool asInt, const char *title)
Hex/decimal dump a memory region to stdout for debugging.
Definition Utils.cpp:6258
static std::map< std::string, Mutex * > * SharedMemoryMutexMap
Definition Utils.h:588
bool GetFirstFreeBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the first 0 (free) bit.
Definition Utils.cpp:2473
bool SignalEvent(const char *name)
Signal a named global event.
Definition Utils.cpp:904
bool GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
Definition Utils.cpp:3210
bool GetNextLineEnd(const char *str, uint32 size, uint32 &len, uint32 &crSize)
Find the end of the current line.
Definition Utils.cpp:6332
bool GetBit(uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
Read bit loc.
Definition Utils.cpp:2692
uint64 ntoh64(const uint64 *input)
Convert a 64-bit value from network to host byte order.
Definition Utils.cpp:2442
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
Definition Utils.cpp:3368
bool ReadProcessOutput(uint32 proc, std::string &out, std::string &err)
Read any pending captured stdout/stderr from a child launched with captureOutput=true.
Definition Utils.cpp:4357
int ToOSPriority(int pri)
Map a CMSDK priority value to the platform's native priority scale.
Definition Utils.cpp:3632
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap
Definition Utils.h:591
bool SendProcessBreak(uint32 proc, int sig)
Attempt a graceful stop: POSIX sends the given signal; Windows posts a CTRL_BREAK to the child's proc...
Definition Utils.cpp:4384
bool SetBitN(uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
Set num consecutive bits starting at loc to value.
Definition Utils.cpp:2629
bool Reset32BitField(char *bitfield, uint32 bytesize)
Zero the whole bitfield, marking every bit as free.
Definition Utils.cpp:2467
bool StartDrumBeat(uint32 id)
Start (or resume) a previously created drum beat.
Definition Utils.cpp:535
bool TextEndsWith(const char *str, const char *end, bool caseSensitive=true)
Test whether str ends with end.
Definition Utils.cpp:7491
bool UnitTest_Timer()
Self test for the Timer class.
Definition Utils.cpp:1867
bool SetBit(uint32 loc, bit value, char *bitfield, uint32 bytesize)
Set bit loc to value.
Definition Utils.cpp:2597
bool GetCurrentThread(ThreadHandle &thread)
Get the handle of the calling thread.
Definition Utils.cpp:3158
bool RenameConsoleWindow(const char *name, bool prepend=false)
Set the console window title.
Definition Utils.cpp:3740
bool TryReapThread(ThreadHandle &hThread)
Definition Utils.cpp:2992
bool UtilsTest()
Run the built-in self test of the utils module.
Definition Utils.cpp:6216
uint32 Calc32BitFieldSize(uint32 bitsize)
Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.
Definition Utils.cpp:2463
uint32 TextReplaceCharsInPlace(char *str, uint32 size, char find, char replace)
Replace every occurrence of a character, in place.
Definition Utils.cpp:7430
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:6314
bool GetOSCPUUsage(double &percentUse)
Get the instantaneous total OS CPU usage.
Definition Utils.cpp:3533
bool GetCurrentThreadOSID(uint32 &tid)
Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
Definition Utils.cpp:3138
bool SeedRandomValues(uint32 seedvalue=0)
Seed the pseudo-random generator.
Definition Utils.cpp:7930
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
Definition Utils.cpp:5500
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
Definition Utils.cpp:5510
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
Definition Utils.cpp:6610
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
Definition Utils.cpp:7018
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
Definition Utils.cpp:5912
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
Definition Utils.cpp:7854
unsigned char * Ascii2UTF16LE(const char *ascii, uint32 len, uint32 &size)
Convert 8-bit ASCII text to UTF-16LE (used for Windows wide APIs and some protocols).
Definition Utils.cpp:5345
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
Definition Utils.cpp:4815
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
Definition Utils.cpp:6495
uint64 ReadRegistryQWORD(const char *key, const char *entry)
Read a 64-bit registry value.
std::string GetCommandLineArg(uint16 n)
Get the n-th positional command line item.
Definition Utils.cpp:4556
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
Definition Utils.cpp:7311
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
Definition Utils.cpp:8077
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
Definition Utils.cpp:7263
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
Definition Utils.cpp:7404
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
Definition Utils.cpp:4550
uint16 GetCPUArchitecture()
CPU architecture id.
Definition Utils.cpp:4906
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:7055
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:6824
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:6365
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
Definition Utils.cpp:7037
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
Definition Utils.cpp:5558
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
Definition Utils.cpp:5838
const char * GetSystemArchitecture()
Architecture name string, e.g.
Definition Utils.cpp:5054
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:6427
std::string GetCommandLinePath()
Get the directory portion of the executable path.
Definition Utils.cpp:4510
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
Definition Utils.cpp:4568
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
Definition Utils.cpp:5607
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
Definition Utils.cpp:7784
uint64 GetCPUSpeed()
Nominal CPU clock speed.
Definition Utils.cpp:4943
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
Definition Utils.cpp:6515
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
Definition Utils.cpp:6797
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
Definition Utils.cpp:7163
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
Definition Utils.cpp:6377
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
Definition Utils.cpp:7010
char * GetFileList(const char *dirname, const char *ext, uint32 &count, bool fullpath, uint32 maxNameLen=256)
List files in a directory matching an extension.
Definition Utils.cpp:7551
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
Definition Utils.cpp:6168
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
Definition Utils.cpp:7215
uint32 StringMultiReplace(std::string &text, std::map< std::string, std::string > &map, bool onlyFirst)
Apply many key→value replacements in one pass.
Definition Utils.cpp:6920
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
Definition Utils.cpp:6769
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
Definition Utils.cpp:7708
uint16 GetCPUCount()
Number of logical CPU cores.
Definition Utils.cpp:4887
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
Definition Utils.cpp:5321
std::map< std::string, std::string > TextMapSplit(const char *text, const char *outersplit, const char *innersplit)
Split "k=v<sep>k=v..." text into a map (later duplicates overwrite earlier ones).
Definition Utils.cpp:6469
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
Definition Utils.cpp:4847
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
Definition Utils.cpp:6535
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
Definition Utils.cpp:7794
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
Definition Utils.cpp:8348
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
Definition Utils.cpp:5766
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
Definition Utils.cpp:6388
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
Definition Utils.cpp:5143
uint32 StringScriptReplace(std::string &text, std::string name, std::list< std::map< std::string, std::string > > &list)
Expand a named repeating template block in text once per map in list, substituting each map's keys in...
Definition Utils.cpp:6954
std::string TextJoinXML(std::map< std::string, std::string > &map, const char *innernodeName, const char *outernodeName)
Serialize a map as XML, one innernodeName element per pair inside an outernodeName element.
Definition Utils.cpp:6751
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
Definition Utils.cpp:4463
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
Definition Utils.cpp:6902
uint64 GetSystemMemorySize()
Total physical RAM installed.
Definition Utils.cpp:4990
uint32 ReadRegistryDWORD(const char *key, const char *entry)
Read a 32-bit registry value.
bool GetLocalMACAddress(uint64 &address)
Get the primary local MAC address.
Definition Utils.cpp:5826
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
Definition Utils.cpp:5526
FileDetails GetFileDetails(const char *filename)
Stat a file.
Definition Utils.cpp:7622
double RandomValue()
Uniform random double in [0,1).
Definition Utils.cpp:7936
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
Definition Utils.cpp:5364
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
Definition Utils.cpp:4533
std::multimap< std::string, std::string > TextMultiMapSplit(const char *text, const char *outersplit, const char *innersplit)
Split "k=v<sep>k=v..." text into a multimap (duplicate keys preserved).
Definition Utils.cpp:6442
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
Definition Utils.cpp:5880
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
Definition Utils.cpp:5698
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
Definition Utils.cpp:7689
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:5619
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
Definition Utils.cpp:5294
std::string GetLocalHostnameString()
Local hostname as std::string.
Definition Utils.cpp:5754
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
Definition Utils.cpp:7774
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
Definition Utils.cpp:7617
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
Definition Utils.cpp:6022
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
Definition Utils.cpp:6409
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
Definition Utils.cpp:7002
bool DeleteAFile(const char *filename, bool force)
Delete a file.
Definition Utils.cpp:7191
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
Definition Utils.cpp:7195
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
Definition Utils.cpp:7982
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
Definition Utils.cpp:4527
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
Definition Utils.cpp:6854
std::vector< std::string > TextListSplitLines(const char *text, bool keepEmpty=true, bool autoTrim=false)
Split text into lines, handling both \n and \r\n.
Definition Utils.cpp:6592
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:7135
std::string GetCurrentDir()
Current working directory.
Definition Utils.cpp:7538
std::string GetCommandLine()
Get the full original command line as one string.
Definition Utils.cpp:4504
std::string ReadRegistryString(const char *key, const char *entry)
Read a string registry value.
std::vector< std::string > TextCommandlineSplit(const char *cmdline)
Split a command line into arguments, honouring quoting rules.
Definition Utils.cpp:6542
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
Definition Utils.cpp:7612
bool DeleteRegistryEntry(const char *key, const char *entry)
Delete a single value from a key.
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:6884
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
Definition Utils.cpp:5595
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
Definition Utils.cpp:7337
bool WriteRegistryQWORD(const char *key, const char *entry, uint64 value)
Write a 64-bit registry value.
char * ReadAFile(const char *filename, uint32 &length, bool binary=false)
Read an entire file into a new buffer.
Definition Utils.cpp:7076
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
Definition Utils.cpp:7738
uint64 AsciiHex2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit hexadecimal integer (with or without 0x) from a substring.
Definition Utils.cpp:7756
const char * GetFileBasename(const char *filename)
Filename portion of a path.
Definition Utils.cpp:7522
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
Definition Utils.cpp:4750
bool WriteRegistryString(const char *key, const char *entry, const char *value)
Write a string registry value.
bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM)
Query total and free physical memory.
Definition Utils.cpp:5013
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:7720
bool WriteRegistryDWORD(const char *key, const char *entry, uint32 value)
Write a 32-bit registry value (creates the key when needed).
std::string TextJoinJSON(std::map< std::string, std::string > &map)
Serialize a map as a JSON object (keys/values escaped).
Definition Utils.cpp:6735
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
Definition Utils.cpp:8351
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
Definition Utils.h:1286
bool DeleteRegistryTree(const char *root, const char *key)
Recursively delete a key and all subkeys.
std::string TextLowercase(const char *text)
Convert to lower case (ASCII/current locale).
Definition Utils.cpp:6371
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
Definition Utils.cpp:7815
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
Definition Utils.cpp:6351
const char * GetComputerName()
Get this machine's hostname.
Definition Utils.cpp:4768
std::string GetFilePath(const char *filename)
Directory portion of a path.
Definition Utils.cpp:7506
const char * GetSystemOSName()
OS name string, e.g.
Definition Utils.cpp:5115
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
Definition Utils.cpp:8019
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
Definition Utils.cpp:5853
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
Definition Utils.cpp:7804
std::string TextJoin(std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
Join vector elements with split.
Definition Utils.cpp:6688
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
Definition Utils.cpp:7973
std::string BytifyRate(double val)
Format a byte rate, e.g.
Definition Utils.cpp:8065
bool ClearUtilsMaps()
Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps).
Definition Utils.cpp:49
uint32 GetDataTypeID(const char *typeName)
Inverse of GetDataTypeName(): look up the numeric datatype id for a type name.
Definition Utils.cpp:142
std::string GetDataTypeName(uint32 datatype)
Translate a CMSDK datatype id (e.g.
Definition Utils.cpp:117
Wire/storage layout of one log record: fixed header immediately followed by the message text.
Definition Utils.h:228
uint32 source
Definition Utils.h:232
uint32 size
Definition Utils.h:229
std::string toJSON()
Serialize the entry (header fields + text) as a JSON object string.
Definition Utils.cpp:258
uint8 level
Definition Utils.h:234
uint64 time
Definition Utils.h:231
bool setText(char *text, uint32 len)
Copy len bytes of text into the payload area and update size.
Definition Utils.cpp:247
uint8 subject
Definition Utils.h:233
uint8 type
Definition Utils.h:235
uint32 cid
Definition Utils.h:230
const char * getText(uint32 &len)
Access the text payload stored after the header.
Definition Utils.cpp:240
std::string toXML()
Serialize the entry as an XML fragment.
Definition Utils.cpp:266
Bookkeeping record for one periodic "drum beat" timer.
Definition Utils.h:423
Existence, type, permission and timestamp information for one file, as returned by GetFileDetails().
Definition Utils.h:1700
Description of one local network interface (IPv4 address, MAC and names).
Definition Utils.h:1441
char friendlyName[MAXKEYNAMELEN+1]
Definition Utils.h:1445
char name[MAXKEYNAMELEN+1]
Definition Utils.h:1444
One (time, entry) pair inside a TimeQueue.
Definition Utils.h:858
uint64 time
Definition Utils.h:859
T entry
Definition Utils.h:860
One scheduled entry inside a Timer: id, active window and platform timer handle.
Definition Utils.h:614
A single timer expiry: which timer fired and when.
Definition Utils.h:632