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#else
615 ProcessData() { outFD = -1; errFD = -1; }
616 int outFD;
617 int errFD;
618};
619static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
620typedef std::pair <uint32, ProcessData*> Proc_Pair;
621#endif
622
625
628 uint32 globalID;
629 uint32 id;
630 uint64 start;
631 uint64 end;
632 uint32 interval;
633 #ifdef WINDOWS
634 HANDLE handle;
635 #else
636 #ifdef __APPLE__
637 dispatch_source_t handle;
638 #else
639 timer_t handle;
640 #endif
641 #endif
642};
643
646 uint32 id;
647 uint64 time;
648};
649
656class Timer {
657public:
659 static std::map<uint32, Timer*>* timers;
660
661 Timer();
662 ~Timer();
663
670 bool addTimer(uint32 id, uint32 interval, uint64 start = 0, uint64 end = 0);
672 bool triggerTimer(uint32 id);
678 bool waitForTimer(uint32 timeout, uint32& id, uint64& time);
680 bool removeTimer(uint32 id);
681
682private:
683 uint32 globalID;
684 Mutex mutex;
685 Semaphore semaphore;
686 std::queue<TimerTrigger*> triggers;
687 std::map<uint32, TimerSchedule*> schedules;
688 std::list<TimerSchedule*> oldSchedules;
689};
690
691#ifdef WINDOWS
693 void CALLBACK TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired);
694#else
696 static void TimerCallback(int sig, siginfo_t *siginfo, void *context);
697#endif
699bool UnitTest_Timer();
701bool UnitTest_Utils();
702
704// Wait Queue //
706
715template <typename T>
717public:
719 virtual ~WaitQueue() {}
720
722 bool add(T entry) {
723 if (!mutex.enter(200, __FUNCTION__))
724 return false;
725 internalQueue.push(entry);
726 semaphore.signal();
727 mutex.leave();
728 return true;
729 }
730
731 uint32 getCount() {
732 uint32 size;
733 if (!mutex.enter(200, __FUNCTION__))
734 return 0;
735 size = (uint32)internalQueue.size();
736 mutex.leave();
737 return size;
738 }
739
740 bool peekFirst(T& first) {
741 if (!mutex.enter(200, __FUNCTION__))
742 return false;
743 if (!internalQueue.size()) {
744 mutex.leave();
745 return false;
746 }
747 first = internalQueue.front();
748 mutex.leave();
749 return true;
750 }
751
752 bool takeFirst(T& first) {
753 if (!mutex.enter(200, __FUNCTION__))
754 return false;
755 if (!internalQueue.size()) {
756 mutex.leave();
757 return false;
758 }
759 first = internalQueue.front();
760 internalQueue.pop();
761 mutex.leave();
762 return true;
763 }
764
766 bool waitForAndPeekFirst(T& first, uint32 timeoutMS) {
767 if (!mutex.enter(200, __FUNCTION__))
768 return false;
769 if (internalQueue.size()) {
770 first = internalQueue.front();
771 mutex.leave();
772 return true;
773 }
774 mutex.leave();
775 if (!semaphore.wait(timeoutMS))
776 return false;
777 if (!mutex.enter(200, __FUNCTION__))
778 return false;
779 if (internalQueue.size()) {
780 first = internalQueue.front();
781 mutex.leave();
782 return true;
783 }
784 else {
785 mutex.leave();
786 return false;
787 }
788 }
789
792 bool waitForAndTakeFirst(T& first, uint32 timeoutMS) {
793 if (!mutex.enter(200, __FUNCTION__))
794 return false;
795 if (internalQueue.size()) {
796 first = internalQueue.front();
797 internalQueue.pop();
798 mutex.leave();
799 return true;
800 }
801 mutex.leave();
802 if (!semaphore.wait(timeoutMS))
803 return false;
804 if (!mutex.enter(200, __FUNCTION__))
805 return false;
806 if (internalQueue.size()) {
807 first = internalQueue.front();
808 internalQueue.pop();
809 mutex.leave();
810 return true;
811 }
812 else {
813 mutex.leave();
814 return false;
815 }
816 }
817
818 virtual bool clear() {
819 if (!mutex.enter(200, __FUNCTION__))
820 return false;
821 std::queue<T> empty;
822 std::swap(internalQueue, empty);
823 mutex.leave();
824 return true;
825 }
826
827protected:
830 std::queue<T> internalQueue;
831};
832
835template <typename T>
836class WaitQueuePointer : public WaitQueue<T> {
837public:
839 virtual ~WaitQueuePointer() { clear(); }
840
843 T waitForAndTakeFirst(uint32 timeoutMS) {
844 T first;
845 if (WaitQueue<T>::waitForAndTakeFirst(first, timeoutMS))
846 return first;
847 else
848 return NULL;
849 }
850
852 virtual bool clear() {
853 if (!WaitQueue<T>::mutex.enter(200, __FUNCTION__))
854 return false;
855 while (WaitQueue<T>::internalQueue.size()) {
856 delete(WaitQueue<T>::internalQueue.front());
858 }
859 WaitQueue<T>::mutex.leave();
860 return true;
861 }
862};
863
864
866// Time Queue //
868
870template <typename T>
872 uint64 time;
874};
875
878template <typename T>
880public:
882 virtual ~TimeQueue() {}
883
885 bool add(uint64 time, T entry) {
886 if (!mutex.enter(200, __FUNCTION__))
887 return false;
888 TimeQueueEntry<T> newEntry;
889 newEntry.time = time;
890 newEntry.entry = entry;
891 typename std::list< TimeQueueEntry<T> >::iterator i = internalList.begin(),
892 e = internalList.end();
893 while (i != e) {
894 if (time < (*i).time) {
895 internalList.insert(i, newEntry);
896 mutex.leave();
897 return true;
898 }
899 i++;
900 }
901 internalList.push_back(newEntry);
902 mutex.leave();
903 return true;
904 }
905
906 uint32 getCount() {
907 uint32 size;
908 if (!mutex.enter(200, __FUNCTION__))
909 return 0;
910 size = (uint32)internalList.size();
911 mutex.leave();
912 return size;
913 }
914
916 bool getNextEntryDue(T& entry) {
917 if (!mutex.enter(200, __FUNCTION__))
918 return false;
919 if (!internalList.size()) {
920 mutex.leave();
921 return false;
922 }
923 uint64 now = GetTimeNow();
924 TimeQueueEntry<T> first = internalList.front();
925 if (first.time < now) {
926 internalList.pop_front();
927 entry = first.entry;
928 mutex.leave();
929 return true;
930 }
931 mutex.leave();
932 return false;
933 }
934
935 virtual bool clear() {
936 if (!mutex.enter(200, __FUNCTION__))
937 return false;
938 std::list< TimeQueueEntry<T> > empty;
939 std::swap(internalList, empty);
940 mutex.leave();
941 return true;
942 }
943
944protected:
946 std::list< TimeQueueEntry<T> > internalList;
947};
948
951template <typename T>
952class TimeQueuePointer : public TimeQueue<T> {
953public:
955 virtual ~TimeQueuePointer() { clear(); }
956
959 T first;
961 return first;
962 else
963 return NULL;
964 }
965
967 virtual bool clear() {
968 if (!TimeQueue<T>::mutex.enter(200, __FUNCTION__))
969 return false;
970 typename std::list< TimeQueueEntry<T> >::iterator i = TimeQueue<T>::internalList.begin(),
972 while (i != e) {
973 delete((*i).entry);
974 i++;
975 }
977 TimeQueue<T>::mutex.leave();
978 return true;
979 }
980};
981
982
984// Shared Memory //
986
988
994
1000char* CreateSharedMemorySegment(const char* name, uint64 size, bool force = false);
1004char* OpenSharedMemorySegment(const char* name, uint64 size);
1008bool CloseSharedMemorySegment(char* data, uint64 size);
1009// Destroy named shared memory segment
1010// bool DestroySharedMemorySegment(char* data, uint32 size);
1011
1013
1018
1020uint64 ntoh64(const uint64 *input);
1022uint64 hton64(const uint64_t *input);
1023
1026uint32 Calc32BitFieldSize(uint32 bitsize);
1028bool Reset32BitField(char* bitfield, uint32 bytesize);
1032bool GetFirstFreeBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1036bool GetFirstFreeBitLocN(const char* bitfield, uint32 bytesize, uint32 num, uint32& loc);
1038bool SetBit(uint32 loc, bit value, char* bitfield, uint32 bytesize);
1041bool SetBitN(uint32 loc, uint32 num, bit value, char* bitfield, uint32 bytesize);
1043bool GetBit(uint32 loc, const char* bitfield, uint32 bytesize, bit& val);
1045bool GetLastOccupiedBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1046
1049std::string GetBitFieldAsString(const char* bitfield, uint32 bytesize, uint32 size);
1052std::string PrintBitFieldString(const char* bitfield, uint32 bytesize, uint32 size, const char* title);
1053
1055
1056
1058// Threading //
1060
1063
1067std::string PrintProgramTrace(uint32 startLine = 0, uint32 endLine = 0);
1069std::list<std::string> GetProgramTrace();
1070
1072int32 AtomicIncrement32(int32 volatile &v);
1074int64 AtomicIncrement64(int64 volatile &v);
1076int32 AtomicDecrement32(int32 volatile &v);
1078int64 AtomicDecrement64(int64 volatile &v);
1079
1081bool Sleep(uint32 ms);
1082
1089bool CreateThread(THREAD_FUNCTION func, void* args, ThreadHandle& thread, uint32 &osID);
1090
1092bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS = 0);
1093bool ReapThread(ThreadHandle& hThread);
1094bool TryReapThread(ThreadHandle& hThread);
1095
1098
1101bool TerminateThread(ThreadHandle hThread);
1102
1105bool PauseThread(ThreadHandle hThread);
1106
1108bool ContinueThread(ThreadHandle hThread);
1109
1111bool GetCurrentThreadUniqueID(uint32 &tid);
1112
1114bool GetCurrentThreadOSID(uint32 &tid);
1115
1117bool GetCurrentThread(ThreadHandle& thread);
1118
1120bool IsThreadRunning(ThreadHandle hThread);
1121
1125
1126#if defined WINDOWS
1127 #define FileTimeToUint64(ft) (((uint64)(ft.dwHighDateTime))<<32)|((uint64)ft.dwLowDateTime)
1128#endif
1129
1133bool GetCPUTicks(ThreadHandle hThread, uint64& ticks);
1134
1136bool GetCPUTicks(uint64& ticks);
1137
1139bool GetProcessCPUTicks(uint64& ticks);
1140
1142bool GetProcessCPUTicks(uint32 osProcID, uint64& ticks);
1143
1151bool GetProcAndOSCPUUsage(double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1152
1160bool GetProcAndOSCPUUsage(uint32 osProcID, double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1161
1163bool GetOSCPUUsage(double& percentUse);
1164
1166bool GetThreadPriority(ThreadHandle hThread, uint16 priority);
1167
1169bool SetThreadPriority(ThreadHandle hThread, uint16 priority);
1170
1172int ToOSPriority(int pri);
1173
1175int FromOSPriority(int pri);
1176
1178bool SignalThread(ThreadHandle hThread, int32 signal);
1179
1181
1183// Desktop //
1185
1188
1190bool GetDesktopSize(uint32& width, uint32& height);
1191
1193bool RenameConsoleWindow(const char* name, bool prepend = false);
1194
1196bool MoveConsoleWindow(int32 x = -1, int32 y = -1, int32 w = -1, int32 h = -1);
1197
1199
1201// Processes //
1203
1204#define PROC_ERROR 0
1205#define PROC_TERMINATED 1
1206#define PROC_NOTSTARTED 2
1207#define PROC_RUNNING 3
1208#define PROC_TIMEOUT 4
1209
1210#define NUM_PIPES 2
1211#define PARENT_WRITE_PIPE 0
1212#define PARENT_READ_PIPE 1
1213/* always in a pipe[], pipe[0] is for read and
1214 pipe[1] is for write */
1215#define READ_FD 0
1216#define WRITE_FD 1
1217#define PARENT_READ_FD ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
1218#define PARENT_WRITE_FD ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
1219#define CHILD_READ_FD ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
1220#define CHILD_WRITE_FD ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
1221
1222#define PROCBUFSIZE 4096
1223
1226
1234int RunOSCommand(const char* cmdline, const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString);
1239uint32 NewProcess(const char* cmdline, const char* initdir = NULL, const char* title = NULL,
1240 int16 x = -1, int16 y = -1, int16 w = -1, int16 h = -1);
1244uint8 GetProcessStatus(uint32 proc, int &returncode);
1246bool EndProcess(uint32 proc);
1247
1267uint32 NewProcessEx(const char* cmdline, const char* initdir, const char* title,
1268 const std::map<std::string, std::string>* env,
1269 bool captureOutput, bool ignoreOutput, bool newProcessGroup,
1270 int posixParentDeathSig = 0, bool posixUseShell = false);
1275bool ReadProcessOutput(uint32 proc, std::string& out, std::string& err);
1281void ReleaseProcessCapture(uint32 proc);
1286bool SendProcessBreak(uint32 proc, int sig);
1291uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode);
1293uint32 GetLocalProcessID();
1294
1296
1298// DLL Libraries //
1300
1301#ifdef WINDOWS
1302 #define DLLHandle HINSTANCE
1303#else // WINDOWS
1304 #define DLLHandle void*
1305#endif // WINDOWS
1306
1309
1311typedef int (* LibraryFunction)();
1312
1313class CommandLineInfo;
1317public:
1321 std::string CommandLineExec;
1324 std::vector<std::string> CommandLineItems;
1325 std::map<std::string, std::string> CommandLineArgs;
1326};
1327
1328
1329
1333bool SetCommandLine(int argc, char* argv[]);
1335std::string GetCommandLine();
1337std::string GetCommandLinePath();
1339std::string GetCommandLineExecutable();
1341std::string GetCommandLineExecutableOnly();
1343uint32 GetCommandLineArgCount();
1345std::string GetCommandLineArg(uint16 n);
1349std::string GetCommandLineArg(const char* key);
1353bool HasCommandLineArg(const char* key, std::string& value);
1354
1356class Library {
1357public:
1360 static std::string patchLibraryFilename(const char* filename, const char* path = NULL);
1361
1362 Library();
1363 ~Library();
1365 bool load(const char* filename);
1367 LibraryFunction getFunction(const char* funcName);
1368private:
1369 DLLHandle handle;
1370};
1371
1373Library* OpenLibrary(const char* libName);
1374
1376
1379
1381const char* GetComputerName();
1382
1384uint64 GetProcessMemoryUsage();
1387
1389uint16 GetCPUCount();
1390
1392uint16 GetCPUArchitecture();
1393
1395uint64 GetCPUSpeed();
1396
1398uint64 GetSystemMemorySize();
1399
1401bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM);
1402
1404const char* GetSystemArchitecture();
1405
1407const char* GetSystemOSName();
1408
1413bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build, char* text, uint16 textSize);
1414
1416
1417//bool RunOSTextCommand(const char* cmd, char* result, uint32 size);
1418
1419//extern char OSLocalHostName[1024];
1420//extern char OSArchitectureName[1024];
1421//extern char OSName[1024];
1422
1423
1425// Sockets //
1427
1433
1434#ifdef WINDOWS
1436 bool CheckNetworkInit();
1437 #define CHECKNETWORKINIT utils::CheckNetworkInit();
1438#else
1439 #define CHECKNETWORKINIT
1440 #define WSAEWOULDBLOCK EAGAIN
1441#endif
1442
1448bool GetSocketError(int wsaError, char* errorString, uint16 errorStringMaxSize, bool* isRecoverable);
1449
1453std::string GetLastOSErrorMessage();
1454
1456bool WaitForSocketReadability(SOCKET s, int32 timeout);
1458bool WaitForSocketWriteability(SOCKET s, int32 timeout);
1459
1464
1472
1474bool LookupIPAddress(const char* name, uint32& address);
1476bool LookupHostname(uint32 address, char* name, uint32 maxSize);
1478std::string GetLocalHostnameString();
1480bool GetLocalHostname(char* name, uint32 maxSize);
1482bool IsLocalIPAddress(const char* addr);
1484bool IsLocalIPAddress(uint32& address);
1486bool GetLocalIPAddress(uint32& address);
1488uint32* GetLocalIPAddresses(uint32& count);
1490bool GetLocalMACAddress(uint64& address);
1492uint64* GetLocalMACAddresses(uint32& count);
1496bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort);
1497
1498#define LOCALHOSTIP 16777343 // 127.0.0.1 as 32-bit dec
1499#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
1500#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
1501
1502#define GETIPPORT(a) *(uint16*)((char*)&a + sizeof(uint32))
1503#define GETIPADDRESS(a) *(uint32*)&a
1504#define GETIPADDRESSPORT(a,p) (((uint32)a)) | (((uint64)p)<<32)
1505#define GETIPADDRESSQUAD(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3]
1506#define GETIPADDRESSQUADPORT(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3], ((uint16*)&a)[2]
1507
1509
1514
1515#ifdef WINDOWS
1517 std::string GetRegistryKeyInfo(const char* key, HKEY &hKeyRoot);
1519 std::string GetRegistryParentKeyInfo(const char* key, HKEY &hKeyRoot);
1520#endif // WINDOWS
1522uint32 ReadRegistryDWORD(const char* key, const char* entry);
1524uint64 ReadRegistryQWORD(const char* key, const char* entry);
1526std::string ReadRegistryString(const char* key, const char* entry);
1528bool WriteRegistryDWORD(const char* key, const char* entry, uint32 value);
1530bool WriteRegistryQWORD(const char* key, const char* entry, uint64 value);
1532bool WriteRegistryString(const char* key, const char* entry, const char* value);
1534bool DeleteRegistryEntry(const char* key, const char* entry);
1536bool DeleteRegistryKey(const char* key);
1538bool DeleteRegistryTree(const char* root, const char* key);
1539//bool CopyRegistryKey(const char* key, const char* newName);
1541bool CopyRegistryTree(const char* entry, const char* newName);
1542//bool RenameRegistryKey(const char* key, const char* newName);
1543//bool RenameRegistryTree(const char* entry, const char* newName);
1544
1545
1546
1548
1552
1554bool UtilsTest();
1556void PrintBinary(void* p, uint32 size, bool asInt, const char* title);
1558const char* stristr(const char *str, const char *substr, uint32 len = 0);
1562bool GetNextLineEnd(const char *str, uint32 size, uint32& len, uint32& crSize);
1564uint32 TextReplaceCharsInPlace(char* str, uint32 size, char find, char replace);
1566bool TextEndsWith(const char* str, const char* end, bool caseSensitive = true);
1568bool TextStartsWith(const char* str, const char* start, bool caseSensitive = true);
1573uint32 strcpyavail(char* dst, const char* src, uint32 maxlen, bool copyAvailable);
1575const char* laststrstr(const char* str1, const char* str2);
1577const char* laststristr(const char* str1, const char* str2);
1578
1580
1583
1587uint32 StringSingleReplace(std::string& text, std::string key, std::string value, bool onlyFirst);
1589uint32 StringMultiReplace(std::string& text, std::map<std::string, std::string>& map, bool onlyFirst);
1593uint32 StringScriptReplace(std::string& text, std::string name, std::list< std::map<std::string, std::string> >& list);
1594
1596
1601
1603std::string TextCapitalise(const char* text);
1605std::string TextUppercase(const char* text);
1607std::string TextLowercase(const char* text);
1609std::string TextIndent(const char* text, const char* indent);
1611std::string TextUnindent(const char* text);
1613std::string TextTrimQuotes(const char* text);
1618std::string TextTrim(const char* text);
1627std::multimap<std::string, std::string> TextMultiMapSplit(const char* text, const char* outersplit, const char* innersplit);
1637std::map<std::string, std::string> TextMapSplit(const char* text, const char* outersplit, const char* innersplit);
1639std::string TextJoin(std::vector<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1641std::string TextJoin(std::list<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1644std::string TextJoin(std::map<std::string, std::string> &map, const char* innersplit, const char* outersplit, bool keyquotes, bool valquotes);
1646std::string TextJoinJSON(std::map<std::string, std::string> &map);
1648std::string TextJoinXML(std::map<std::string, std::string> &map, const char* innernodeName, const char* outernodeName);
1655std::vector<std::string> TextListSplit(const char* text, const char* split, bool keepEmpty = true, bool autoTrim = false);
1657std::vector<std::string> TextListSplitLines(const char* text, bool keepEmpty = true, bool autoTrim = false);
1659std::vector<std::string> TextListBreakLines(const char* text, uint32 maxLineLength = 80);
1661std::string TextListBreakLines(const char* text, uint32 maxLineLength, const char* breakstr);
1663std::string TextVectorConcat(std::vector<std::string>, const char* sep, bool allowEmpty = true);
1665std::vector<std::string> TextCommandlineSplit(const char* cmdline);
1667char** SplitCommandline(const char* cmdline, int& argc);
1669wchar_t** SplitCommandlineW(const char* cmdline, int& argc);
1671bool DeleteCommandline(char** argv, int argc);
1672
1674
1677
1686std::string StringFormat(const char *format, ...);
1688char* StringFormat(uint32& size, const char *format, ...);
1690bool StringFormatInto(char* dst, uint32 maxsize, const char *format, ...);
1692char* StringFormatVA(uint32& size, const char *format, va_list args);
1693
1695
1698
1700unsigned char Hex2Char(const char* str);
1702unsigned char Dec2Char(const char* str);
1712int CRC32(const char *addr, uint32 length, int32 crc = 0);
1713
1715int8 CompareFloats(float64 a, float64 b);
1716
1718
1723
1737
1738#define NOSUCHFILE 0
1739#define STANDARDFILE 1
1740#define STANDARDDIR 2
1741
1746std::string ReadAFileString(std::string filename);
1764char* ReadAFile(const char* filename, uint32& length, bool binary = false);
1766char* ReadAFile(const char* dir, const char* filename, uint32& length, bool binary = false);
1771bool WriteAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1773bool WriteAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1775bool AppendToAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1777bool AppendToAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1793char* GetFileList(const char* dirname, const char* ext, uint32& count, bool fullpath, uint32 maxNameLen = 256);
1795FileDetails GetFileDetails(const char* filename);
1797std::string GetFilePath(const char* filename);
1799const char* GetFileBasename(const char* filename);
1801std::string GetCurrentDir();
1803bool DeleteAFile(const char* filename, bool force);
1805bool DeleteAFile(const char* dir, const char* filename, bool force);
1807bool DeleteADir(const char* dirname, bool force);
1809bool CreateADir(const char* dirname);
1811bool DoesADirExist(const char* dirname);
1813bool DoesAFileExist(const char* filename);
1815bool DeleteFilesInADir(const char* dirname, bool force);
1817bool ChangeAFileAttr(const char* filename, bool read, bool write);
1819bool MoveAFile(const char* oldfilename, const char* newfilename, bool force = false);
1821bool MoveAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1823bool CopyAFile(const char* oldfilename, const char* newfilename, bool force = false);
1825bool CopyAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1826
1828
1843
1845char* Int2Ascii(int64 value, char* result, uint16 size, uint8 base);
1847char* Uint2Ascii(uint64 value, char* result, uint16 size, uint8 base);
1851unsigned char* Ascii2UTF16LE(const char* ascii, uint32 len, uint32& size);
1852
1854bool IsTextNumeric(const char* ascii, uint32 start = 0, uint32 end = 0);
1856int64 Ascii2Int64(const char* ascii, uint32 start = 0, uint32 end = 0);
1858uint64 Ascii2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
1860uint64 AsciiHex2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
1862int32 Ascii2Int32(const char* ascii, uint32 start = 0, uint32 end = 0);
1864uint32 Ascii2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
1866uint32 AsciiHex2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
1868float64 Ascii2Float64(const char* ascii, uint32 start = 0, uint32 end = 0);
1869
1871char* TextSubstringCopy(const char* ascii, uint32 start, uint32 end);
1872
1879std::string DecodeJSON(std::string str);
1884std::string EncodeJSON(std::string str);
1885
1887
1890
1896bool SeedRandomValues(uint32 seedvalue = 0);
1903double RandomValue();
1905double RandomValue(double to);
1907double RandomValue(double from, double to);
1909double RandomValue(double from, double to, double interval);
1911int64 RandomInt(int64 from = 0, int64 to = 100);
1912
1917std::string BytifySize(double val);
1919std::string BytifySizes(double val1, double val2);
1921std::string BytifyRate(double val);
1923std::string BytifyRates(double val1, double val2);
1924
1926 // end of utils
1928
1929} // namespace utils
1930} // namespace cmlabs
1931
1932#endif //_UTILS_H_
1933
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:1304
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:1316
std::map< std::string, std::string > CommandLineArgs
Definition Utils.h:1325
static CommandLineInfo * CommandLineInfoSingleton
Definition Utils.h:1318
std::string CommandLineExecOnly
Definition Utils.h:1322
std::string CommandLineExecPath
Definition Utils.h:1323
std::vector< std::string > CommandLineItems
Definition Utils.h:1324
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:1356
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
Definition Utils.cpp:4864
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:4746
bool load(const char *filename)
Load a library.
Definition Utils.cpp:4776
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:916
uint32 getCount()
Number of scheduled entries.
Definition Utils.h:906
std::list< TimeQueueEntry< T > > internalList
Definition Utils.h:946
virtual bool clear()
Discard all scheduled entries.
Definition Utils.h:935
bool add(uint64 time, T entry)
Insert an entry sorted by its due time.
Definition Utils.h:885
T getNextEntryDue()
Pop the earliest due entry.
Definition Utils.h:958
virtual bool clear()
Delete every scheduled pointer and empty the queue.
Definition Utils.h:967
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:659
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:752
bool waitForAndPeekFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and peek it without removal.
Definition Utils.h:766
bool add(T entry)
Append an entry and wake one waiting consumer.
Definition Utils.h:722
bool peekFirst(T &first)
Copy the front entry without removing it.
Definition Utils.h:740
std::queue< T > internalQueue
Definition Utils.h:830
bool waitForAndTakeFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and dequeue it.
Definition Utils.h:792
virtual bool clear()
Discard all queued entries.
Definition Utils.h:818
uint32 getCount()
Number of queued entries.
Definition Utils.h:731
T waitForAndTakeFirst(uint32 timeoutMS)
Convenience overload: dequeue with timeout, returning NULL instead of using an out-parameter.
Definition Utils.h:843
virtual bool clear()
Delete every queued pointer and empty the queue.
Definition Utils.h:852
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
static std::map< uint32, ProcessData * > * ProcessInformationMap
Definition Utils.h:619
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
Definition Utils.cpp:3198
void ReleaseProcessCapture(uint32 proc)
POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captur...
Definition Utils.cpp:4196
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:4208
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:7590
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:7647
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
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, int posixParentDeathSig=0, bool posixUseShell=false)
Launch a child with environment overrides and optional output capture.
Definition Utils.cpp:4244
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
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:7615
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:4133
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:4544
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:6442
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:6407
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:6481
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:4491
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:4533
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:7640
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:6365
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:7579
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:6463
std::pair< uint32, ProcessData * > Proc_Pair
Definition Utils.h:620
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:8079
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
Definition Utils.cpp:5649
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
Definition Utils.cpp:5659
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
Definition Utils.cpp:6759
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
Definition Utils.cpp:7167
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
Definition Utils.cpp:6061
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
Definition Utils.cpp:8003
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:5494
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
Definition Utils.cpp:4964
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
Definition Utils.cpp:6644
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:4705
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
Definition Utils.cpp:7460
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
Definition Utils.cpp:8226
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
Definition Utils.cpp:7412
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
Definition Utils.cpp:7553
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
Definition Utils.cpp:4699
uint16 GetCPUArchitecture()
CPU architecture id.
Definition Utils.cpp:5055
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:7204
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:6973
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:6514
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
Definition Utils.cpp:7186
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
Definition Utils.cpp:5707
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
Definition Utils.cpp:5987
const char * GetSystemArchitecture()
Architecture name string, e.g.
Definition Utils.cpp:5203
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:6576
std::string GetCommandLinePath()
Get the directory portion of the executable path.
Definition Utils.cpp:4659
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
Definition Utils.cpp:4717
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
Definition Utils.cpp:5756
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
Definition Utils.cpp:7933
uint64 GetCPUSpeed()
Nominal CPU clock speed.
Definition Utils.cpp:5092
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
Definition Utils.cpp:6664
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
Definition Utils.cpp:6946
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
Definition Utils.cpp:7312
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
Definition Utils.cpp:6526
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
Definition Utils.cpp:7159
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:7700
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
Definition Utils.cpp:6317
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
Definition Utils.cpp:7364
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:7069
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:6918
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
Definition Utils.cpp:7857
uint16 GetCPUCount()
Number of logical CPU cores.
Definition Utils.cpp:5036
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
Definition Utils.cpp:5470
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:6618
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
Definition Utils.cpp:4996
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
Definition Utils.cpp:6684
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
Definition Utils.cpp:7943
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
Definition Utils.cpp:8497
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
Definition Utils.cpp:5915
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
Definition Utils.cpp:6537
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
Definition Utils.cpp:5292
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:7103
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:6900
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
Definition Utils.cpp:4612
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
Definition Utils.cpp:7051
uint64 GetSystemMemorySize()
Total physical RAM installed.
Definition Utils.cpp:5139
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:5975
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
Definition Utils.cpp:5675
FileDetails GetFileDetails(const char *filename)
Stat a file.
Definition Utils.cpp:7771
double RandomValue()
Uniform random double in [0,1).
Definition Utils.cpp:8085
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
Definition Utils.cpp:5513
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
Definition Utils.cpp:4682
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:6591
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
Definition Utils.cpp:6029
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
Definition Utils.cpp:5847
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
Definition Utils.cpp:7838
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:5768
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
Definition Utils.cpp:5443
std::string GetLocalHostnameString()
Local hostname as std::string.
Definition Utils.cpp:5903
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
Definition Utils.cpp:7923
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
Definition Utils.cpp:7766
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
Definition Utils.cpp:6171
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
Definition Utils.cpp:6558
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
Definition Utils.cpp:7151
bool DeleteAFile(const char *filename, bool force)
Delete a file.
Definition Utils.cpp:7340
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
Definition Utils.cpp:7344
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
Definition Utils.cpp:8131
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
Definition Utils.cpp:4676
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
Definition Utils.cpp:7003
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:6741
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:7284
std::string GetCurrentDir()
Current working directory.
Definition Utils.cpp:7687
std::string GetCommandLine()
Get the full original command line as one string.
Definition Utils.cpp:4653
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:6691
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
Definition Utils.cpp:7761
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:7033
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
Definition Utils.cpp:5744
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
Definition Utils.cpp:7486
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:7225
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
Definition Utils.cpp:7887
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:7905
const char * GetFileBasename(const char *filename)
Filename portion of a path.
Definition Utils.cpp:7671
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
Definition Utils.cpp:4899
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:5162
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:7869
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:6884
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
Definition Utils.cpp:8500
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
Definition Utils.h:1311
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:6520
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
Definition Utils.cpp:7964
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
Definition Utils.cpp:6500
const char * GetComputerName()
Get this machine's hostname.
Definition Utils.cpp:4917
std::string GetFilePath(const char *filename)
Directory portion of a path.
Definition Utils.cpp:7655
const char * GetSystemOSName()
OS name string, e.g.
Definition Utils.cpp:5264
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
Definition Utils.cpp:8168
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
Definition Utils.cpp:6002
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:7953
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:6837
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
Definition Utils.cpp:8122
std::string BytifyRate(double val)
Format a byte rate, e.g.
Definition Utils.cpp:8214
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:1725
Description of one local network interface (IPv4 address, MAC and names).
Definition Utils.h:1466
char friendlyName[MAXKEYNAMELEN+1]
Definition Utils.h:1470
char name[MAXKEYNAMELEN+1]
Definition Utils.h:1469
POSIX capture bookkeeping for children started via NewProcessEx(captureOutput).
Definition Utils.h:614
int errFD
Parent read-end of the child's stderr (-1 = not captured).
Definition Utils.h:617
int outFD
Parent read-end of the child's stdout (-1 = not captured).
Definition Utils.h:616
One (time, entry) pair inside a TimeQueue.
Definition Utils.h:871
uint64 time
Definition Utils.h:872
T entry
Definition Utils.h:873
One scheduled entry inside a Timer: id, active window and platform timer handle.
Definition Utils.h:627
A single timer expiry: which timer fired and when.
Definition Utils.h:645