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();
498 void setCancelSafe(bool on);
499protected:
500 char *name;
502 uint32 osid;
503 uint32 total;
504 uint32 count;
505 #ifdef WINDOWS
506 HANDLE mutex;
507 #else
508 //sem_t* semaphore;
509 pthread_mutex_t* mutex;
510 #endif
511};
512
513
520public:
522 Semaphore(uint32 maxCount = 100);
524 Semaphore(const char* name, uint32 maxCount = 100);
525 ~Semaphore();
527 bool wait();
529 bool wait(uint32 timeout);
531 bool signal();
532// bool destroy();
533 char *name;
534protected:
535 #ifdef WINDOWS
536 HANDLE semaphore;
537 #else
538 #ifdef __APPLE__
539 void* semaphore_impl; /* dispatch_semaphore_t when name==NULL, else char* to shared memory */
540 #else
541 sem_t* semaphore;
542 #endif
543 #endif
544};
545
550class Event {
551public:
553 Event();
555 Event(const char* name);
556 ~Event();
558 bool waitNext();
560 bool waitNext(uint32 timeout);
562 bool signal();
563// bool destroy();
564protected:
565 char *name;
566 #ifdef WINDOWS
567 HANDLE event;
568 #else
569 pthread_cond_t* event;
570 pthread_mutex_t* mutex;
571 #endif
572};
573
578bool EnterMutex(const char* name, uint32 ms, bool autocreate = true);
580bool LeaveMutex(const char* name);
582bool DestroyMutex(const char* name);
583
587Semaphore* GetSemaphore(const char* name, bool autocreate = true);
589bool WaitForSemaphore(const char* name, uint32 ms, bool autocreate = true);
591bool SignalSemaphore(const char* name);
593bool DestroySemaphore(const char* name);
594
596bool WaitNextEvent(const char* name, uint32 ms, bool autocreate = true);
598bool SignalEvent(const char* name);
600bool DestroyEvent(const char* name);
601
603
605static std::map<std::string, Mutex*>* SharedMemoryMutexMap = NULL;
606typedef std::pair<std::string, Mutex*> SharedMemoryMutexMapPair;
608static std::map<std::string, Semaphore*>* SharedMemorySemaphoreMap = NULL;
609typedef std::pair<std::string, Semaphore*> SharedMemorySemaphoreMapPair;
611static std::map<std::string, Event*>* SharedMemoryEventMap = NULL;
612typedef std::pair<std::string, Event*> SharedMemoryEventMapPair;
613
614#ifdef WINDOWS
615struct ProcessData {
616 ProcessData() { hOutRead = NULL; hErrRead = NULL; hInWrite = NULL; hJob = NULL; }
617 PROCESS_INFORMATION procInfo;
618 STARTUPINFO si;
619 HANDLE hOutRead;
620 HANDLE hErrRead;
626 HANDLE hInWrite;
633 HANDLE hJob;
634};
635static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
636typedef std::pair <uint32, ProcessData*> Proc_Pair;
637static HANDLE ghJob = NULL;
638#else
645 ProcessData() { outFD = -1; errFD = -1; }
646 int outFD;
647 int errFD;
648};
649static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
650typedef std::pair <uint32, ProcessData*> Proc_Pair;
651#endif
652
655
658 uint32 globalID;
659 uint32 id;
660 uint64 start;
661 uint64 end;
662 uint32 interval;
663 #ifdef WINDOWS
664 HANDLE handle;
665 #else
666 #ifdef __APPLE__
667 dispatch_source_t handle;
668 #else
669 timer_t handle;
670 #endif
671 #endif
672};
673
676 uint32 id;
677 uint64 time;
678};
679
686class Timer {
687public:
689 static std::map<uint32, Timer*>* timers;
690
691 Timer();
692 ~Timer();
693
700 bool addTimer(uint32 id, uint32 interval, uint64 start = 0, uint64 end = 0);
702 bool triggerTimer(uint32 id);
708 bool waitForTimer(uint32 timeout, uint32& id, uint64& time);
710 bool removeTimer(uint32 id);
711
712private:
713 uint32 globalID;
714 Mutex mutex;
715 Semaphore semaphore;
716 std::queue<TimerTrigger*> triggers;
717 std::map<uint32, TimerSchedule*> schedules;
718 std::list<TimerSchedule*> oldSchedules;
719};
720
721#ifdef WINDOWS
723 void CALLBACK TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired);
724#else
726 static void TimerCallback(int sig, siginfo_t *siginfo, void *context);
727#endif
729bool UnitTest_Timer();
731bool UnitTest_Utils();
733
735// Wait Queue //
737
746template <typename T>
748public:
750 virtual ~WaitQueue() {}
751
753 bool add(T entry) {
754 if (!mutex.enter(200, __FUNCTION__))
755 return false;
756 internalQueue.push(entry);
757 semaphore.signal();
758 mutex.leave();
759 return true;
760 }
761
762 uint32 getCount() {
763 uint32 size;
764 if (!mutex.enter(200, __FUNCTION__))
765 return 0;
766 size = (uint32)internalQueue.size();
767 mutex.leave();
768 return size;
769 }
770
771 bool peekFirst(T& first) {
772 if (!mutex.enter(200, __FUNCTION__))
773 return false;
774 if (!internalQueue.size()) {
775 mutex.leave();
776 return false;
777 }
778 first = internalQueue.front();
779 mutex.leave();
780 return true;
781 }
782
783 bool takeFirst(T& first) {
784 if (!mutex.enter(200, __FUNCTION__))
785 return false;
786 if (!internalQueue.size()) {
787 mutex.leave();
788 return false;
789 }
790 first = internalQueue.front();
791 internalQueue.pop();
792 mutex.leave();
793 return true;
794 }
795
797 bool waitForAndPeekFirst(T& first, uint32 timeoutMS) {
798 if (!mutex.enter(200, __FUNCTION__))
799 return false;
800 if (internalQueue.size()) {
801 first = internalQueue.front();
802 mutex.leave();
803 return true;
804 }
805 mutex.leave();
806 if (!semaphore.wait(timeoutMS))
807 return false;
808 if (!mutex.enter(200, __FUNCTION__))
809 return false;
810 if (internalQueue.size()) {
811 first = internalQueue.front();
812 mutex.leave();
813 return true;
814 }
815 else {
816 mutex.leave();
817 return false;
818 }
819 }
820
823 bool waitForAndTakeFirst(T& first, uint32 timeoutMS) {
824 if (!mutex.enter(200, __FUNCTION__))
825 return false;
826 if (internalQueue.size()) {
827 first = internalQueue.front();
828 internalQueue.pop();
829 mutex.leave();
830 return true;
831 }
832 mutex.leave();
833 if (!semaphore.wait(timeoutMS))
834 return false;
835 if (!mutex.enter(200, __FUNCTION__))
836 return false;
837 if (internalQueue.size()) {
838 first = internalQueue.front();
839 internalQueue.pop();
840 mutex.leave();
841 return true;
842 }
843 else {
844 mutex.leave();
845 return false;
846 }
847 }
848
849 virtual bool clear() {
850 if (!mutex.enter(200, __FUNCTION__))
851 return false;
852 std::queue<T> empty;
853 std::swap(internalQueue, empty);
854 mutex.leave();
855 return true;
856 }
857
858protected:
861 std::queue<T> internalQueue;
862};
863
866template <typename T>
867class WaitQueuePointer : public WaitQueue<T> {
868public:
870 virtual ~WaitQueuePointer() { clear(); }
871
874 T waitForAndTakeFirst(uint32 timeoutMS) {
875 T first;
876 if (WaitQueue<T>::waitForAndTakeFirst(first, timeoutMS))
877 return first;
878 else
879 return NULL;
880 }
881
883 virtual bool clear() {
884 if (!WaitQueue<T>::mutex.enter(200, __FUNCTION__))
885 return false;
886 while (WaitQueue<T>::internalQueue.size()) {
887 delete(WaitQueue<T>::internalQueue.front());
889 }
890 WaitQueue<T>::mutex.leave();
891 return true;
892 }
893};
894
895
897// Time Queue //
899
901template <typename T>
903 uint64 time;
905};
906
909template <typename T>
911public:
913 virtual ~TimeQueue() {}
914
916 bool add(uint64 time, T entry) {
917 if (!mutex.enter(200, __FUNCTION__))
918 return false;
919 TimeQueueEntry<T> newEntry;
920 newEntry.time = time;
921 newEntry.entry = entry;
922 typename std::list< TimeQueueEntry<T> >::iterator i = internalList.begin(),
923 e = internalList.end();
924 while (i != e) {
925 if (time < (*i).time) {
926 internalList.insert(i, newEntry);
927 mutex.leave();
928 return true;
929 }
930 i++;
931 }
932 internalList.push_back(newEntry);
933 mutex.leave();
934 return true;
935 }
936
937 uint32 getCount() {
938 uint32 size;
939 if (!mutex.enter(200, __FUNCTION__))
940 return 0;
941 size = (uint32)internalList.size();
942 mutex.leave();
943 return size;
944 }
945
947 bool getNextEntryDue(T& entry) {
948 if (!mutex.enter(200, __FUNCTION__))
949 return false;
950 if (!internalList.size()) {
951 mutex.leave();
952 return false;
953 }
954 uint64 now = GetTimeNow();
955 TimeQueueEntry<T> first = internalList.front();
956 if (first.time < now) {
957 internalList.pop_front();
958 entry = first.entry;
959 mutex.leave();
960 return true;
961 }
962 mutex.leave();
963 return false;
964 }
965
966 virtual bool clear() {
967 if (!mutex.enter(200, __FUNCTION__))
968 return false;
969 std::list< TimeQueueEntry<T> > empty;
970 std::swap(internalList, empty);
971 mutex.leave();
972 return true;
973 }
974
975protected:
977 std::list< TimeQueueEntry<T> > internalList;
978};
979
982template <typename T>
983class TimeQueuePointer : public TimeQueue<T> {
984public:
986 virtual ~TimeQueuePointer() { clear(); }
987
990 T first;
992 return first;
993 else
994 return NULL;
995 }
996
998 virtual bool clear() {
999 if (!TimeQueue<T>::mutex.enter(200, __FUNCTION__))
1000 return false;
1001 typename std::list< TimeQueueEntry<T> >::iterator i = TimeQueue<T>::internalList.begin(),
1003 while (i != e) {
1004 delete((*i).entry);
1005 i++;
1006 }
1008 TimeQueue<T>::mutex.leave();
1009 return true;
1010 }
1011};
1012
1013
1015// Shared Memory //
1017
1019
1025
1031char* CreateSharedMemorySegment(const char* name, uint64 size, bool force = false);
1035char* OpenSharedMemorySegment(const char* name, uint64 size);
1039bool CloseSharedMemorySegment(char* data, uint64 size);
1044void ClearStaleSharedSegments(uint16 port);
1045// Destroy named shared memory segment
1046// bool DestroySharedMemorySegment(char* data, uint32 size);
1047
1049
1054
1056uint64 ntoh64(const uint64 *input);
1058uint64 hton64(const uint64_t *input);
1059
1062uint32 Calc32BitFieldSize(uint32 bitsize);
1064bool Reset32BitField(char* bitfield, uint32 bytesize);
1068bool GetFirstFreeBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1072bool GetFirstFreeBitLocN(const char* bitfield, uint32 bytesize, uint32 num, uint32& loc);
1074bool SetBit(uint32 loc, bit value, char* bitfield, uint32 bytesize);
1077bool SetBitN(uint32 loc, uint32 num, bit value, char* bitfield, uint32 bytesize);
1079bool GetBit(uint32 loc, const char* bitfield, uint32 bytesize, bit& val);
1081bool GetLastOccupiedBitLoc(const char* bitfield, uint32 bytesize, uint32& loc);
1082
1085std::string GetBitFieldAsString(const char* bitfield, uint32 bytesize, uint32 size);
1088std::string PrintBitFieldString(const char* bitfield, uint32 bytesize, uint32 size, const char* title);
1089
1091
1092
1094// Threading //
1096
1099
1103std::string PrintProgramTrace(uint32 startLine = 0, uint32 endLine = 0);
1105std::list<std::string> GetProgramTrace();
1106
1108int32 AtomicIncrement32(int32 volatile &v);
1110int64 AtomicIncrement64(int64 volatile &v);
1112int32 AtomicDecrement32(int32 volatile &v);
1114int64 AtomicDecrement64(int64 volatile &v);
1115
1117bool Sleep(uint32 ms);
1118
1125bool CreateThread(THREAD_FUNCTION func, void* args, ThreadHandle& thread, uint32 &osID);
1126
1128bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS = 0);
1129bool ReapThread(ThreadHandle& hThread);
1130bool TryReapThread(ThreadHandle& hThread);
1131
1134
1137bool TerminateThread(ThreadHandle hThread);
1138
1147typedef void (*ShutdownSignalCallback)(int sig, int count);
1148
1158
1168
1172bool StopSignalThread();
1173
1176bool PauseThread(ThreadHandle hThread);
1177
1179bool ContinueThread(ThreadHandle hThread);
1180
1182bool GetCurrentThreadUniqueID(uint32 &tid);
1183
1185bool GetCurrentThreadOSID(uint32 &tid);
1186
1188bool GetCurrentThread(ThreadHandle& thread);
1189
1191bool IsThreadRunning(ThreadHandle hThread);
1192
1196
1197#if defined WINDOWS
1198 #define FileTimeToUint64(ft) (((uint64)(ft.dwHighDateTime))<<32)|((uint64)ft.dwLowDateTime)
1199#endif
1200
1204bool GetCPUTicks(ThreadHandle hThread, uint64& ticks);
1205
1207bool GetCPUTicks(uint64& ticks);
1208
1210bool GetProcessCPUTicks(uint64& ticks);
1211
1213bool GetProcessCPUTicks(uint32 osProcID, uint64& ticks);
1214
1222bool GetProcAndOSCPUUsage(double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1223
1231bool GetProcAndOSCPUUsage(uint32 osProcID, double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1232
1234bool GetOSCPUUsage(double& percentUse);
1235
1237bool GetThreadPriority(ThreadHandle hThread, uint16 priority);
1238
1240bool SetThreadPriority(ThreadHandle hThread, uint16 priority);
1241
1243int ToOSPriority(int pri);
1244
1246int FromOSPriority(int pri);
1247
1249bool SignalThread(ThreadHandle hThread, int32 signal);
1250
1252
1254// Desktop //
1256
1259
1261bool GetDesktopSize(uint32& width, uint32& height);
1262
1264bool RenameConsoleWindow(const char* name, bool prepend = false);
1265
1267bool MoveConsoleWindow(int32 x = -1, int32 y = -1, int32 w = -1, int32 h = -1);
1268
1270
1272// Processes //
1274
1275#define PROC_ERROR 0
1276#define PROC_TERMINATED 1
1277#define PROC_NOTSTARTED 2
1278#define PROC_RUNNING 3
1279#define PROC_TIMEOUT 4
1280
1281#define NUM_PIPES 2
1282#define PARENT_WRITE_PIPE 0
1283#define PARENT_READ_PIPE 1
1284/* always in a pipe[], pipe[0] is for read and
1285 pipe[1] is for write */
1286#define READ_FD 0
1287#define WRITE_FD 1
1288#define PARENT_READ_FD ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
1289#define PARENT_WRITE_FD ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
1290#define CHILD_READ_FD ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
1291#define CHILD_WRITE_FD ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
1292
1293#define PROCBUFSIZE 4096
1294
1297
1305int RunOSCommand(const char* cmdline, const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString);
1310uint32 NewProcess(const char* cmdline, const char* initdir = NULL, const char* title = NULL,
1311 int16 x = -1, int16 y = -1, int16 w = -1, int16 h = -1);
1315uint8 GetProcessStatus(uint32 proc, int &returncode);
1317bool EndProcess(uint32 proc);
1318
1341uint32 NewProcessEx(const char* cmdline, const char* initdir, const char* title,
1342 const std::map<std::string, std::string>* env,
1343 bool captureOutput, bool ignoreOutput, bool newProcessGroup,
1344 int posixParentDeathSig = 0, bool posixUseShell = false);
1349bool ReadProcessOutput(uint32 proc, std::string& out, std::string& err);
1359bool WriteProcessInput(uint32 proc, const char* data, uint32 len);
1365bool CloseProcessInput(uint32 proc);
1371void ReleaseProcessCapture(uint32 proc);
1376bool SendProcessBreak(uint32 proc, int sig);
1385
1393bool ProbeProcessWait(uint32 pid, ProcessWaitInfo& out);
1413uint32 NewProcessTerminal(const char* cmdline, const char* initdir,
1414 const std::map<std::string, std::string>* env,
1415 uint16 cols = 0, uint16 rows = 0);
1420bool ReadProcessTerminal(uint32 proc, std::string& out, bool& eofOut);
1423bool WriteProcessTerminal(uint32 proc, const char* data, uint32 len);
1426bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows);
1430void CloseProcessTerminal(uint32 proc);
1435uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode);
1437uint32 GetLocalProcessID();
1438
1440
1442// DLL Libraries //
1444
1445#ifdef WINDOWS
1446 #define DLLHandle HINSTANCE
1447#else // WINDOWS
1448 #define DLLHandle void*
1449#endif // WINDOWS
1450
1453
1455typedef int (* LibraryFunction)();
1456
1457class CommandLineInfo;
1461public:
1465 std::string CommandLineExec;
1468 std::vector<std::string> CommandLineItems;
1469 std::map<std::string, std::string> CommandLineArgs;
1470};
1471
1472
1473
1477bool SetCommandLine(int argc, char* argv[]);
1479std::string GetCommandLine();
1481std::string GetCommandLinePath();
1483std::string GetCommandLineExecutable();
1485std::string GetCommandLineExecutableOnly();
1487uint32 GetCommandLineArgCount();
1489std::string GetCommandLineArg(uint16 n);
1493std::string GetCommandLineArg(const char* key);
1497bool HasCommandLineArg(const char* key, std::string& value);
1498
1500class Library {
1501public:
1504 static std::string patchLibraryFilename(const char* filename, const char* path = NULL);
1505
1506 Library();
1507 ~Library();
1509 bool load(const char* filename);
1511 LibraryFunction getFunction(const char* funcName);
1512private:
1513 DLLHandle handle;
1514};
1515
1517Library* OpenLibrary(const char* libName);
1518
1520
1523
1525const char* GetComputerName();
1526
1528uint64 GetProcessMemoryUsage();
1531
1533uint16 GetCPUCount();
1534
1536uint16 GetCPUArchitecture();
1537
1539uint64 GetCPUSpeed();
1540
1542uint64 GetSystemMemorySize();
1543
1545bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM);
1546
1548const char* GetSystemArchitecture();
1549
1551const char* GetSystemOSName();
1552
1557bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build, char* text, uint16 textSize);
1558
1560
1561//bool RunOSTextCommand(const char* cmd, char* result, uint32 size);
1562
1563//extern char OSLocalHostName[1024];
1564//extern char OSArchitectureName[1024];
1565//extern char OSName[1024];
1566
1567
1569// Sockets //
1571
1577
1578#ifdef WINDOWS
1580 bool CheckNetworkInit();
1581 #define CHECKNETWORKINIT utils::CheckNetworkInit();
1582#else
1583 #define CHECKNETWORKINIT
1584 #define WSAEWOULDBLOCK EAGAIN
1585#endif
1586
1592bool GetSocketError(int wsaError, char* errorString, uint16 errorStringMaxSize, bool* isRecoverable);
1593
1597std::string GetLastOSErrorMessage();
1598
1600bool WaitForSocketReadability(SOCKET s, int32 timeout);
1602bool WaitForSocketWriteability(SOCKET s, int32 timeout);
1603
1608
1616
1618bool LookupIPAddress(const char* name, uint32& address);
1620bool LookupHostname(uint32 address, char* name, uint32 maxSize);
1622std::string GetLocalHostnameString();
1624bool GetLocalHostname(char* name, uint32 maxSize);
1626bool IsLocalIPAddress(const char* addr);
1628bool IsLocalIPAddress(uint32& address);
1630bool GetLocalIPAddress(uint32& address);
1632uint32* GetLocalIPAddresses(uint32& count);
1634bool GetLocalMACAddress(uint64& address);
1636uint64* GetLocalMACAddresses(uint32& count);
1640bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort);
1641
1642#define LOCALHOSTIP 16777343 // 127.0.0.1 as 32-bit dec
1643#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
1644#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
1645
1646#define GETIPPORT(a) *(uint16*)((char*)&a + sizeof(uint32))
1647#define GETIPADDRESS(a) *(uint32*)&a
1648#define GETIPADDRESSPORT(a,p) (((uint32)a)) | (((uint64)p)<<32)
1649#define GETIPADDRESSQUAD(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3]
1650#define GETIPADDRESSQUADPORT(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3], ((uint16*)&a)[2]
1651
1653
1658
1659#ifdef WINDOWS
1661 std::string GetRegistryKeyInfo(const char* key, HKEY &hKeyRoot);
1663 std::string GetRegistryParentKeyInfo(const char* key, HKEY &hKeyRoot);
1664#endif // WINDOWS
1666uint32 ReadRegistryDWORD(const char* key, const char* entry);
1668uint64 ReadRegistryQWORD(const char* key, const char* entry);
1670std::string ReadRegistryString(const char* key, const char* entry);
1672bool WriteRegistryDWORD(const char* key, const char* entry, uint32 value);
1674bool WriteRegistryQWORD(const char* key, const char* entry, uint64 value);
1676bool WriteRegistryString(const char* key, const char* entry, const char* value);
1678bool DeleteRegistryEntry(const char* key, const char* entry);
1680bool DeleteRegistryKey(const char* key);
1682bool DeleteRegistryTree(const char* root, const char* key);
1683//bool CopyRegistryKey(const char* key, const char* newName);
1685bool CopyRegistryTree(const char* entry, const char* newName);
1686//bool RenameRegistryKey(const char* key, const char* newName);
1687//bool RenameRegistryTree(const char* entry, const char* newName);
1688
1689
1690
1692
1696
1698bool UtilsTest();
1700void PrintBinary(void* p, uint32 size, bool asInt, const char* title);
1702const char* stristr(const char *str, const char *substr, uint32 len = 0);
1706bool GetNextLineEnd(const char *str, uint32 size, uint32& len, uint32& crSize);
1708uint32 TextReplaceCharsInPlace(char* str, uint32 size, char find, char replace);
1710bool TextEndsWith(const char* str, const char* end, bool caseSensitive = true);
1712bool TextStartsWith(const char* str, const char* start, bool caseSensitive = true);
1717uint32 strcpyavail(char* dst, const char* src, uint32 maxlen, bool copyAvailable);
1719const char* laststrstr(const char* str1, const char* str2);
1721const char* laststristr(const char* str1, const char* str2);
1722
1724
1727
1731uint32 StringSingleReplace(std::string& text, std::string key, std::string value, bool onlyFirst);
1733uint32 StringMultiReplace(std::string& text, std::map<std::string, std::string>& map, bool onlyFirst);
1737uint32 StringScriptReplace(std::string& text, std::string name, std::list< std::map<std::string, std::string> >& list);
1738
1740
1745
1747std::string TextCapitalise(const char* text);
1749std::string TextUppercase(const char* text);
1751std::string TextLowercase(const char* text);
1753std::string TextIndent(const char* text, const char* indent);
1755std::string TextUnindent(const char* text);
1757std::string TextTrimQuotes(const char* text);
1762std::string TextTrim(const char* text);
1771std::multimap<std::string, std::string> TextMultiMapSplit(const char* text, const char* outersplit, const char* innersplit);
1781std::map<std::string, std::string> TextMapSplit(const char* text, const char* outersplit, const char* innersplit);
1783std::string TextJoin(std::vector<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1785std::string TextJoin(std::list<std::string> &list, const char* split, uint32 start = 0, uint32 count = 0);
1788std::string TextJoin(std::map<std::string, std::string> &map, const char* innersplit, const char* outersplit, bool keyquotes, bool valquotes);
1790std::string TextJoinJSON(std::map<std::string, std::string> &map);
1792std::string TextJoinXML(std::map<std::string, std::string> &map, const char* innernodeName, const char* outernodeName);
1799std::vector<std::string> TextListSplit(const char* text, const char* split, bool keepEmpty = true, bool autoTrim = false);
1801std::vector<std::string> TextListSplitLines(const char* text, bool keepEmpty = true, bool autoTrim = false);
1803std::vector<std::string> TextListBreakLines(const char* text, uint32 maxLineLength = 80);
1805std::string TextListBreakLines(const char* text, uint32 maxLineLength, const char* breakstr);
1807std::string TextVectorConcat(std::vector<std::string>, const char* sep, bool allowEmpty = true);
1809std::vector<std::string> TextCommandlineSplit(const char* cmdline);
1811char** SplitCommandline(const char* cmdline, int& argc);
1813wchar_t** SplitCommandlineW(const char* cmdline, int& argc);
1815bool DeleteCommandline(char** argv, int argc);
1816
1818
1821
1830std::string StringFormat(const char *format, ...);
1832char* StringFormat(uint32& size, const char *format, ...);
1834bool StringFormatInto(char* dst, uint32 maxsize, const char *format, ...);
1836char* StringFormatVA(uint32& size, const char *format, va_list args);
1837
1839
1842
1844unsigned char Hex2Char(const char* str);
1846unsigned char Dec2Char(const char* str);
1856int CRC32(const char *addr, uint32 length, int32 crc = 0);
1857
1859int8 CompareFloats(float64 a, float64 b);
1860
1862
1867
1881
1882#define NOSUCHFILE 0
1883#define STANDARDFILE 1
1884#define STANDARDDIR 2
1885
1890std::string ReadAFileString(std::string filename);
1908char* ReadAFile(const char* filename, uint32& length, bool binary = false);
1910char* ReadAFile(const char* dir, const char* filename, uint32& length, bool binary = false);
1915bool WriteAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1917bool WriteAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1919bool AppendToAFile(const char* filename, const char* data, uint32 length, bool binary = false);
1921bool AppendToAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary = false);
1937char* GetFileList(const char* dirname, const char* ext, uint32& count, bool fullpath, uint32 maxNameLen = 256);
1939FileDetails GetFileDetails(const char* filename);
1941std::string GetFilePath(const char* filename);
1943const char* GetFileBasename(const char* filename);
1945std::string GetCurrentDir();
1947bool DeleteAFile(const char* filename, bool force);
1949bool DeleteAFile(const char* dir, const char* filename, bool force);
1951bool DeleteADir(const char* dirname, bool force);
1953bool CreateADir(const char* dirname);
1955bool DoesADirExist(const char* dirname);
1957bool DoesAFileExist(const char* filename);
1959bool DeleteFilesInADir(const char* dirname, bool force);
1961bool ChangeAFileAttr(const char* filename, bool read, bool write);
1963bool MoveAFile(const char* oldfilename, const char* newfilename, bool force = false);
1965bool MoveAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1967bool CopyAFile(const char* oldfilename, const char* newfilename, bool force = false);
1969bool CopyAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force = false);
1970
1972
1987
1989char* Int2Ascii(int64 value, char* result, uint16 size, uint8 base);
1991char* Uint2Ascii(uint64 value, char* result, uint16 size, uint8 base);
1995unsigned char* Ascii2UTF16LE(const char* ascii, uint32 len, uint32& size);
1996
1998bool IsTextNumeric(const char* ascii, uint32 start = 0, uint32 end = 0);
2000int64 Ascii2Int64(const char* ascii, uint32 start = 0, uint32 end = 0);
2002uint64 Ascii2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
2004uint64 AsciiHex2Uint64(const char* ascii, uint32 start = 0, uint32 end = 0);
2006int32 Ascii2Int32(const char* ascii, uint32 start = 0, uint32 end = 0);
2008uint32 Ascii2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
2010uint32 AsciiHex2Uint32(const char* ascii, uint32 start = 0, uint32 end = 0);
2012float64 Ascii2Float64(const char* ascii, uint32 start = 0, uint32 end = 0);
2013
2015char* TextSubstringCopy(const char* ascii, uint32 start, uint32 end);
2016
2023std::string DecodeJSON(std::string str);
2028std::string EncodeJSON(std::string str);
2029
2031
2034
2040bool SeedRandomValues(uint32 seedvalue = 0);
2047double RandomValue();
2049double RandomValue(double to);
2051double RandomValue(double from, double to);
2053double RandomValue(double from, double to, double interval);
2055int64 RandomInt(int64 from = 0, int64 to = 100);
2056
2061std::string BytifySize(double val);
2063std::string BytifySizes(double val1, double val2);
2065std::string BytifyRate(double val);
2067std::string BytifyRates(double val1, double val2);
2068
2070 // end of utils
2072
2073} // namespace utils
2074} // namespace cmlabs
2075
2076#endif //_UTILS_H_
2077
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:1448
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:48
~CleanShutdown()
Destroys all lazily-created global utility maps via ClearUtilsMaps().
Definition Utils.cpp:52
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:288
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
Definition Utils.cpp:182
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:319
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:367
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:193
static bool SetLogLevelVerbose(uint8 level)
Set the verbose (print) level threshold for all topics.
Definition Utils.cpp:217
Singleton snapshot of the parsed process command line (set via SetCommandLine()).
Definition Utils.h:1460
std::map< std::string, std::string > CommandLineArgs
Definition Utils.h:1469
static CommandLineInfo * CommandLineInfoSingleton
Definition Utils.h:1462
std::string CommandLineExecOnly
Definition Utils.h:1466
std::string CommandLineExecPath
Definition Utils.h:1467
std::vector< std::string > CommandLineItems
Definition Utils.h:1468
pthread_cond_t * event
Definition Utils.h:569
bool waitNext()
Block until the next signal() occurs.
Definition Utils.cpp:1720
Event()
Create an anonymous, process-local event.
Definition Utils.cpp:1637
bool signal()
Wake all threads currently waiting on this event.
Definition Utils.cpp:1744
pthread_mutex_t * mutex
Definition Utils.h:570
Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen).
Definition Utils.h:1500
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
Definition Utils.cpp:5883
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:5765
bool load(const char *filename)
Load a library.
Definition Utils.cpp:5795
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:463
Mutex()
Create an anonymous, process-local mutex.
Definition Utils.cpp:1040
void setCancelSafe(bool on)
Make this mutex cancellation-safe (POSIX only; no-op on Windows).
Definition Utils.cpp:1016
bool leave()
Release the mutex.
Definition Utils.cpp:1330
bool enter()
Block until the mutex is acquired.
Definition Utils.cpp:1158
pthread_mutex_t * mutex
Definition Utils.h:509
Counting semaphore, optionally named for cross-process use.
Definition Utils.h:519
Semaphore(uint32 maxCount=100)
Create an anonymous semaphore.
Definition Utils.cpp:1406
bool signal()
Increment (release) the semaphore, waking one waiter.
Definition Utils.cpp:1586
bool wait()
Block until the semaphore can be decremented.
Definition Utils.cpp:1517
bool getNextEntryDue(T &entry)
Pop the earliest entry if its due time has passed (non-blocking).
Definition Utils.h:947
uint32 getCount()
Number of scheduled entries.
Definition Utils.h:937
std::list< TimeQueueEntry< T > > internalList
Definition Utils.h:977
virtual bool clear()
Discard all scheduled entries.
Definition Utils.h:966
bool add(uint64 time, T entry)
Insert an entry sorted by its due time.
Definition Utils.h:916
T getNextEntryDue()
Pop the earliest due entry.
Definition Utils.h:989
virtual bool clear()
Delete every scheduled pointer and empty the queue.
Definition Utils.h:998
bool addTimer(uint32 id, uint32 interval, uint64 start=0, uint64 end=0)
Register a periodic timer.
Definition Utils.cpp:1814
static std::map< uint32, Timer * > * timers
Global registry mapping globalID to live Timer instances, used by the OS callbacks.
Definition Utils.h:689
bool triggerTimer(uint32 id)
Manually inject an expiry for timer id, as if it had fired now.
Definition Utils.cpp:1938
bool waitForTimer(uint32 timeout, uint32 &id, uint64 &time)
Wait for the next expiry of any registered timer.
Definition Utils.cpp:1960
bool removeTimer(uint32 id)
Unregister a timer and cancel its OS timer.
Definition Utils.cpp:1911
bool takeFirst(T &first)
Remove and return the front entry.
Definition Utils.h:783
bool waitForAndPeekFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and peek it without removal.
Definition Utils.h:797
bool add(T entry)
Append an entry and wake one waiting consumer.
Definition Utils.h:753
bool peekFirst(T &first)
Copy the front entry without removing it.
Definition Utils.h:771
std::queue< T > internalQueue
Definition Utils.h:861
bool waitForAndTakeFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and dequeue it.
Definition Utils.h:823
virtual bool clear()
Discard all queued entries.
Definition Utils.h:849
uint32 getCount()
Number of queued entries.
Definition Utils.h:762
T waitForAndTakeFirst(uint32 timeoutMS)
Convenience overload: dequeue with timeout, returning NULL instead of using an out-parameter.
Definition Utils.h:874
virtual bool clear()
Delete every queued pointer and empty the queue.
Definition Utils.h:883
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:2133
int64 AtomicDecrement64(int64 volatile &v)
Atomically decrement a 64-bit value.
Definition Utils.cpp:3111
bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows)
Resize the pseudo-terminal (TIOCSWINSZ + SIGWINCH to the child's group).
Definition Utils.cpp:5521
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:4387
bool SetSharedSystemInstance(uint32 inst)
Set the instance number used to namespace shared OS objects, allowing several independent CMSDK syste...
Definition Utils.cpp:960
static std::map< uint32, ProcessData * > * ProcessInformationMap
Definition Utils.h:649
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
Definition Utils.cpp:3584
void ReleaseProcessCapture(uint32 proc)
POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captur...
Definition Utils.cpp:4584
bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS=0)
Join a thread.
Definition Utils.cpp:3309
bool SignalSemaphore(const char *name)
Signal a named global semaphore.
Definition Utils.cpp:826
bool GetThreadPriority(ThreadHandle hThread, uint16 priority)
Query a thread's scheduling priority.
Definition Utils.cpp:3976
std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
Definition Utils.h:606
int FromOSPriority(int pri)
Map a native OS priority back to the CMSDK priority scale.
Definition Utils.cpp:4066
bool CloseProcessInput(uint32 proc)
Close a child's stdin, delivering EOF (T1.1 step 2.7c).
Definition Utils.cpp:5331
bool EndProcess(uint32 proc)
Forcibly terminate a child process.
Definition Utils.cpp:4602
std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
Definition Utils.h:609
static Mutex * SharedMemorySemaphoreMapMutex
Definition Utils.h:607
bool GetLastOccupiedBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the highest set (occupied) bit.
Definition Utils.cpp:3008
const char * laststrstr(const char *str1, const char *str2)
Find the last occurrence of str2 in str1.
Definition Utils.cpp:8624
std::pair< std::string, Event * > SharedMemoryEventMapPair
Definition Utils.h:612
bool DestroyEvent(const char *name)
Destroy a named global event.
Definition Utils.cpp:939
bool WaitForSemaphore(const char *name, uint32 ms, bool autocreate=true)
Wait on a named global semaphore.
Definition Utils.cpp:787
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:8681
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:3121
bool SetThreadPriority(ThreadHandle hThread, uint16 priority)
Set a thread's scheduling priority.
Definition Utils.cpp:3999
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:5474
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:3801
bool PauseThread(ThreadHandle hThread)
Suspend a thread's execution.
Definition Utils.cpp:3484
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:5405
static std::map< std::string, Event * > * SharedMemoryEventMap
Definition Utils.h:611
bool MoveConsoleWindow(int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
Move/resize the console window.
Definition Utils.cpp:4148
bool WriteProcessTerminal(uint32 proc, const char *data, uint32 len)
Write bytes to the child's terminal input (its stdin).
Definition Utils.cpp:5499
bool IsThreadRunning(ThreadHandle hThread)
Check whether a thread is still alive.
Definition Utils.cpp:3554
bool CreateThread(THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
Start a new OS thread.
Definition Utils.cpp:3187
int32 AtomicDecrement32(int32 volatile &v)
Atomically decrement a 32-bit value.
Definition Utils.cpp:3101
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:5052
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:4090
bool BlockShutdownSignals()
Block the graceful-shutdown signals (SIGINT, SIGTERM, SIGHUP) on the CALLING thread.
Definition Utils.cpp:3433
bool UnitTest_ProbeProcessWait()
Definition Utils.cpp:2076
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
Definition Utils.cpp:2489
int64 AtomicIncrement64(int64 volatile &v)
Atomically increment a 64-bit value.
Definition Utils.cpp:3091
uint32 GetSharedSystemInstance()
Get the current shared-system instance number.
Definition Utils.cpp:965
bool StopDrumBeat(uint32 id)
Stop a running drum beat without destroying it.
Definition Utils.cpp:594
bool EnterMutex(const char *name, uint32 ms, bool autocreate=true)
Acquire a named global mutex, creating it on first use.
Definition Utils.cpp:671
const char * laststristr(const char *str1, const char *str2)
Case-insensitive laststrstr().
Definition Utils.cpp:8649
bool ProbeProcessWait(uint32 pid, ProcessWaitInfo &out)
Probe whether a child process (group) appears blocked reading stdin (fd 0).
Definition Utils.cpp:4847
static Mutex * SharedMemoryMutexMapMutex
Definition Utils.h:604
#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:495
bool ReapThread(ThreadHandle &hThread)
Definition Utils.cpp:3267
std::string PrintProgramTrace(uint32 startLine=0, uint32 endLine=0)
Format the current call stack as printable text.
Definition Utils.cpp:3131
uint8 GetProcessStatus(uint32 proc, int &returncode)
Poll a child started with NewProcess().
Definition Utils.cpp:4519
bool(* DrumBeatFunc)(uint32 id, uint32 count)
Callback invoked on every drum-beat tick.
Definition Utils.h:418
static Mutex * SharedMemoryEventMapMutex
Definition Utils.h:610
Semaphore * GetSemaphore(const char *name, bool autocreate=true)
Look up (and optionally create) a named semaphore in the global registry.
Definition Utils.cpp:748
bool LeaveMutex(const char *name)
Release a named global mutex previously acquired with EnterMutex().
Definition Utils.cpp:711
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:4194
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:2368
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:3052
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:3033
uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode)
Wait for a child to exit.
Definition Utils.cpp:5561
uint32 GetLocalProcessID()
Get the OS process id of the current process.
Definition Utils.cpp:4185
bool EndDrumBeat(uint32 id)
Destroy a drum beat and release its OS timer.
Definition Utils.cpp:627
bool DestroySemaphore(const char *name)
Destroy a named global semaphore.
Definition Utils.cpp:858
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
Definition Utils.cpp:2604
bool TerminateThread(ThreadHandle hThread)
Forcibly kill a thread.
Definition Utils.cpp:3359
bool GetFirstFreeBitLocN(const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
Find the first run of num consecutive 0 bits.
Definition Utils.cpp:2765
bool StartSignalThread(ShutdownSignalCallback cb)
Start the dedicated signal-handling thread (POSIX only).
Definition Utils.cpp:3445
bool GetCurrentThreadUniqueID(uint32 &tid)
Get a process-unique id for the calling thread.
Definition Utils.cpp:3504
int32 AtomicIncrement32(int32 volatile &v)
Atomically increment a 32-bit value.
Definition Utils.cpp:3081
bool GetDesktopSize(uint32 &width, uint32 &height)
Get the primary desktop resolution.
Definition Utils.cpp:4106
bool CheckForThreadFinished(ThreadHandle hThread)
Non-blocking check whether a thread has terminated.
Definition Utils.cpp:3233
void(* ShutdownSignalCallback)(int sig, int count)
Callback invoked (on the dedicated signal thread) when a graceful-shutdown signal is caught.
Definition Utils.h:1147
bool DestroyMutex(const char *name)
Destroy a named global mutex and remove it from the registry.
Definition Utils.cpp:724
bool ContinueThread(ThreadHandle hThread)
Resume a thread paused with PauseThread().
Definition Utils.cpp:3493
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
Definition Utils.cpp:7476
void CloseProcessTerminal(uint32 proc)
Close the master side (terminal hangup: the child's foreground group gets SIGHUP and any blocked term...
Definition Utils.cpp:5538
std::list< std::string > GetProgramTrace()
Capture the current call stack.
Definition Utils.cpp:3146
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:1996
void PrintBinary(void *p, uint32 size, bool asInt, const char *title)
Hex/decimal dump a memory region to stdout for debugging.
Definition Utils.cpp:7441
static std::map< std::string, Mutex * > * SharedMemoryMutexMap
Definition Utils.h:605
bool GetFirstFreeBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the first 0 (free) bit.
Definition Utils.cpp:2733
bool SignalEvent(const char *name)
Signal a named global event.
Definition Utils.cpp:926
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:5301
bool GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
Definition Utils.cpp:3596
bool GetNextLineEnd(const char *str, uint32 size, uint32 &len, uint32 &crSize)
Find the end of the current line.
Definition Utils.cpp:7515
bool GetBit(uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
Read bit loc.
Definition Utils.cpp:2983
uint64 ntoh64(const uint64 *input)
Convert a 64-bit value from network to host byte order.
Definition Utils.cpp:2702
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
Definition Utils.cpp:3754
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:5347
int ToOSPriority(int pri)
Map a CMSDK priority value to the platform's native priority scale.
Definition Utils.cpp:4018
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap
Definition Utils.h:608
bool StopSignalThread()
Stop the dedicated signal thread and join it.
Definition Utils.cpp:3468
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:5550
bool SetBitN(uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
Set num consecutive bits starting at loc to value.
Definition Utils.cpp:2920
bool Reset32BitField(char *bitfield, uint32 bytesize)
Zero the whole bitfield, marking every bit as free.
Definition Utils.cpp:2727
bool StartDrumBeat(uint32 id)
Start (or resume) a previously created drum beat.
Definition Utils.cpp:548
bool TextEndsWith(const char *str, const char *end, bool caseSensitive=true)
Test whether str ends with end.
Definition Utils.cpp:8674
bool UnitTest_Timer()
Self test for the Timer class.
Definition Utils.cpp:2009
bool SetBit(uint32 loc, bit value, char *bitfield, uint32 bytesize)
Set bit loc to value.
Definition Utils.cpp:2888
bool GetCurrentThread(ThreadHandle &thread)
Get the handle of the calling thread.
Definition Utils.cpp:3544
bool RenameConsoleWindow(const char *name, bool prepend=false)
Set the console window title.
Definition Utils.cpp:4126
bool TryReapThread(ThreadHandle &hThread)
Definition Utils.cpp:3283
bool UtilsTest()
Run the built-in self test of the utils module.
Definition Utils.cpp:7399
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:2723
uint32 TextReplaceCharsInPlace(char *str, uint32 size, char find, char replace)
Replace every occurrence of a character, in place.
Definition Utils.cpp:8613
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:7497
void ClearStaleSharedSegments(uint16 port)
Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.
Definition Utils.cpp:2678
std::pair< uint32, ProcessData * > Proc_Pair
Definition Utils.h:650
bool GetOSCPUUsage(double &percentUse)
Get the instantaneous total OS CPU usage.
Definition Utils.cpp:3919
bool GetCurrentThreadOSID(uint32 &tid)
Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
Definition Utils.cpp:3524
bool SeedRandomValues(uint32 seedvalue=0)
Seed the pseudo-random generator.
Definition Utils.cpp:9113
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
Definition Utils.cpp:6668
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
Definition Utils.cpp:6678
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
Definition Utils.cpp:7793
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
Definition Utils.cpp:8201
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
Definition Utils.cpp:7080
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
Definition Utils.cpp:9037
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:6513
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
Definition Utils.cpp:5983
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
Definition Utils.cpp:7678
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:5724
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
Definition Utils.cpp:8494
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
Definition Utils.cpp:9260
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
Definition Utils.cpp:8446
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
Definition Utils.cpp:8587
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
Definition Utils.cpp:5718
uint16 GetCPUArchitecture()
CPU architecture id.
Definition Utils.cpp:6074
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:8238
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:8007
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:7548
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
Definition Utils.cpp:8220
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
Definition Utils.cpp:6726
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
Definition Utils.cpp:7006
const char * GetSystemArchitecture()
Architecture name string, e.g.
Definition Utils.cpp:6222
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:7610
std::string GetCommandLinePath()
Get the directory portion of the executable path.
Definition Utils.cpp:5678
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
Definition Utils.cpp:5736
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
Definition Utils.cpp:6775
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
Definition Utils.cpp:8967
uint64 GetCPUSpeed()
Nominal CPU clock speed.
Definition Utils.cpp:6111
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
Definition Utils.cpp:7698
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
Definition Utils.cpp:7980
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
Definition Utils.cpp:8346
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
Definition Utils.cpp:7560
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
Definition Utils.cpp:8193
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:8734
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
Definition Utils.cpp:7351
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
Definition Utils.cpp:8398
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:8103
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:7952
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
Definition Utils.cpp:8891
uint16 GetCPUCount()
Number of logical CPU cores.
Definition Utils.cpp:6055
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
Definition Utils.cpp:6489
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:7652
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
Definition Utils.cpp:6015
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
Definition Utils.cpp:7718
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
Definition Utils.cpp:8977
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
Definition Utils.cpp:9531
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
Definition Utils.cpp:6934
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
Definition Utils.cpp:7571
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
Definition Utils.cpp:6311
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:8137
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:7934
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
Definition Utils.cpp:5631
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
Definition Utils.cpp:8085
uint64 GetSystemMemorySize()
Total physical RAM installed.
Definition Utils.cpp:6158
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:6994
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
Definition Utils.cpp:6694
FileDetails GetFileDetails(const char *filename)
Stat a file.
Definition Utils.cpp:8805
double RandomValue()
Uniform random double in [0,1).
Definition Utils.cpp:9119
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
Definition Utils.cpp:6532
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
Definition Utils.cpp:5701
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:7625
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
Definition Utils.cpp:7048
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
Definition Utils.cpp:6866
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
Definition Utils.cpp:8872
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:6787
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
Definition Utils.cpp:6462
std::string GetLocalHostnameString()
Local hostname as std::string.
Definition Utils.cpp:6922
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
Definition Utils.cpp:8957
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
Definition Utils.cpp:8800
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
Definition Utils.cpp:7205
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
Definition Utils.cpp:7592
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
Definition Utils.cpp:8185
bool DeleteAFile(const char *filename, bool force)
Delete a file.
Definition Utils.cpp:8374
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
Definition Utils.cpp:8378
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
Definition Utils.cpp:9165
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
Definition Utils.cpp:5695
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
Definition Utils.cpp:8037
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:7775
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:8318
std::string GetCurrentDir()
Current working directory.
Definition Utils.cpp:8721
std::string GetCommandLine()
Get the full original command line as one string.
Definition Utils.cpp:5672
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:7725
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
Definition Utils.cpp:8795
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:8067
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
Definition Utils.cpp:6763
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
Definition Utils.cpp:8520
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:8259
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
Definition Utils.cpp:8921
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:8939
const char * GetFileBasename(const char *filename)
Filename portion of a path.
Definition Utils.cpp:8705
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
Definition Utils.cpp:5918
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:6181
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:8903
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:7918
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
Definition Utils.cpp:9534
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
Definition Utils.h:1455
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:7554
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
Definition Utils.cpp:8998
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
Definition Utils.cpp:7534
const char * GetComputerName()
Get this machine's hostname.
Definition Utils.cpp:5936
std::string GetFilePath(const char *filename)
Directory portion of a path.
Definition Utils.cpp:8689
const char * GetSystemOSName()
OS name string, e.g.
Definition Utils.cpp:6283
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
Definition Utils.cpp:9202
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
Definition Utils.cpp:7021
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:8987
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:7871
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
Definition Utils.cpp:9156
std::string BytifyRate(double val)
Format a byte rate, e.g.
Definition Utils.cpp:9248
bool ClearUtilsMaps()
Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps).
Definition Utils.cpp:62
uint32 GetDataTypeID(const char *typeName)
Inverse of GetDataTypeName(): look up the numeric datatype id for a type name.
Definition Utils.cpp:155
std::string GetDataTypeName(uint32 datatype)
Translate a CMSDK datatype id (e.g.
Definition Utils.cpp:130
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:271
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:260
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:253
std::string toXML()
Serialize the entry as an XML fragment.
Definition Utils.cpp:279
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:1869
Description of one local network interface (IPv4 address, MAC and names).
Definition Utils.h:1610
char friendlyName[MAXKEYNAMELEN+1]
Definition Utils.h:1614
char name[MAXKEYNAMELEN+1]
Definition Utils.h:1613
POSIX capture bookkeeping for children started via NewProcessEx(captureOutput).
Definition Utils.h:644
int errFD
Parent read-end of the child's stderr (-1 = not captured).
Definition Utils.h:647
int outFD
Parent read-end of the child's stdout (-1 = not captured).
Definition Utils.h:646
Snapshot from ProbeProcessWait(): is the child (group) alive, is it blocked reading stdin,...
Definition Utils.h:1379
uint64 cpuTimeMs
cumulative user+sys CPU across the process group, in ms
Definition Utils.h:1383
bool waitingStdin
blocked reading fd 0 (exact on Linux; best-effort composite elsewhere)
Definition Utils.h:1382
bool alive
process (or group) still exists
Definition Utils.h:1380
bool waitExact
true only when the OS reported the exact blocking syscall (Linux /proc/<pid>/syscall)
Definition Utils.h:1381
One (time, entry) pair inside a TimeQueue.
Definition Utils.h:902
uint64 time
Definition Utils.h:903
T entry
Definition Utils.h:904
One scheduled entry inside a Timer: id, active window and platform timer handle.
Definition Utils.h:657
A single timer expiry: which timer fired and when.
Definition Utils.h:675