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 // Named (process-shared) mutexes recover from an owner that died holding them (17 Nov 2026): Linux uses robust
143 // mutexes (EOWNERDEAD); macOS has none, so its named mutexes are a lock word holding the owner's pid, taken over by
144 // a waiter once that process is gone (Utils.cpp SharedLockAcquire). Defining CMSDK_MUTEX_PID_RECOVERY forces the
145 // macOS scheme on Linux too (futex instead of os_sync/ulock; used to test it there).
146 #if defined(__APPLE__) && !defined(CMSDK_MUTEX_PID_RECOVERY)
147 #define CMSDK_MUTEX_PID_RECOVERY 1
148 #endif
149 // Named semaphores on macOS are a counter word in a shared segment that nothing ever holds, so a process can die
150 // inside wait()/signal() (18 Nov 2026; Utils.cpp SemWordWait). Defining CMSDK_SEMAPHORE_WORD uses it on Linux too
151 // (instead of sem_open; to test it there).
152 #if defined(__APPLE__) && !defined(CMSDK_SEMAPHORE_WORD)
153 #define CMSDK_SEMAPHORE_WORD 1
154 #endif
155 #ifdef CMSDK_MUTEX_PID_RECOVERY
156 #define MUTEXMEMSIZE 128
157 #else
158 #define MUTEXMEMSIZE 64
159 #endif
160 #define EVENTMEMSIZE 256
161 #define SEMAPHOREMEMSIZE 256
162 #define _strcmpi strcasecmp
163 #define _strnicmp strnicmp
164 #define DllExport
165#endif
166
167#ifndef SD_BOTH
168 #define SD_BOTH 2
169#endif
170
171#define OSCPU_UNKNOWN 0
172#define OSCPU_X86 1
173#define OSCPU_AMD64 2
174#define OSCPU_IA64 3
175
176#define ERROR64 0xFFFFFFFFFFFFFFFFL
177#define ERROR32 0xFFFFFFFF
178#define ERROR16 0xFFFF
179#define ERROR8 0xFF
180
181#include "PsyTime.h"
182
183namespace cmlabs {
184
186// INIT/EXIT //
188
196public:
201};
202
207bool ClearUtilsMaps();
208
210// Logging //
212
213#define LOG_NOTOPIC 0
214#define LOG_SYSTEM 1
215#define LOG_NETWORK 2
216#define LOG_MEMORY 3
217#define LOG_PROCESS 4
218#define LOG_TOPIC5 5
219#define LOG_TOPIC6 6
220#define LOG_TOPIC7 7
221#define LOG_TOPIC8 8
222#define LOG_TOPIC9 9
223#define LOG_TOPIC10 10
224#define LOG_TOPIC11 11
225#define LOG_MAXCOUNT 12
226
227#define LOGPRINT 1
228#define LOGDEBUG 2
229
233std::string GetDataTypeName(uint32 datatype);
237uint32 GetDataTypeID(const char* typeName);
238
239// #define GETLOGTEXT(l) (char*)l+sizeof(LogEntry)
245struct LogEntry {
246 uint32 size; //
247 uint32 cid; // LOGENTRYID
248 uint64 time; //
249 uint32 source; //
250 uint8 subject; //
251 uint8 level; //
252 uint8 type; //
256 const char* getText(uint32& len);
261 bool setText(char* text, uint32 len);
263 std::string toJSON();
265 std::string toXML();
266};
267
274public:
276// virtual bool logPrint(uint32 source, uint8 subject, uint8 level, std::string text, uint64 time) = 0;
277// virtual bool logDebug(uint32 source, uint8 subject, uint8 level, std::string text, uint64 time) = 0;
279 virtual bool logEntry(LogEntry* entry) = 0;
280};
281
290public:
291 LogSystem();
292 ~LogSystem();
293
297 static bool SetLogReceiver(LogReceiver* rec);
298
303 static bool SetLogFileOutput(const char* logfile, bool printOut = true);
305 static bool SetLogLevelDebug(uint8 level);
307 static bool SetLogLevelDebug(uint8 subject, uint8 level);
309 static bool SetLogLevelVerbose(uint8 level);
311 static bool SetLogLevelVerbose(uint8 subject, uint8 level);
312
319 static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... );
321 static bool LogSystemDebug(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... );
322
326 char* logfile;
328};
329
330#define LogPrint LogSystem::LogSystemPrint
331#define LogDebug LogSystem::LogSystemDebug
332
333namespace utils {
334
395
397bool UtilsTest();
398
399// bool GetSystemName(uint32 id, const char* title, char* name, uint32 size);
400
401
402
404// Mutexes //
406
407#ifdef WINDOWS
408 #define SharedMemoryFileHandleMapType std::map<char*, HANDLE>
409#else
410 #define SharedMemoryFileHandleMapType std::map<void*, std::string>
411#endif
413
414static uint16 SharedSystemInstance = 0;
415
421
425bool SetSharedSystemInstance(uint32 inst);
428
429// https://stackoverflow.com/questions/44807302/create-c-timer-in-macos/52905687#52905687
430
435typedef bool (* DrumBeatFunc)(uint32 id, uint32 count);
436
441 uint32 id;
443 uint64 started;
444 uint32 interval;
446 uint32 count;
447 #ifdef WINDOWS
448 HANDLE handle;
449 #else
450 #ifdef __APPLE__
451 dispatch_source_t handle;
452 #else
453 timer_t handle;
454 #endif
455 #endif
456};
457
458static std::map<uint32, DrumBeatInfo>* DrumBeatMap = NULL;
459
466bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart = false);
468bool StartDrumBeat(uint32 id);
470bool StopDrumBeat(uint32 id);
472bool EndDrumBeat(uint32 id);
473
480class Mutex {
481public:
483 Mutex();
487 Mutex(const char* name, bool force = false);
488 ~Mutex();
490 bool enter();
495 bool enter(uint32 timeout, const char* errorMsg = NULL);
497 bool leave();
498// bool destroy();
515 void setCancelSafe(bool on);
516protected:
517 char *name;
519 uint32 osid;
520 uint32 total;
521 uint32 count;
522 #ifdef WINDOWS
523 HANDLE mutex;
524 #else
525 //sem_t* semaphore;
526 pthread_mutex_t* mutex;
527 #endif
528};
529
530
537public:
539 Semaphore(uint32 maxCount = 100);
541 Semaphore(const char* name, uint32 maxCount = 100);
542 ~Semaphore();
544 bool wait();
546 bool wait(uint32 timeout);
548 bool signal();
549// bool destroy();
550 char *name;
551protected:
552 #ifdef WINDOWS
553 HANDLE semaphore;
554 #else
555 #ifdef __APPLE__
556 void* semaphore_impl; /* dispatch_semaphore_t when name==NULL, else char* to shared memory */
557 #else
558 sem_t* semaphore;
559 #endif
560 #endif
561};
562
567class Event {
568public:
570 Event();
572 Event(const char* name);
573 ~Event();
575 bool waitNext();
577 bool waitNext(uint32 timeout);
579 bool signal();
580// bool destroy();
581protected:
582 char *name;
583 #ifdef WINDOWS
584 HANDLE event;
585 #else
586 pthread_cond_t* event;
587 pthread_mutex_t* mutex;
588 #endif
589};
590
595bool EnterMutex(const char* name, uint32 ms, bool autocreate = true);
597bool LeaveMutex(const char* name);
599bool DestroyMutex(const char* name);
600
604Semaphore* GetSemaphore(const char* name, bool autocreate = true);
606bool WaitForSemaphore(const char* name, uint32 ms, bool autocreate = true);
608bool SignalSemaphore(const char* name);
610bool DestroySemaphore(const char* name);
611
613bool WaitNextEvent(const char* name, uint32 ms, bool autocreate = true);
615bool SignalEvent(const char* name);
617bool DestroyEvent(const char* name);
618
620
622static std::map<std::string, Mutex*>* SharedMemoryMutexMap = NULL;
623typedef std::pair<std::string, Mutex*> SharedMemoryMutexMapPair;
625static std::map<std::string, Semaphore*>* SharedMemorySemaphoreMap = NULL;
626typedef std::pair<std::string, Semaphore*> SharedMemorySemaphoreMapPair;
628static std::map<std::string, Event*>* SharedMemoryEventMap = NULL;
629typedef std::pair<std::string, Event*> SharedMemoryEventMapPair;
630
631#ifdef WINDOWS
632struct ProcessData {
633 ProcessData() { hOutRead = NULL; hErrRead = NULL; hInWrite = NULL; hJob = NULL; }
634 PROCESS_INFORMATION procInfo;
635 STARTUPINFO si;
636 HANDLE hOutRead;
637 HANDLE hErrRead;
643 HANDLE hInWrite;
650 HANDLE hJob;
651};
652static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
653typedef std::pair <uint32, ProcessData*> Proc_Pair;
654static HANDLE ghJob = NULL;
655#else
662 ProcessData() { outFD = -1; errFD = -1; }
663 int outFD;
664 int errFD;
665};
666static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
667typedef std::pair <uint32, ProcessData*> Proc_Pair;
668#endif
669
672
675 uint32 globalID;
676 uint32 id;
677 uint64 start;
678 uint64 end;
679 uint32 interval;
680 #ifdef WINDOWS
681 HANDLE handle;
682 #else
683 #ifdef __APPLE__
684 dispatch_source_t handle;
685 #else
686 timer_t handle;
687 #endif
688 #endif
689};
690
693 uint32 id;
694 uint64 time;
695};
696
703class Timer {
704public:
706 static std::map<uint32, Timer*>* timers;
707
708 Timer();
709 ~Timer();
710
717 bool addTimer(uint32 id, uint32 interval, uint64 start = 0, uint64 end = 0);
719 bool triggerTimer(uint32 id);
725 bool waitForTimer(uint32 timeout, uint32& id, uint64& time);
727 bool removeTimer(uint32 id);
728
729private:
730 uint32 globalID;
731 Mutex mutex;
732 Semaphore semaphore;
733 std::queue<TimerTrigger*> triggers;
734 std::map<uint32, TimerSchedule*> schedules;
735 std::list<TimerSchedule*> oldSchedules;
736};
737
738#ifdef WINDOWS
740 void CALLBACK TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired);
741#else
743 static void TimerCallback(int sig, siginfo_t *siginfo, void *context);
744#endif
746bool UnitTest_Timer();
748bool UnitTest_Utils();
756
758// Wait Queue //
760
769template <typename T>
771public:
773 virtual ~WaitQueue() {}
774
776 bool add(T entry) {
777 if (!mutex.enter(200, __FUNCTION__))
778 return false;
779 internalQueue.push(entry);
780 semaphore.signal();
781 mutex.leave();
782 return true;
783 }
784
785 uint32 getCount() {
786 uint32 size;
787 if (!mutex.enter(200, __FUNCTION__))
788 return 0;
789 size = (uint32)internalQueue.size();
790 mutex.leave();
791 return size;
792 }
793
794 bool peekFirst(T& first) {
795 if (!mutex.enter(200, __FUNCTION__))
796 return false;
797 if (!internalQueue.size()) {
798 mutex.leave();
799 return false;
800 }
801 first = internalQueue.front();
802 mutex.leave();
803 return true;
804 }
805
806 bool takeFirst(T& first) {
807 if (!mutex.enter(200, __FUNCTION__))
808 return false;
809 if (!internalQueue.size()) {
810 mutex.leave();
811 return false;
812 }
813 first = internalQueue.front();
814 internalQueue.pop();
815 mutex.leave();
816 return true;
817 }
818
820 bool waitForAndPeekFirst(T& first, uint32 timeoutMS) {
821 if (!mutex.enter(200, __FUNCTION__))
822 return false;
823 if (internalQueue.size()) {
824 first = internalQueue.front();
825 mutex.leave();
826 return true;
827 }
828 mutex.leave();
829 if (!semaphore.wait(timeoutMS))
830 return false;
831 if (!mutex.enter(200, __FUNCTION__))
832 return false;
833 if (internalQueue.size()) {
834 first = internalQueue.front();
835 mutex.leave();
836 return true;
837 }
838 else {
839 mutex.leave();
840 return false;
841 }
842 }
843
846 bool waitForAndTakeFirst(T& first, uint32 timeoutMS) {
847 if (!mutex.enter(200, __FUNCTION__))
848 return false;
849 if (internalQueue.size()) {
850 first = internalQueue.front();
851 internalQueue.pop();
852 mutex.leave();
853 return true;
854 }
855 mutex.leave();
856 if (!semaphore.wait(timeoutMS))
857 return false;
858 if (!mutex.enter(200, __FUNCTION__))
859 return false;
860 if (internalQueue.size()) {
861 first = internalQueue.front();
862 internalQueue.pop();
863 mutex.leave();
864 return true;
865 }
866 else {
867 mutex.leave();
868 return false;
869 }
870 }
871
872 virtual bool clear() {
873 if (!mutex.enter(200, __FUNCTION__))
874 return false;
875 std::queue<T> empty;
876 std::swap(internalQueue, empty);
877 mutex.leave();
878 return true;
879 }
880
881protected:
884 std::queue<T> internalQueue;
885};
886
889template <typename T>
890class WaitQueuePointer : public WaitQueue<T> {
891public:
893 virtual ~WaitQueuePointer() { clear(); }
894
897 T waitForAndTakeFirst(uint32 timeoutMS) {
898 T first;
899 if (WaitQueue<T>::waitForAndTakeFirst(first, timeoutMS))
900 return first;
901 else
902 return NULL;
903 }
904
906 virtual bool clear() {
907 if (!WaitQueue<T>::mutex.enter(200, __FUNCTION__))
908 return false;
909 while (WaitQueue<T>::internalQueue.size()) {
910 delete(WaitQueue<T>::internalQueue.front());
912 }
913 WaitQueue<T>::mutex.leave();
914 return true;
915 }
916};
917
918
920// Time Queue //
922
924template <typename T>
926 uint64 time;
928};
929
932template <typename T>
934public:
936 virtual ~TimeQueue() {}
937
939 bool add(uint64 time, T entry) {
940 if (!mutex.enter(200, __FUNCTION__))
941 return false;
942 TimeQueueEntry<T> newEntry;
943 newEntry.time = time;
944 newEntry.entry = entry;
945 typename std::list< TimeQueueEntry<T> >::iterator i = internalList.begin(),
946 e = internalList.end();
947 while (i != e) {
948 if (time < (*i).time) {
949 internalList.insert(i, newEntry);
950 mutex.leave();
951 return true;
952 }
953 i++;
954 }
955 internalList.push_back(newEntry);
956 mutex.leave();
957 return true;
958 }
959
960 uint32 getCount() {
961 uint32 size;
962 if (!mutex.enter(200, __FUNCTION__))
963 return 0;
964 size = (uint32)internalList.size();
965 mutex.leave();
966 return size;
967 }
968
970 bool getNextEntryDue(T& entry) {
971 if (!mutex.enter(200, __FUNCTION__))
972 return false;
973 if (!internalList.size()) {
974 mutex.leave();
975 return false;
976 }
977 uint64 now = GetTimeNow();
978 TimeQueueEntry<T> first = internalList.front();
979 if (first.time < now) {
980 internalList.pop_front();
981 entry = first.entry;
982 mutex.leave();
983 return true;
984 }
985 mutex.leave();
986 return false;
987 }
988
989 virtual bool clear() {
990 if (!mutex.enter(200, __FUNCTION__))
991 return false;
992 std::list< TimeQueueEntry<T> > empty;
993 std::swap(internalList, empty);
994 mutex.leave();
995 return true;
996 }
997
998protected:
1000 std::list< TimeQueueEntry<T> > internalList;
1001};
1002
1005template <typename T>
1006class TimeQueuePointer : public TimeQueue<T> {
1007public:
1009 virtual ~TimeQueuePointer() { clear(); }
1010
1013 T first;
1015 return first;
1016 else
1017 return NULL;
1018 }
1019
1021 virtual bool clear() {
1022 if (!TimeQueue<T>::mutex.enter(200, __FUNCTION__))
1023 return false;
1024 typename std::list< TimeQueueEntry<T> >::iterator i = TimeQueue<T>::internalList.begin(),
1026 while (i != e) {
1027 delete((*i).entry);
1028 i++;
1029 }
1031 TimeQueue<T>::mutex.leave();
1032 return true;
1033 }
1034};
1035
1036
1038// Shared Memory //
1040
1042
1048
1054char* CreateSharedMemorySegment(const char* name, uint64 size, bool force = false);
1058char* OpenSharedMemorySegment(const char* name, uint64 size);
1066bool CloseSharedMemorySegment(char* data, uint64 size);
1071bool DisownSharedMemorySegment(char* data);
1075bool UnlinkSharedMemorySegment(char* data);
1078uint32 RemovePortSharedSegments(uint16 port);
1083void ClearStaleSharedSegments(uint16 port);
1084// Destroy named shared memory segment
1085// bool DestroySharedMemorySegment(char* data, uint32 size);
1086
1088
1093
1095uint64 ntoh64(const uint64 *input);
1097uint64 hton64(const uint64_t *input);
1098
1101uint32 Calc32BitFieldSize(uint32 bitsize);
1103bool Reset32BitField(char* bitfield, uint32 bytesize);
1107bool GetFirstFreeBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1111bool GetFirstFreeBitLocN(const char* bitfield, uint32 bytesize, uint32 num, uint32& loc);
1113bool SetBit(uint32 loc, bit value, char* bitfield, uint32 bytesize);
1116bool SetBitN(uint32 loc, uint32 num, bit value, char* bitfield, uint32 bytesize);
1118bool GetBit(uint32 loc, const char* bitfield, uint32 bytesize, bit& val);
1120bool GetLastOccupiedBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1121
1124std::string GetBitFieldAsString(const char* bitfield, uint32 bytesize, uint32 size);
1127std::string PrintBitFieldString(const char* bitfield, uint32 bytesize, uint32 size, const char* title);
1128
1130
1131
1133// Threading //
1135
1138
1142std::string PrintProgramTrace(uint32 startLine = 0, uint32 endLine = 0);
1144std::list<std::string> GetProgramTrace();
1145
1147int32 AtomicIncrement32(int32 volatile &v);
1149int64 AtomicIncrement64(int64 volatile &v);
1151int32 AtomicDecrement32(int32 volatile &v);
1153int64 AtomicDecrement64(int64 volatile &v);
1154
1156bool Sleep(uint32 ms);
1157
1164bool CreateThread(THREAD_FUNCTION func, void* args, ThreadHandle& thread, uint32 &osID);
1165
1167bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS = 0);
1168bool ReapThread(ThreadHandle& hThread);
1169bool TryReapThread(ThreadHandle& hThread);
1170
1173
1176bool TerminateThread(ThreadHandle hThread);
1177
1186typedef void (*ShutdownSignalCallback)(int sig, int count);
1187
1197
1207
1211bool StopSignalThread();
1212
1215bool PauseThread(ThreadHandle hThread);
1216
1218bool ContinueThread(ThreadHandle hThread);
1219
1221bool GetCurrentThreadUniqueID(uint32 &tid);
1222
1224bool GetCurrentThreadOSID(uint32 &tid);
1225
1227bool GetCurrentThread(ThreadHandle& thread);
1228
1230bool IsThreadRunning(ThreadHandle hThread);
1231
1235
1236#if defined WINDOWS
1237 #define FileTimeToUint64(ft) (((uint64)(ft.dwHighDateTime))<<32)|((uint64)ft.dwLowDateTime)
1238#endif
1239
1243bool GetCPUTicks(ThreadHandle hThread, uint64& ticks);
1244
1246bool GetCPUTicks(uint64& ticks);
1247
1249bool GetProcessCPUTicks(uint64& ticks);
1250
1252bool GetProcessCPUTicks(uint32 osProcID, uint64& ticks);
1253
1261bool GetProcAndOSCPUUsage(double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1262
1270bool GetProcAndOSCPUUsage(uint32 osProcID, double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1271
1273bool GetOSCPUUsage(double& percentUse);
1274
1276bool GetThreadPriority(ThreadHandle hThread, uint16 priority);
1277
1279bool SetThreadPriority(ThreadHandle hThread, uint16 priority);
1280
1282int ToOSPriority(int pri);
1283
1285int FromOSPriority(int pri);
1286
1288bool SignalThread(ThreadHandle hThread, int32 signal);
1289
1291
1293// Desktop //
1295
1298
1300bool GetDesktopSize(uint32& width, uint32& height);
1301
1303bool RenameConsoleWindow(const char* name, bool prepend = false);
1304
1306bool MoveConsoleWindow(int32 x = -1, int32 y = -1, int32 w = -1, int32 h = -1);
1307
1309
1311// Processes //
1313
1314#define PROC_ERROR 0
1315#define PROC_TERMINATED 1
1316#define PROC_NOTSTARTED 2
1317#define PROC_RUNNING 3
1318#define PROC_TIMEOUT 4
1319
1320#define NUM_PIPES 2
1321#define PARENT_WRITE_PIPE 0
1322#define PARENT_READ_PIPE 1
1323/* always in a pipe[], pipe[0] is for read and
1324 pipe[1] is for write */
1325#define READ_FD 0
1326#define WRITE_FD 1
1327#define PARENT_READ_FD ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
1328#define PARENT_WRITE_FD ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
1329#define CHILD_READ_FD ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
1330#define CHILD_WRITE_FD ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
1331
1332#define PROCBUFSIZE 4096
1333
1336
1344int RunOSCommand(const char* cmdline, const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString);
1349uint32 NewProcess(const char* cmdline, const char* initdir = NULL, const char* title = NULL,
1350 int16 x = -1, int16 y = -1, int16 w = -1, int16 h = -1);
1354uint8 GetProcessStatus(uint32 proc, int &returncode);
1356bool EndProcess(uint32 proc);
1357
1380uint32 NewProcessEx(const char* cmdline, const char* initdir, const char* title,
1381 const std::map<std::string, std::string>* env,
1382 bool captureOutput, bool ignoreOutput, bool newProcessGroup,
1383 int posixParentDeathSig = 0, bool posixUseShell = false);
1388bool ReadProcessOutput(uint32 proc, std::string& out, std::string& err);
1398bool WriteProcessInput(uint32 proc, const char* data, uint32 len);
1404bool CloseProcessInput(uint32 proc);
1410void ReleaseProcessCapture(uint32 proc);
1415bool SendProcessBreak(uint32 proc, int sig);
1424
1432bool ProbeProcessWait(uint32 pid, ProcessWaitInfo& out);
1452uint32 NewProcessTerminal(const char* cmdline, const char* initdir,
1453 const std::map<std::string, std::string>* env,
1454 uint16 cols = 0, uint16 rows = 0);
1459bool ReadProcessTerminal(uint32 proc, std::string& out, bool& eofOut);
1462bool WriteProcessTerminal(uint32 proc, const char* data, uint32 len);
1465bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows);
1469void CloseProcessTerminal(uint32 proc);
1474uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode);
1476uint32 GetLocalProcessID();
1477
1479
1481// DLL Libraries //
1483
1484#ifdef WINDOWS
1485 #define DLLHandle HINSTANCE
1486#else // WINDOWS
1487 #define DLLHandle void*
1488#endif // WINDOWS
1489
1492
1494typedef int (* LibraryFunction)();
1495
1496class CommandLineInfo;
1500public:
1504 std::string CommandLineExec;
1507 std::vector<std::string> CommandLineItems;
1508 std::map<std::string, std::string> CommandLineArgs;
1509};
1510
1511
1512
1516bool SetCommandLine(int argc, char* argv[]);
1518std::string GetCommandLine();
1520std::string GetCommandLinePath();
1522std::string GetCommandLineExecutable();
1524std::string GetCommandLineExecutableOnly();
1526uint32 GetCommandLineArgCount();
1528std::string GetCommandLineArg(uint16 n);
1532std::string GetCommandLineArg(const char* key);
1536bool HasCommandLineArg(const char* key, std::string& value);
1537
1539class Library {
1540public:
1543 static std::string patchLibraryFilename(const char* filename, const char* path = NULL);
1544
1545 Library();
1546 ~Library();
1548 bool load(const char* filename);
1550 LibraryFunction getFunction(const char* funcName);
1551private:
1552 DLLHandle handle;
1553};
1554
1556Library* OpenLibrary(const char* libName);
1557
1559
1562
1564const char* GetComputerName();
1565
1567uint64 GetProcessMemoryUsage();
1570
1572uint16 GetCPUCount();
1573
1575uint16 GetCPUArchitecture();
1576
1578uint64 GetCPUSpeed();
1579
1581uint64 GetSystemMemorySize();
1582
1584bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM);
1585
1587const char* GetSystemArchitecture();
1588
1590const char* GetSystemOSName();
1591
1596bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build, char* text, uint16 textSize);
1597
1599
1600//bool RunOSTextCommand(const char* cmd, char* result, uint32 size);
1601
1602//extern char OSLocalHostName[1024];
1603//extern char OSArchitectureName[1024];
1604//extern char OSName[1024];
1605
1606
1608// Sockets //
1610
1616
1617#ifdef WINDOWS
1619 bool CheckNetworkInit();
1620 #define CHECKNETWORKINIT utils::CheckNetworkInit();
1621#else
1622 #define CHECKNETWORKINIT
1623 #define WSAEWOULDBLOCK EAGAIN
1624#endif
1625
1631bool GetSocketError(int wsaError, char* errorString, uint16 errorStringMaxSize, bool* isRecoverable);
1632
1636std::string GetLastOSErrorMessage();
1637
1639bool WaitForSocketReadability(SOCKET s, int32 timeout);
1641bool WaitForSocketWriteability(SOCKET s, int32 timeout);
1642
1647
1655
1657bool LookupIPAddress(const char* name, uint32& address);
1659bool LookupHostname(uint32 address, char* name, uint32 maxSize);
1661std::string GetLocalHostnameString();
1663bool GetLocalHostname(char* name, uint32 maxSize);
1665bool IsLocalIPAddress(const char* addr);
1667bool IsLocalIPAddress(uint32& address);
1669bool GetLocalIPAddress(uint32& address);
1671uint32* GetLocalIPAddresses(uint32& count);
1673bool GetLocalMACAddress(uint64& address);
1675uint64* GetLocalMACAddresses(uint32& count);
1679bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort);
1680
1681#define LOCALHOSTIP 16777343 // 127.0.0.1 as 32-bit dec
1682#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
1683#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
1684
1685#define GETIPPORT(a) *(uint16*)((char*)&a + sizeof(uint32))
1686#define GETIPADDRESS(a) *(uint32*)&a
1687#define GETIPADDRESSPORT(a,p) (((uint32)a)) | (((uint64)p)<<32)
1688#define GETIPADDRESSQUAD(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3]
1689#define GETIPADDRESSQUADPORT(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3], ((uint16*)&a)[2]
1690
1692
1697
1698#ifdef WINDOWS
1700 std::string GetRegistryKeyInfo(const char* key, HKEY &hKeyRoot);
1702 std::string GetRegistryParentKeyInfo(const char* key, HKEY &hKeyRoot);
1703#endif // WINDOWS
1705uint32 ReadRegistryDWORD(const char* key, const char* entry);
1707uint64 ReadRegistryQWORD(const char* key, const char* entry);
1709std::string ReadRegistryString(const char* key, const char* entry);
1711bool WriteRegistryDWORD(const char* key, const char* entry, uint32 value);
1713bool WriteRegistryQWORD(const char* key, const char* entry, uint64 value);
1715bool WriteRegistryString(const char* key, const char* entry, const char* value);
1717bool DeleteRegistryEntry(const char* key, const char* entry);
1719bool DeleteRegistryKey(const char* key);
1721bool DeleteRegistryTree(const char* root, const char* key);
1722//bool CopyRegistryKey(const char* key, const char* newName);
1724bool CopyRegistryTree(const char* entry, const char* newName);
1725//bool RenameRegistryKey(const char* key, const char* newName);
1726//bool RenameRegistryTree(const char* entry, const char* newName);
1727
1728
1729
1731
1735
1737bool UtilsTest();
1739void PrintBinary(void* p, uint32 size, bool asInt, const char* title);
1741const char* stristr(const char *str, const char *substr, uint32 len = 0);
1745bool GetNextLineEnd(const char *str, uint32 size, uint32& len, uint32& crSize);
1747uint32 TextReplaceCharsInPlace(char* str, uint32 size, char find, char replace);
1749bool TextEndsWith(const char* str, const char* end, bool caseSensitive = true);
1751bool TextStartsWith(const char* str, const char* start, bool caseSensitive = true);
1756uint32 strcpyavail(char* dst, const char* src, uint32 maxlen, bool copyAvailable);
1758const char* laststrstr(const char* str1, const char* str2);
1760const char* laststristr(const char* str1, const char* str2);
1761
1763
1766
1770uint32 StringSingleReplace(std::string& text, std::string key, std::string value, bool onlyFirst);
1772uint32 StringMultiReplace(std::string& text, std::map<std::string, std::string>& map, bool onlyFirst);
1776uint32 StringScriptReplace(std::string& text, std::string name, std::list< std::map<std::string, std::string> >& list);
1777
1779
1784
1786std::string TextCapitalise(const char* text);
1788std::string TextUppercase(const char* text);
1790std::string TextLowercase(const char* text);
1792std::string TextIndent(const char* text, const char* indent);
1794std::string TextUnindent(const char* text);
1796std::string TextTrimQuotes(const char* text);
1801std::string TextTrim(const char* text);
1810std::multimap<std::string, std::string> TextMultiMapSplit(const char* text, const char* outersplit, const char* innersplit);
1820std::map<std::string, std::string> TextMapSplit(const char* text, const char* outersplit, const char* innersplit);
1822std::string TextJoin(std::vector<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1824std::string TextJoin(std::list<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1827std::string TextJoin(std::map<std::string, std::string> &map, const char* innersplit, const char* outersplit, bool keyquotes, bool valquotes);
1829std::string TextJoinJSON(std::map<std::string, std::string> &map);
1831std::string TextJoinXML(std::map<std::string, std::string> &map, const char* innernodeName, const char* outernodeName);
1838std::vector<std::string> TextListSplit(const char* text, const char* split, bool keepEmpty = true, bool autoTrim = false);
1840std::vector<std::string> TextListSplitLines(const char* text, bool keepEmpty = true, bool autoTrim = false);
1842std::vector<std::string> TextListBreakLines(const char* text, uint32 maxLineLength = 80);
1844std::string TextListBreakLines(const char* text, uint32 maxLineLength, const char* breakstr);
1846std::string TextVectorConcat(std::vector<std::string>, const char* sep, bool allowEmpty = true);
1848std::vector<std::string> TextCommandlineSplit(const char* cmdline);
1850char** SplitCommandline(const char* cmdline, int& argc);
1852wchar_t** SplitCommandlineW(const char* cmdline, int& argc);
1854bool DeleteCommandline(char** argv, int argc);
1855
1857
1860
1869std::string StringFormat(const char *format, ...);
1871char* StringFormat(uint32& size, const char *format, ...);
1873bool StringFormatInto(char* dst, uint32 maxsize, const char *format, ...);
1875char* StringFormatVA(uint32& size, const char *format, va_list args);
1876
1878
1881
1883unsigned char Hex2Char(const char* str);
1885unsigned char Dec2Char(const char* str);
1895int CRC32(const char *addr, uint32 length, int32 crc = 0);
1896
1898int8 CompareFloats(float64 a, float64 b);
1899
1901
1906
1920
1921#define NOSUCHFILE 0
1922#define STANDARDFILE 1
1923#define STANDARDDIR 2
1924
1929std::string ReadAFileString(std::string filename);
1947char* ReadAFile(const char* filename, uint32& length, bool binary = false);
1949char* ReadAFile(const char* dir, const char* filename, uint32& length, bool binary = false);
1954bool WriteAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1956bool WriteAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1958bool AppendToAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1960bool AppendToAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1976char* GetFileList(const char* dirname, const char* ext, uint32& count, bool fullpath, uint32 maxNameLen = 256);
1978FileDetails GetFileDetails(const char* filename);
1980std::string GetFilePath(const char* filename);
1982const char* GetFileBasename(const char* filename);
1984std::string GetCurrentDir();
1986bool DeleteAFile(const char* filename, bool force);
1988bool DeleteAFile(const char* dir, const char* filename, bool force);
1990bool DeleteADir(const char* dirname, bool force);
1992bool CreateADir(const char* dirname);
1994bool DoesADirExist(const char* dirname);
1996bool DoesAFileExist(const char* filename);
1998bool DeleteFilesInADir(const char* dirname, bool force);
2000bool ChangeAFileAttr(const char* filename, bool read, bool write);
2002bool MoveAFile(const char* oldfilename, const char* newfilename, bool force = false);
2004bool MoveAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
2006bool CopyAFile(const char* oldfilename, const char* newfilename, bool force = false);
2008bool CopyAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
2009
2011
2026
2028char* Int2Ascii(int64 value, char* result, uint16 size, uint8 base);
2030char* Uint2Ascii(uint64 value, char* result, uint16 size, uint8 base);
2034unsigned char* Ascii2UTF16LE(const char* ascii, uint32 len, uint32& size);
2035
2037bool IsTextNumeric(const char* ascii, uint32 start = 0, uint32 end = 0);
2039int64 Ascii2Int64(const char* ascii, uint32 start = 0, uint32 end = 0);
2041uint64 Ascii2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
2043uint64 AsciiHex2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
2045int32 Ascii2Int32(const char* ascii, uint32 start = 0, uint32 end = 0);
2047uint32 Ascii2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
2049uint32 AsciiHex2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
2051float64 Ascii2Float64(const char* ascii, uint32 start = 0, uint32 end = 0);
2052
2054char* TextSubstringCopy(const char* ascii, uint32 start, uint32 end);
2055
2062std::string DecodeJSON(std::string str);
2067std::string EncodeJSON(std::string str);
2068
2070
2073
2079bool SeedRandomValues(uint32 seedvalue = 0);
2086double RandomValue();
2088double RandomValue(double to);
2090double RandomValue(double from, double to);
2092double RandomValue(double from, double to, double interval);
2094int64 RandomInt(int64 from = 0, int64 to = 100);
2095
2100std::string BytifySize(double val);
2102std::string BytifySizes(double val1, double val2);
2104std::string BytifyRate(double val);
2106std::string BytifyRates(double val1, double val2);
2107
2109 // end of utils
2111
2112} // namespace utils
2113} // namespace cmlabs
2114
2115#endif //_UTILS_H_
2116
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:1487
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:225
#define SOCKET
Definition Utils.h:134
CleanShutdown()
Default constructor; no side effects.
Definition Utils.cpp:75
~CleanShutdown()
Destroys all lazily-created global utility maps via ClearUtilsMaps().
Definition Utils.cpp:79
Callback interface for receiving log entries produced through LogSystem.
Definition Utils.h:273
virtual bool logEntry(LogEntry *entry)=0
Handle one log record.
char * logfile
Definition Utils.h:326
static bool SetLogFileOutput(const char *logfile, bool printOut=true)
Direct log output to a file.
Definition Utils.cpp:315
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
Definition Utils.cpp:209
bool printToStdOut
Definition Utils.h:327
uint8 logLevelVerbose[LOG_MAXCOUNT]
Definition Utils.h:323
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:346
uint8 logLevelDebug[LOG_MAXCOUNT]
Definition Utils.h:324
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:394
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
Definition Utils.h:295
LogReceiver * logReceiverObj
Definition Utils.h:325
static bool SetLogLevelDebug(uint8 level)
Set the debug level threshold for all topics.
Definition Utils.cpp:220
static bool SetLogLevelVerbose(uint8 level)
Set the verbose (print) level threshold for all topics.
Definition Utils.cpp:244
Singleton snapshot of the parsed process command line (set via SetCommandLine()).
Definition Utils.h:1499
std::map< std::string, std::string > CommandLineArgs
Definition Utils.h:1508
static CommandLineInfo * CommandLineInfoSingleton
Definition Utils.h:1501
std::string CommandLineExecOnly
Definition Utils.h:1505
std::string CommandLineExecPath
Definition Utils.h:1506
std::vector< std::string > CommandLineItems
Definition Utils.h:1507
pthread_cond_t * event
Definition Utils.h:586
bool waitNext()
Block until the next signal() occurs.
Definition Utils.cpp:2165
Event()
Create an anonymous, process-local event.
Definition Utils.cpp:2097
bool signal()
Wake all threads currently waiting on this event.
Definition Utils.cpp:2193
pthread_mutex_t * mutex
Definition Utils.h:587
Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen).
Definition Utils.h:1539
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
Definition Utils.cpp:6877
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:6753
bool load(const char *filename)
Load a library.
Definition Utils.cpp:6784
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:480
Mutex()
Create an anonymous, process-local mutex.
Definition Utils.cpp:1393
void setCancelSafe(bool on)
Make this mutex cancellation-safe (POSIX only; no-op on Windows).
Definition Utils.cpp:1369
bool leave()
Release the mutex.
Definition Utils.cpp:1704
bool enter()
Block until the mutex is acquired.
Definition Utils.cpp:1512
pthread_mutex_t * mutex
Definition Utils.h:526
Counting semaphore, optionally named for cross-process use.
Definition Utils.h:536
Semaphore(uint32 maxCount=100)
Create an anonymous semaphore.
Definition Utils.cpp:1876
bool signal()
Increment (release) the semaphore, waking one waiter.
Definition Utils.cpp:2006
bool wait()
Block until the semaphore can be decremented.
Definition Utils.cpp:1969
bool getNextEntryDue(T &entry)
Pop the earliest entry if its due time has passed (non-blocking).
Definition Utils.h:970
uint32 getCount()
Number of scheduled entries.
Definition Utils.h:960
std::list< TimeQueueEntry< T > > internalList
Definition Utils.h:1000
virtual bool clear()
Discard all scheduled entries.
Definition Utils.h:989
bool add(uint64 time, T entry)
Insert an entry sorted by its due time.
Definition Utils.h:939
T getNextEntryDue()
Pop the earliest due entry.
Definition Utils.h:1012
virtual bool clear()
Delete every scheduled pointer and empty the queue.
Definition Utils.h:1021
bool addTimer(uint32 id, uint32 interval, uint64 start=0, uint64 end=0)
Register a periodic timer.
Definition Utils.cpp:2265
static std::map< uint32, Timer * > * timers
Global registry mapping globalID to live Timer instances, used by the OS callbacks.
Definition Utils.h:706
bool triggerTimer(uint32 id)
Manually inject an expiry for timer id, as if it had fired now.
Definition Utils.cpp:2389
bool waitForTimer(uint32 timeout, uint32 &id, uint64 &time)
Wait for the next expiry of any registered timer.
Definition Utils.cpp:2411
bool removeTimer(uint32 id)
Unregister a timer and cancel its OS timer.
Definition Utils.cpp:2362
bool takeFirst(T &first)
Remove and return the front entry.
Definition Utils.h:806
bool waitForAndPeekFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and peek it without removal.
Definition Utils.h:820
bool add(T entry)
Append an entry and wake one waiting consumer.
Definition Utils.h:776
bool peekFirst(T &first)
Copy the front entry without removing it.
Definition Utils.h:794
std::queue< T > internalQueue
Definition Utils.h:884
bool waitForAndTakeFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and dequeue it.
Definition Utils.h:846
virtual bool clear()
Discard all queued entries.
Definition Utils.h:872
uint32 getCount()
Number of queued entries.
Definition Utils.h:785
T waitForAndTakeFirst(uint32 timeoutMS)
Convenience overload: dequeue with timeout, returning NULL instead of using an out-parameter.
Definition Utils.h:897
virtual bool clear()
Delete every queued pointer and empty the queue.
Definition Utils.h:906
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:3012
int64 AtomicDecrement64(int64 volatile &v)
Atomically decrement a 64-bit value.
Definition Utils.cpp:4068
bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows)
Resize the pseudo-terminal (TIOCSWINSZ + SIGWINCH to the child's group).
Definition Utils.cpp:6509
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:5356
bool SetSharedSystemInstance(uint32 inst)
Set the instance number used to namespace shared OS objects, allowing several independent CMSDK syste...
Definition Utils.cpp:1313
static std::map< uint32, ProcessData * > * ProcessInformationMap
Definition Utils.h:666
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
Definition Utils.cpp:4541
bool UnitTest_MutexOwnerDeath()
Definition Utils.cpp:2626
void ReleaseProcessCapture(uint32 proc)
POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captur...
Definition Utils.cpp:5554
bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS=0)
Join a thread.
Definition Utils.cpp:4266
bool SignalSemaphore(const char *name)
Signal a named global semaphore.
Definition Utils.cpp:1177
bool GetThreadPriority(ThreadHandle hThread, uint16 priority)
Query a thread's scheduling priority.
Definition Utils.cpp:4933
bool UnitTest_ChildSignalMask()
Self test: a child launched with the shutdown signals blocked still stops on SIGTERM (POSIX).
Definition Utils.cpp:2588
std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
Definition Utils.h:623
int FromOSPriority(int pri)
Map a native OS priority back to the CMSDK priority scale.
Definition Utils.cpp:5023
bool CloseProcessInput(uint32 proc)
Close a child's stdin, delivering EOF (T1.1 step 2.7c).
Definition Utils.cpp:6318
bool EndProcess(uint32 proc)
Forcibly terminate a child process.
Definition Utils.cpp:5572
std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
Definition Utils.h:626
static Mutex * SharedMemorySemaphoreMapMutex
Definition Utils.h:624
bool GetLastOccupiedBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the highest set (occupied) bit.
Definition Utils.cpp:3965
const char * laststrstr(const char *str1, const char *str2)
Find the last occurrence of str2 in str1.
Definition Utils.cpp:9636
uint32 RemovePortSharedSegments(uint16 port)
Remove every shared-memory/semaphore name for this port (as ClearStaleSharedSegments,...
Definition Utils.cpp:3627
std::pair< std::string, Event * > SharedMemoryEventMapPair
Definition Utils.h:629
bool DestroyEvent(const char *name)
Destroy a named global event.
Definition Utils.cpp:1292
bool WaitForSemaphore(const char *name, uint32 ms, bool autocreate=true)
Wait on a named global semaphore.
Definition Utils.cpp:1136
static SharedMemoryFileHandleMapType * SharedMemoryFileHandleMap
Definition Utils.h:412
bool TextStartsWith(const char *str, const char *start, bool caseSensitive=true)
Test whether str starts with start.
Definition Utils.cpp:9693
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:4078
bool SetThreadPriority(ThreadHandle hThread, uint16 priority)
Set a thread's scheduling priority.
Definition Utils.cpp:4956
bool WaitNextEvent(const char *name, uint32 ms, bool autocreate=true)
Wait for the next signal on a named global event.
bool ReadProcessTerminal(uint32 proc, std::string &out, bool &eofOut)
Non-blocking read of the merged terminal stream.
Definition Utils.cpp:6462
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:4758
bool UnitTest_SemaphoreUserDeath()
Definition Utils.cpp:2891
bool PauseThread(ThreadHandle hThread)
Suspend a thread's execution.
Definition Utils.cpp:4441
uint32 NewProcessTerminal(const char *cmdline, const char *initdir, const std::map< std::string, std::string > *env, uint16 cols=0, uint16 rows=0)
Launch a child on a new pseudo-terminal (POSIX: posix_openpt + fork; child setsid() + TIOCSCTTY so it...
Definition Utils.cpp:6392
static std::map< std::string, Event * > * SharedMemoryEventMap
Definition Utils.h:628
bool MoveConsoleWindow(int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
Move/resize the console window.
Definition Utils.cpp:5105
bool WriteProcessTerminal(uint32 proc, const char *data, uint32 len)
Write bytes to the child's terminal input (its stdin).
Definition Utils.cpp:6487
bool IsThreadRunning(ThreadHandle hThread)
Check whether a thread is still alive.
Definition Utils.cpp:4511
bool CreateThread(THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
Start a new OS thread.
Definition Utils.cpp:4144
int32 AtomicDecrement32(int32 volatile &v)
Atomically decrement a 32-bit value.
Definition Utils.cpp:4058
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:6039
static std::map< uint32, DrumBeatInfo > * DrumBeatMap
Definition Utils.h:458
bool SignalThread(ThreadHandle hThread, int32 signal)
Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).
Definition Utils.cpp:5047
bool UnitTest_EventUserDeath()
Definition Utils.cpp:2946
bool BlockShutdownSignals()
Block the graceful-shutdown signals (SIGINT, SIGTERM, SIGHUP) on the CALLING thread.
Definition Utils.cpp:4390
bool UnitTest_ProbeProcessWait()
Definition Utils.cpp:2527
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
Definition Utils.cpp:3380
int64 AtomicIncrement64(int64 volatile &v)
Atomically increment a 64-bit value.
Definition Utils.cpp:4048
uint32 GetSharedSystemInstance()
Get the current shared-system instance number.
Definition Utils.cpp:1318
bool StopDrumBeat(uint32 id)
Stop a running drum beat without destroying it.
Definition Utils.cpp:868
bool EnterMutex(const char *name, uint32 ms, bool autocreate=true)
Acquire a named global mutex, creating it on first use.
Definition Utils.cpp:945
const char * laststristr(const char *str1, const char *str2)
Case-insensitive laststrstr().
Definition Utils.cpp:9661
bool ProbeProcessWait(uint32 pid, ProcessWaitInfo &out)
Probe whether a child process (group) appears blocked reading stdin (fd 0).
Definition Utils.cpp:5817
static Mutex * SharedMemoryMutexMapMutex
Definition Utils.h:621
#define SharedMemoryFileHandleMapType
Definition Utils.h:410
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:769
bool ReapThread(ThreadHandle &hThread)
Definition Utils.cpp:4224
std::string PrintProgramTrace(uint32 startLine=0, uint32 endLine=0)
Format the current call stack as printable text.
Definition Utils.cpp:4088
bool UnlinkSharedMemorySegment(char *data)
Remove a segment's name now, whoever created it; every existing mapping stays valid.
Definition Utils.cpp:3548
uint8 GetProcessStatus(uint32 proc, int &returncode)
Poll a child started with NewProcess().
Definition Utils.cpp:5489
bool(* DrumBeatFunc)(uint32 id, uint32 count)
Callback invoked on every drum-beat tick.
Definition Utils.h:435
static Mutex * SharedMemoryEventMapMutex
Definition Utils.h:627
Semaphore * GetSemaphore(const char *name, bool autocreate=true)
Look up (and optionally create) a named semaphore in the global registry.
Definition Utils.cpp:1095
bool LeaveMutex(const char *name)
Release a named global mutex previously acquired with EnterMutex().
Definition Utils.cpp:985
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:5151
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:3247
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:4009
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:3990
uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode)
Wait for a child to exit.
Definition Utils.cpp:6549
uint32 GetLocalProcessID()
Get the OS process id of the current process.
Definition Utils.cpp:5142
bool EndDrumBeat(uint32 id)
Destroy a drum beat and release its OS timer.
Definition Utils.cpp:901
bool DestroySemaphore(const char *name)
Destroy a named global semaphore.
Definition Utils.cpp:1211
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
Definition Utils.cpp:3491
bool TerminateThread(ThreadHandle hThread)
Forcibly kill a thread.
Definition Utils.cpp:4316
bool GetFirstFreeBitLocN(const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
Find the first run of num consecutive 0 bits.
Definition Utils.cpp:3722
bool StartSignalThread(ShutdownSignalCallback cb)
Start the dedicated signal-handling thread (POSIX only).
Definition Utils.cpp:4402
bool GetCurrentThreadUniqueID(uint32 &tid)
Get a process-unique id for the calling thread.
Definition Utils.cpp:4461
int32 AtomicIncrement32(int32 volatile &v)
Atomically increment a 32-bit value.
Definition Utils.cpp:4038
bool GetDesktopSize(uint32 &width, uint32 &height)
Get the primary desktop resolution.
Definition Utils.cpp:5063
bool CheckForThreadFinished(ThreadHandle hThread)
Non-blocking check whether a thread has terminated.
Definition Utils.cpp:4190
void(* ShutdownSignalCallback)(int sig, int count)
Callback invoked (on the dedicated signal thread) when a graceful-shutdown signal is caught.
Definition Utils.h:1186
bool DestroyMutex(const char *name)
Destroy a named global mutex and remove it from the registry.
Definition Utils.cpp:998
bool UnitTest_SharedNames()
Definition Utils.cpp:2733
bool ContinueThread(ThreadHandle hThread)
Resume a thread paused with PauseThread().
Definition Utils.cpp:4450
bool DisownSharedMemorySegment(char *data)
Give up this process's ownership of a segment's name, so closing it here only unmaps.
Definition Utils.cpp:3529
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
Definition Utils.cpp:8470
void CloseProcessTerminal(uint32 proc)
Close the master side (terminal hangup: the child's foreground group gets SIGHUP and any blocked term...
Definition Utils.cpp:6526
std::list< std::string > GetProgramTrace()
Capture the current call stack.
Definition Utils.cpp:4103
uint64 hton64(const uint64_t *input)
Convert a 64-bit value from host to network byte order.
static uint16 SharedSystemInstance
Definition Utils.h:414
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:2447
void PrintBinary(void *p, uint32 size, bool asInt, const char *title)
Hex/decimal dump a memory region to stdout for debugging.
Definition Utils.cpp:8435
static std::map< std::string, Mutex * > * SharedMemoryMutexMap
Definition Utils.h:622
bool GetFirstFreeBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the first 0 (free) bit.
Definition Utils.cpp:3690
bool SignalEvent(const char *name)
Signal a named global event.
Definition Utils.cpp:1279
bool WriteProcessInput(uint32 proc, const char *data, uint32 len)
Write to the stdin of a child launched with captureOutput=true (T1.1 step 2.7c).
Definition Utils.cpp:6288
bool GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
Definition Utils.cpp:4553
bool GetNextLineEnd(const char *str, uint32 size, uint32 &len, uint32 &crSize)
Find the end of the current line.
Definition Utils.cpp:8509
bool GetBit(uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
Read bit loc.
Definition Utils.cpp:3940
uint64 ntoh64(const uint64 *input)
Convert a 64-bit value from network to host byte order.
Definition Utils.cpp:3659
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
Definition Utils.cpp:4711
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:6334
int ToOSPriority(int pri)
Map a CMSDK priority value to the platform's native priority scale.
Definition Utils.cpp:4975
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap
Definition Utils.h:625
bool StopSignalThread()
Stop the dedicated signal thread and join it.
Definition Utils.cpp:4425
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:6538
bool SetBitN(uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
Set num consecutive bits starting at loc to value.
Definition Utils.cpp:3877
bool Reset32BitField(char *bitfield, uint32 bytesize)
Zero the whole bitfield, marking every bit as free.
Definition Utils.cpp:3684
bool StartDrumBeat(uint32 id)
Start (or resume) a previously created drum beat.
Definition Utils.cpp:822
bool TextEndsWith(const char *str, const char *end, bool caseSensitive=true)
Test whether str ends with end.
Definition Utils.cpp:9686
bool UnitTest_Timer()
Self test for the Timer class.
Definition Utils.cpp:2460
bool SetBit(uint32 loc, bit value, char *bitfield, uint32 bytesize)
Set bit loc to value.
Definition Utils.cpp:3845
bool GetCurrentThread(ThreadHandle &thread)
Get the handle of the calling thread.
Definition Utils.cpp:4501
bool RenameConsoleWindow(const char *name, bool prepend=false)
Set the console window title.
Definition Utils.cpp:5083
bool TryReapThread(ThreadHandle &hThread)
Definition Utils.cpp:4240
bool UtilsTest()
Run the built-in self test of the utils module.
Definition Utils.cpp:8393
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:3680
uint32 TextReplaceCharsInPlace(char *str, uint32 size, char find, char replace)
Replace every occurrence of a character, in place.
Definition Utils.cpp:9625
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:8491
void ClearStaleSharedSegments(uint16 port)
Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.
Definition Utils.cpp:3648
std::pair< uint32, ProcessData * > Proc_Pair
Definition Utils.h:667
bool GetOSCPUUsage(double &percentUse)
Get the instantaneous total OS CPU usage.
Definition Utils.cpp:4876
bool GetCurrentThreadOSID(uint32 &tid)
Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
Definition Utils.cpp:4481
bool SeedRandomValues(uint32 seedvalue=0)
Seed the pseudo-random generator.
Definition Utils.cpp:10125
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
Definition Utils.cpp:7662
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
Definition Utils.cpp:7672
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
Definition Utils.cpp:8787
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
Definition Utils.cpp:9195
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
Definition Utils.cpp:8074
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
Definition Utils.cpp:10049
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:7507
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
Definition Utils.cpp:6977
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
Definition Utils.cpp:8672
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:6712
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
Definition Utils.cpp:9488
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
Definition Utils.cpp:10272
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
Definition Utils.cpp:9440
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
Definition Utils.cpp:9599
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
Definition Utils.cpp:6706
uint16 GetCPUArchitecture()
CPU architecture id.
Definition Utils.cpp:7068
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:9232
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:9001
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:8542
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
Definition Utils.cpp:9214
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
Definition Utils.cpp:7720
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
Definition Utils.cpp:8000
const char * GetSystemArchitecture()
Architecture name string, e.g.
Definition Utils.cpp:7216
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:8604
std::string GetCommandLinePath()
Get the directory portion of the executable path.
Definition Utils.cpp:6666
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
Definition Utils.cpp:6724
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
Definition Utils.cpp:7769
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
Definition Utils.cpp:9979
uint64 GetCPUSpeed()
Nominal CPU clock speed.
Definition Utils.cpp:7105
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
Definition Utils.cpp:8692
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
Definition Utils.cpp:8974
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
Definition Utils.cpp:9340
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
Definition Utils.cpp:8554
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
Definition Utils.cpp:9187
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:9746
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
Definition Utils.cpp:8345
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
Definition Utils.cpp:9392
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:9097
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:8946
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
Definition Utils.cpp:9903
uint16 GetCPUCount()
Number of logical CPU cores.
Definition Utils.cpp:7049
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
Definition Utils.cpp:7483
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:8646
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
Definition Utils.cpp:7009
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
Definition Utils.cpp:8712
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
Definition Utils.cpp:9989
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
Definition Utils.cpp:10543
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
Definition Utils.cpp:7928
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
Definition Utils.cpp:8565
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
Definition Utils.cpp:7305
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:9131
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:8928
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
Definition Utils.cpp:6619
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
Definition Utils.cpp:9079
uint64 GetSystemMemorySize()
Total physical RAM installed.
Definition Utils.cpp:7152
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:7988
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
Definition Utils.cpp:7688
FileDetails GetFileDetails(const char *filename)
Stat a file.
Definition Utils.cpp:9817
double RandomValue()
Uniform random double in [0,1).
Definition Utils.cpp:10131
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
Definition Utils.cpp:7526
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
Definition Utils.cpp:6689
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:8619
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
Definition Utils.cpp:8042
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
Definition Utils.cpp:7860
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
Definition Utils.cpp:9884
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:7781
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
Definition Utils.cpp:7456
std::string GetLocalHostnameString()
Local hostname as std::string.
Definition Utils.cpp:7916
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
Definition Utils.cpp:9969
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
Definition Utils.cpp:9812
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
Definition Utils.cpp:8199
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
Definition Utils.cpp:8586
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
Definition Utils.cpp:9179
bool DeleteAFile(const char *filename, bool force)
Delete a file.
Definition Utils.cpp:9368
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
Definition Utils.cpp:9372
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
Definition Utils.cpp:10177
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
Definition Utils.cpp:6683
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
Definition Utils.cpp:9031
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:8769
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:9312
std::string GetCurrentDir()
Current working directory.
Definition Utils.cpp:9733
std::string GetCommandLine()
Get the full original command line as one string.
Definition Utils.cpp:6660
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:8719
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
Definition Utils.cpp:9807
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:9061
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
Definition Utils.cpp:7757
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
Definition Utils.cpp:9532
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:9253
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
Definition Utils.cpp:9933
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:9951
const char * GetFileBasename(const char *filename)
Filename portion of a path.
Definition Utils.cpp:9717
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
Definition Utils.cpp:6912
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:7175
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:9915
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:8912
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
Definition Utils.cpp:10546
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
Definition Utils.h:1494
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:8548
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
Definition Utils.cpp:10010
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
Definition Utils.cpp:8528
const char * GetComputerName()
Get this machine's hostname.
Definition Utils.cpp:6930
std::string GetFilePath(const char *filename)
Directory portion of a path.
Definition Utils.cpp:9701
const char * GetSystemOSName()
OS name string, e.g.
Definition Utils.cpp:7277
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
Definition Utils.cpp:10214
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
Definition Utils.cpp:8015
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:9999
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:8865
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
Definition Utils.cpp:10168
std::string BytifyRate(double val)
Format a byte rate, e.g.
Definition Utils.cpp:10260
bool ClearUtilsMaps()
Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps).
Definition Utils.cpp:89
uint32 GetDataTypeID(const char *typeName)
Inverse of GetDataTypeName(): look up the numeric datatype id for a type name.
Definition Utils.cpp:182
std::string GetDataTypeName(uint32 datatype)
Translate a CMSDK datatype id (e.g.
Definition Utils.cpp:157
Wire/storage layout of one log record: fixed header immediately followed by the message text.
Definition Utils.h:245
uint32 source
Definition Utils.h:249
uint32 size
Definition Utils.h:246
std::string toJSON()
Serialize the entry (header fields + text) as a JSON object string.
Definition Utils.cpp:298
uint8 level
Definition Utils.h:251
uint64 time
Definition Utils.h:248
bool setText(char *text, uint32 len)
Copy len bytes of text into the payload area and update size.
Definition Utils.cpp:287
uint8 subject
Definition Utils.h:250
uint8 type
Definition Utils.h:252
uint32 cid
Definition Utils.h:247
const char * getText(uint32 &len)
Access the text payload stored after the header.
Definition Utils.cpp:280
std::string toXML()
Serialize the entry as an XML fragment.
Definition Utils.cpp:306
Bookkeeping record for one periodic "drum beat" timer.
Definition Utils.h:440
Existence, type, permission and timestamp information for one file, as returned by GetFileDetails().
Definition Utils.h:1908
Description of one local network interface (IPv4 address, MAC and names).
Definition Utils.h:1649
char friendlyName[MAXKEYNAMELEN+1]
Definition Utils.h:1653
char name[MAXKEYNAMELEN+1]
Definition Utils.h:1652
POSIX capture bookkeeping for children started via NewProcessEx(captureOutput).
Definition Utils.h:661
int errFD
Parent read-end of the child's stderr (-1 = not captured).
Definition Utils.h:664
int outFD
Parent read-end of the child's stdout (-1 = not captured).
Definition Utils.h:663
Snapshot from ProbeProcessWait(): is the child (group) alive, is it blocked reading stdin,...
Definition Utils.h:1418
uint64 cpuTimeMs
cumulative user+sys CPU across the process group, in ms
Definition Utils.h:1422
bool waitingStdin
blocked reading fd 0 (exact on Linux; best-effort composite elsewhere)
Definition Utils.h:1421
bool alive
process (or group) still exists
Definition Utils.h:1419
bool waitExact
true only when the OS reported the exact blocking syscall (Linux /proc/<pid>/syscall)
Definition Utils.h:1420
One (time, entry) pair inside a TimeQueue.
Definition Utils.h:925
uint64 time
Definition Utils.h:926
T entry
Definition Utils.h:927
One scheduled entry inside a Timer: id, active window and platform timer handle.
Definition Utils.h:674
A single timer expiry: which timer fired and when.
Definition Utils.h:692