10#if !defined(_UTILS_H_)
39 #include <semaphore.h>
43 #include <sys/utsname.h>
48 #include <mach/mach.h>
49 #include <mach/mach_time.h>
50 #include <dispatch/dispatch.h>
52 #include <sys/prctl.h>
57 #include <sys/syscall.h>
59 #include <sys/sysinfo.h>
61 #include <sys/socket.h>
64 #include <sys/ioctl.h>
66 #include <netinet/tcp.h>
69 #include <sys/resource.h>
76 #define GetCurrentDirEx _getcwd
79 #define GetCurrentDirEx getcwd
82#define WINSHMEMSPACE "Local"
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
94#define THREAD_TERMINATED 1
96#define THREAD_RUNNING 3
97#define THREAD_PAUSED 4
98#define THREAD_INTERRUPTED 5
100#define THREAD_STATS_OFF 0
101#define THREAD_STATS_AUTO 1
102#define THREAD_STATS_ADHOC 2
108 #define ThreadHandle HANDLE
111 #define THREAD_RET DWORD
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
125 #define ThreadHandle pthread_t
127 #define THREAD_RET 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
136 #define SOCKET_ERROR -1
137 #define INVALID_SOCKET -1
138 #define closesocket(X) close(X)
139 #define SOCKETWOULDBLOCK EINPROGRESS
140 #define SOCKETTRYAGAIN EAGAIN
142 #define MUTEXMEMSIZE 64
143 #define EVENTMEMSIZE 256
144 #define SEMAPHOREMEMSIZE 256
145 #define _strcmpi strcasecmp
146 #define _strnicmp strnicmp
154#define OSCPU_UNKNOWN 0
159#define ERROR64 0xFFFFFFFFFFFFFFFFL
160#define ERROR32 0xFFFFFFFF
161#define ERROR16 0xFFFF
206#define LOG_TOPIC10 10
207#define LOG_TOPIC11 11
208#define LOG_MAXCOUNT 12
239 const char*
getText(uint32& len);
244 bool setText(
char* text, uint32 len);
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, ... );
313#define LogPrint LogSystem::LogSystemPrint
314#define LogDebug LogSystem::LogSystemDebug
391 #define SharedMemoryFileHandleMapType std::map<char*, HANDLE>
393 #define SharedMemoryFileHandleMapType std::map<void*, std::string>
470 Mutex(
const char*
name,
bool force =
false);
478 bool enter(uint32 timeout,
const char* errorMsg = NULL);
512 bool wait(uint32 timeout);
522 void* semaphore_impl;
561bool EnterMutex(
const char* name, uint32 ms,
bool autocreate =
true);
599 ProcessData() { hOutRead = NULL; hErrRead = NULL; }
600 PROCESS_INFORMATION procInfo;
605static std::map<uint32, ProcessData*>* ProcessInformationMap = NULL;
606typedef std::pair <uint32, ProcessData*> Proc_Pair;
607static HANDLE ghJob = NULL;
657 bool addTimer(uint32
id, uint32 interval, uint64 start = 0, uint64 end = 0);
665 bool waitForTimer(uint32 timeout, uint32&
id, uint64& time);
673 std::queue<TimerTrigger*> triggers;
674 std::map<uint32, TimerSchedule*> schedules;
675 std::list<TimerSchedule*> oldSchedules;
680 void CALLBACK
TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired);
683 static void TimerCallback(
int sig, siginfo_t *siginfo,
void *context);
710 if (!
mutex.enter(200, __FUNCTION__))
720 if (!
mutex.enter(200, __FUNCTION__))
728 if (!
mutex.enter(200, __FUNCTION__))
740 if (!
mutex.enter(200, __FUNCTION__))
754 if (!
mutex.enter(200, __FUNCTION__))
764 if (!
mutex.enter(200, __FUNCTION__))
780 if (!
mutex.enter(200, __FUNCTION__))
791 if (!
mutex.enter(200, __FUNCTION__))
806 if (!
mutex.enter(200, __FUNCTION__))
872 bool add(uint64 time, T entry) {
873 if (!
mutex.enter(200, __FUNCTION__))
876 newEntry.
time = time;
877 newEntry.
entry = entry;
878 typename std::list< TimeQueueEntry<T> >::iterator i =
internalList.begin(),
881 if (time < (*i).time) {
895 if (!
mutex.enter(200, __FUNCTION__))
904 if (!
mutex.enter(200, __FUNCTION__))
912 if (first.
time < now) {
923 if (!
mutex.enter(200, __FUNCTION__))
925 std::list< TimeQueueEntry<T> > empty;
1007uint64
ntoh64(
const uint64 *input);
1025bool SetBit(uint32 loc, bit value,
char* bitfield, uint32 bytesize);
1028bool SetBitN(uint32 loc, uint32 num, bit value,
char* bitfield, uint32 bytesize);
1030bool GetBit(uint32 loc,
const char* bitfield, uint32 bytesize, bit& val);
1039std::string
PrintBitFieldString(
const char* bitfield, uint32 bytesize, uint32 size,
const char* title);
1068bool Sleep(uint32 ms);
1114 #define FileTimeToUint64(ft) (((uint64)(ft.dwHighDateTime))<<32)|((uint64)ft.dwLowDateTime)
1138bool GetProcAndOSCPUUsage(
double& procPercentUse,
double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1147bool GetProcAndOSCPUUsage(uint32 osProcID,
double& procPercentUse,
double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks);
1192#define PROC_TERMINATED 1
1193#define PROC_NOTSTARTED 2
1194#define PROC_RUNNING 3
1195#define PROC_TIMEOUT 4
1198#define PARENT_WRITE_PIPE 0
1199#define PARENT_READ_PIPE 1
1204#define PARENT_READ_FD ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
1205#define PARENT_WRITE_FD ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
1206#define CHILD_READ_FD ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
1207#define CHILD_WRITE_FD ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
1209#define PROCBUFSIZE 4096
1221int RunOSCommand(
const char* cmdline,
const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString);
1226uint32
NewProcess(
const char* cmdline,
const char* initdir = NULL,
const char* title = NULL,
1227 int16 x = -1, int16 y = -1, int16 w = -1, int16 h = -1);
1249uint32
NewProcessEx(
const char* cmdline,
const char* initdir,
const char* title,
1250 const std::map<std::string, std::string>* env,
1251 bool captureOutput,
bool ignoreOutput,
bool newProcessGroup);
1266uint8
WaitForProcess(uint32 proc, uint32 timeout,
int &returncode);
1277 #define DLLHandle HINSTANCE
1279 #define DLLHandle void*
1340 bool load(
const char* filename);
1388bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build,
char* text, uint16 textSize);
1411 bool CheckNetworkInit();
1412 #define CHECKNETWORKINIT utils::CheckNetworkInit();
1414 #define CHECKNETWORKINIT
1415 #define WSAEWOULDBLOCK EAGAIN
1423bool GetSocketError(
int wsaError,
char* errorString, uint16 errorStringMaxSize,
bool* isRecoverable);
1473#define LOCALHOSTIP 16777343
1474#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
1475#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
1477#define GETIPPORT(a) *(uint16*)((char*)&a + sizeof(uint32))
1478#define GETIPADDRESS(a) *(uint32*)&a
1479#define GETIPADDRESSPORT(a,p) (((uint32)a)) | (((uint64)p)<<32)
1480#define GETIPADDRESSQUAD(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3]
1481#define GETIPADDRESSQUADPORT(a) ((uint8*)&a)[0], ((uint8*)&a)[1], ((uint8*)&a)[2], ((uint8*)&a)[3], ((uint16*)&a)[2]
1492 std::string GetRegistryKeyInfo(
const char* key, HKEY &hKeyRoot);
1494 std::string GetRegistryParentKeyInfo(
const char* key, HKEY &hKeyRoot);
1531void PrintBinary(
void* p, uint32 size,
bool asInt,
const char* title);
1533const char*
stristr(
const char *str,
const char *substr, uint32 len = 0);
1537bool GetNextLineEnd(
const char *str, uint32 size, uint32& len, uint32& crSize);
1541bool TextEndsWith(
const char* str,
const char* end,
bool caseSensitive =
true);
1543bool TextStartsWith(
const char* str,
const char* start,
bool caseSensitive =
true);
1548uint32
strcpyavail(
char* dst,
const char* src, uint32 maxlen,
bool copyAvailable);
1550const char*
laststrstr(
const char* str1,
const char* str2);
1552const char*
laststristr(
const char* str1,
const char* str2);
1562uint32
StringSingleReplace(std::string& text, std::string key, std::string value,
bool onlyFirst);
1564uint32
StringMultiReplace(std::string& text, std::map<std::string, std::string>& map,
bool onlyFirst);
1568uint32
StringScriptReplace(std::string& text, std::string name, std::list< std::map<std::string, std::string> >& list);
1584std::string
TextIndent(
const char* text,
const char* indent);
1593std::string
TextTrim(
const char* text);
1602std::multimap<std::string, std::string>
TextMultiMapSplit(
const char* text,
const char* outersplit,
const char* innersplit);
1612std::map<std::string, std::string>
TextMapSplit(
const char* text,
const char* outersplit,
const char* innersplit);
1614std::string
TextJoin(std::vector<std::string> &list,
const char* split, uint32 start = 0, uint32 count = 0);
1616std::string
TextJoin(std::list<std::string> &list,
const char* split, uint32 start = 0, uint32 count = 0);
1619std::string
TextJoin(std::map<std::string, std::string> &map,
const char* innersplit,
const char* outersplit,
bool keyquotes,
bool valquotes);
1621std::string
TextJoinJSON(std::map<std::string, std::string> &map);
1623std::string
TextJoinXML(std::map<std::string, std::string> &map,
const char* innernodeName,
const char* outernodeName);
1630std::vector<std::string>
TextListSplit(
const char* text,
const char* split,
bool keepEmpty =
true,
bool autoTrim =
false);
1632std::vector<std::string>
TextListSplitLines(
const char* text,
bool keepEmpty =
true,
bool autoTrim =
false);
1634std::vector<std::string>
TextListBreakLines(
const char* text, uint32 maxLineLength = 80);
1636std::string
TextListBreakLines(
const char* text, uint32 maxLineLength,
const char* breakstr);
1638std::string
TextVectorConcat(std::vector<std::string>,
const char* sep,
bool allowEmpty =
true);
1663char*
StringFormat(uint32& size,
const char *format, ...);
1667char*
StringFormatVA(uint32& size,
const char *format, va_list args);
1675unsigned char Hex2Char(
const char* str);
1677unsigned char Dec2Char(
const char* str);
1687int CRC32(
const char *addr, uint32 length, int32 crc = 0);
1714#define STANDARDFILE 1
1715#define STANDARDDIR 2
1739char*
ReadAFile(
const char* filename, uint32& length,
bool binary =
false);
1741char*
ReadAFile(
const char* dir,
const char* filename, uint32& length,
bool binary =
false);
1746bool WriteAFile(
const char* filename,
const char* data, uint32 length,
bool binary =
false);
1748bool WriteAFile(
const char* dir,
const char* filename,
const char* data, uint32 length,
bool binary =
false);
1750bool AppendToAFile(
const char* filename,
const char* data, uint32 length,
bool binary =
false);
1752bool AppendToAFile(
const char* dir,
const char* filename,
const char* data, uint32 length,
bool binary =
false);
1768char*
GetFileList(
const char* dirname,
const char* ext, uint32& count,
bool fullpath, uint32 maxNameLen = 256);
1778bool DeleteAFile(
const char* filename,
bool force);
1780bool DeleteAFile(
const char* dir,
const char* filename,
bool force);
1782bool DeleteADir(
const char* dirname,
bool force);
1794bool MoveAFile(
const char* oldfilename,
const char* newfilename,
bool force =
false);
1796bool MoveAFile(
const char* olddir,
const char* oldfilename,
const char* newdir,
const char* newfilename,
bool force =
false);
1798bool CopyAFile(
const char* oldfilename,
const char* newfilename,
bool force =
false);
1800bool CopyAFile(
const char* olddir,
const char* oldfilename,
const char* newdir,
const char* newfilename,
bool force =
false);
1820char*
Int2Ascii(int64 value,
char* result, uint16 size, uint8 base);
1822char*
Uint2Ascii(uint64 value,
char* result, uint16 size, uint8 base);
1826unsigned char*
Ascii2UTF16LE(
const char* ascii, uint32 len, uint32& size);
1829bool IsTextNumeric(
const char* ascii, uint32 start = 0, uint32 end = 0);
1831int64
Ascii2Int64(
const char* ascii, uint32 start = 0, uint32 end = 0);
1833uint64
Ascii2Uint64(
const char* ascii, uint32 start = 0, uint32 end = 0);
1835uint64
AsciiHex2Uint64(
const char* ascii, uint32 start = 0, uint32 end = 0);
1837int32
Ascii2Int32(
const char* ascii, uint32 start = 0, uint32 end = 0);
1839uint32
Ascii2Uint32(
const char* ascii, uint32 start = 0, uint32 end = 0);
1841uint32
AsciiHex2Uint32(
const char* ascii, uint32 start = 0, uint32 end = 0);
1843float64
Ascii2Float64(
const char* ascii, uint32 start = 0, uint32 end = 0);
1884double RandomValue(
double from,
double to,
double interval);
1886int64
RandomInt(int64 from = 0, int64 to = 100);
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.
THREAD_RET(* THREAD_FUNCTION)(void *)
CleanShutdown()
Default constructor; no side effects.
~CleanShutdown()
Destroys all lazily-created global utility maps via ClearUtilsMaps().
Callback interface for receiving log entries produced through LogSystem.
virtual bool logEntry(LogEntry *entry)=0
Handle one log record.
static bool SetLogFileOutput(const char *logfile, bool printOut=true)
Direct log output to a file.
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
uint8 logLevelVerbose[LOG_MAXCOUNT]
static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring,...)
printf-style informational logging (usually invoked via the LogPrint macro).
uint8 logLevelDebug[LOG_MAXCOUNT]
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...
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
LogReceiver * logReceiverObj
static bool SetLogLevelDebug(uint8 level)
Set the debug level threshold for all topics.
static bool SetLogLevelVerbose(uint8 level)
Set the verbose (print) level threshold for all topics.
Singleton snapshot of the parsed process command line (set via SetCommandLine()).
std::string CommandLineExec
std::string CommandLineString
std::map< std::string, std::string > CommandLineArgs
static CommandLineInfo * CommandLineInfoSingleton
std::string CommandLineExecOnly
std::string CommandLineExecPath
std::vector< std::string > CommandLineItems
bool waitNext()
Block until the next signal() occurs.
Event()
Create an anonymous, process-local event.
bool signal()
Wake all threads currently waiting on this event.
Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen).
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
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...
bool load(const char *filename)
Load a library.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Mutex()
Create an anonymous, process-local mutex.
bool leave()
Release the mutex.
bool enter()
Block until the mutex is acquired.
Counting semaphore, optionally named for cross-process use.
Semaphore(uint32 maxCount=100)
Create an anonymous semaphore.
bool signal()
Increment (release) the semaphore, waking one waiter.
bool wait()
Block until the semaphore can be decremented.
bool getNextEntryDue(T &entry)
Pop the earliest entry if its due time has passed (non-blocking).
uint32 getCount()
Number of scheduled entries.
std::list< TimeQueueEntry< T > > internalList
virtual bool clear()
Discard all scheduled entries.
bool add(uint64 time, T entry)
Insert an entry sorted by its due time.
T getNextEntryDue()
Pop the earliest due entry.
virtual ~TimeQueuePointer()
virtual bool clear()
Delete every scheduled pointer and empty the queue.
bool addTimer(uint32 id, uint32 interval, uint64 start=0, uint64 end=0)
Register a periodic timer.
static std::map< uint32, Timer * > * timers
Global registry mapping globalID to live Timer instances, used by the OS callbacks.
bool triggerTimer(uint32 id)
Manually inject an expiry for timer id, as if it had fired now.
bool waitForTimer(uint32 timeout, uint32 &id, uint64 &time)
Wait for the next expiry of any registered timer.
bool removeTimer(uint32 id)
Unregister a timer and cancel its OS timer.
bool takeFirst(T &first)
Remove and return the front entry.
bool waitForAndPeekFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and peek it without removal.
bool add(T entry)
Append an entry and wake one waiting consumer.
bool peekFirst(T &first)
Copy the front entry without removing it.
std::queue< T > internalQueue
bool waitForAndTakeFirst(T &first, uint32 timeoutMS)
Block up to timeoutMS for an entry and dequeue it.
virtual bool clear()
Discard all queued entries.
uint32 getCount()
Number of queued entries.
T waitForAndTakeFirst(uint32 timeoutMS)
Convenience overload: dequeue with timeout, returning NULL instead of using an out-parameter.
virtual ~WaitQueuePointer()
virtual bool clear()
Delete every queued pointer and empty the queue.
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.
bool UnitTest_Utils()
Aggregate self test for miscellaneous utils functionality.
int64 AtomicDecrement64(int64 volatile &v)
Atomically decrement a 64-bit value.
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.
bool SetSharedSystemInstance(uint32 inst)
Set the instance number used to namespace shared OS objects, allowing several independent CMSDK syste...
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS=0)
Join a thread.
bool SignalSemaphore(const char *name)
Signal a named global semaphore.
bool GetThreadPriority(ThreadHandle hThread, uint16 priority)
Query a thread's scheduling priority.
std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
int FromOSPriority(int pri)
Map a native OS priority back to the CMSDK priority scale.
bool EndProcess(uint32 proc)
Forcibly terminate a child process.
std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
static Mutex * SharedMemorySemaphoreMapMutex
bool GetLastOccupiedBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the highest set (occupied) bit.
const char * laststrstr(const char *str1, const char *str2)
Find the last occurrence of str2 in str1.
std::pair< std::string, Event * > SharedMemoryEventMapPair
bool DestroyEvent(const char *name)
Destroy a named global event.
bool WaitForSemaphore(const char *name, uint32 ms, bool autocreate=true)
Wait on a named global semaphore.
static SharedMemoryFileHandleMapType * SharedMemoryFileHandleMap
bool TextStartsWith(const char *str, const char *start, bool caseSensitive=true)
Test whether str starts with start.
bool Sleep(uint32 ms)
Suspend the calling thread.
bool SetThreadPriority(ThreadHandle hThread, uint16 priority)
Set a thread's scheduling priority.
bool WaitNextEvent(const char *name, uint32 ms, bool autocreate=true)
Wait for the next signal on a named global event.
bool GetProcAndOSCPUUsage(double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks)
Sample CPU usage of this process and of the whole OS since the previous call.
bool PauseThread(ThreadHandle hThread)
Suspend a thread's execution.
static std::map< std::string, Event * > * SharedMemoryEventMap
bool MoveConsoleWindow(int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
Move/resize the console window.
bool IsThreadRunning(ThreadHandle hThread)
Check whether a thread is still alive.
bool CreateThread(THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
Start a new OS thread.
int32 AtomicDecrement32(int32 volatile &v)
Atomically decrement a 32-bit value.
static std::map< uint32, DrumBeatInfo > * DrumBeatMap
bool SignalThread(ThreadHandle hThread, int32 signal)
Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
int64 AtomicIncrement64(int64 volatile &v)
Atomically increment a 64-bit value.
uint32 GetSharedSystemInstance()
Get the current shared-system instance number.
bool StopDrumBeat(uint32 id)
Stop a running drum beat without destroying it.
uint32 NewProcessEx(const char *cmdline, const char *initdir, const char *title, const std::map< std::string, std::string > *env, bool captureOutput, bool ignoreOutput, bool newProcessGroup)
Launch a child with environment overrides and optional output capture.
bool EnterMutex(const char *name, uint32 ms, bool autocreate=true)
Acquire a named global mutex, creating it on first use.
const char * laststristr(const char *str1, const char *str2)
Case-insensitive laststrstr().
static Mutex * SharedMemoryMutexMapMutex
#define SharedMemoryFileHandleMapType
bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false)
Create a periodic timer ("drum beat") that calls func every interval ms.
bool ReapThread(ThreadHandle &hThread)
std::string PrintProgramTrace(uint32 startLine=0, uint32 endLine=0)
Format the current call stack as printable text.
uint8 GetProcessStatus(uint32 proc, int &returncode)
Poll a child started with NewProcess().
bool(* DrumBeatFunc)(uint32 id, uint32 count)
Callback invoked on every drum-beat tick.
static Mutex * SharedMemoryEventMapMutex
Semaphore * GetSemaphore(const char *name, bool autocreate=true)
Look up (and optionally create) a named semaphore in the global registry.
bool LeaveMutex(const char *name)
Release a named global mutex previously acquired with EnterMutex().
int RunOSCommand(const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString)
Run a command synchronously and capture its output.
char * CreateSharedMemorySegment(const char *name, uint64 size, bool force=false)
Create a named shared memory segment and map it into this process.
std::string PrintBitFieldString(const char *bitfield, uint32 bytesize, uint32 size, const char *title)
Like GetBitFieldAsString() but prefixed with title and formatted for printing.
std::string GetBitFieldAsString(const char *bitfield, uint32 bytesize, uint32 size)
Render the first size bits as a '0'/'1' string, for debugging.
uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode)
Wait for a child to exit.
uint32 GetLocalProcessID()
Get the OS process id of the current process.
bool EndDrumBeat(uint32 id)
Destroy a drum beat and release its OS timer.
bool DestroySemaphore(const char *name)
Destroy a named global semaphore.
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
bool TerminateThread(ThreadHandle hThread)
Forcibly kill a thread.
bool GetFirstFreeBitLocN(const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
Find the first run of num consecutive 0 bits.
bool GetCurrentThreadUniqueID(uint32 &tid)
Get a process-unique id for the calling thread.
int32 AtomicIncrement32(int32 volatile &v)
Atomically increment a 32-bit value.
bool GetDesktopSize(uint32 &width, uint32 &height)
Get the primary desktop resolution.
bool CheckForThreadFinished(ThreadHandle hThread)
Non-blocking check whether a thread has terminated.
bool DestroyMutex(const char *name)
Destroy a named global mutex and remove it from the registry.
bool ContinueThread(ThreadHandle hThread)
Resume a thread paused with PauseThread().
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
std::list< std::string > GetProgramTrace()
Capture the current call stack.
uint64 hton64(const uint64_t *input)
Convert a 64-bit value from host to network byte order.
static uint16 SharedSystemInstance
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'...
void PrintBinary(void *p, uint32 size, bool asInt, const char *title)
Hex/decimal dump a memory region to stdout for debugging.
static std::map< std::string, Mutex * > * SharedMemoryMutexMap
bool GetFirstFreeBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the first 0 (free) bit.
bool SignalEvent(const char *name)
Signal a named global event.
bool GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
bool GetNextLineEnd(const char *str, uint32 size, uint32 &len, uint32 &crSize)
Find the end of the current line.
bool GetBit(uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
Read bit loc.
uint64 ntoh64(const uint64 *input)
Convert a 64-bit value from network to host byte order.
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
bool ReadProcessOutput(uint32 proc, std::string &out, std::string &err)
Read any pending captured stdout/stderr from a child launched with captureOutput=true.
int ToOSPriority(int pri)
Map a CMSDK priority value to the platform's native priority scale.
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap
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...
bool SetBitN(uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
Set num consecutive bits starting at loc to value.
bool Reset32BitField(char *bitfield, uint32 bytesize)
Zero the whole bitfield, marking every bit as free.
bool StartDrumBeat(uint32 id)
Start (or resume) a previously created drum beat.
bool TextEndsWith(const char *str, const char *end, bool caseSensitive=true)
Test whether str ends with end.
bool UnitTest_Timer()
Self test for the Timer class.
bool SetBit(uint32 loc, bit value, char *bitfield, uint32 bytesize)
Set bit loc to value.
bool GetCurrentThread(ThreadHandle &thread)
Get the handle of the calling thread.
bool RenameConsoleWindow(const char *name, bool prepend=false)
Set the console window title.
bool TryReapThread(ThreadHandle &hThread)
bool UtilsTest()
Run the built-in self test of the utils module.
uint32 Calc32BitFieldSize(uint32 bitsize)
Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.
uint32 TextReplaceCharsInPlace(char *str, uint32 size, char find, char replace)
Replace every occurrence of a character, in place.
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
bool GetOSCPUUsage(double &percentUse)
Get the instantaneous total OS CPU usage.
bool GetCurrentThreadOSID(uint32 &tid)
Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
bool SeedRandomValues(uint32 seedvalue=0)
Seed the pseudo-random generator.
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
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).
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
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.
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
uint16 GetCPUArchitecture()
CPU architecture id.
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
const char * GetSystemArchitecture()
Architecture name string, e.g.
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
std::string GetCommandLinePath()
Get the directory portion of the executable path.
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
uint64 GetCPUSpeed()
Nominal CPU clock speed.
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
char * GetFileList(const char *dirname, const char *ext, uint32 &count, bool fullpath, uint32 maxNameLen=256)
List files in a directory matching an extension.
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
uint32 StringMultiReplace(std::string &text, std::map< std::string, std::string > &map, bool onlyFirst)
Apply many key→value replacements in one pass.
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
uint16 GetCPUCount()
Number of logical CPU cores.
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
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).
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
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...
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.
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
uint64 GetSystemMemorySize()
Total physical RAM installed.
uint32 ReadRegistryDWORD(const char *key, const char *entry)
Read a 32-bit registry value.
bool GetLocalMACAddress(uint64 &address)
Get the primary local MAC address.
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
FileDetails GetFileDetails(const char *filename)
Stat a file.
double RandomValue()
Uniform random double in [0,1).
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
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).
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
std::string GetLocalHostnameString()
Local hostname as std::string.
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
bool DeleteAFile(const char *filename, bool force)
Delete a file.
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
std::vector< std::string > TextListSplitLines(const char *text, bool keepEmpty=true, bool autoTrim=false)
Split text into lines, handling both \n and \r\n.
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
std::string GetCurrentDir()
Current working directory.
std::string GetCommandLine()
Get the full original command line as one string.
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.
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
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.
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
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.
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
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.
const char * GetFileBasename(const char *filename)
Filename portion of a path.
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
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.
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
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).
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
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).
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
const char * GetComputerName()
Get this machine's hostname.
std::string GetFilePath(const char *filename)
Directory portion of a path.
const char * GetSystemOSName()
OS name string, e.g.
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
std::string TextJoin(std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
Join vector elements with split.
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
std::string BytifyRate(double val)
Format a byte rate, e.g.
bool ClearUtilsMaps()
Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps).
uint32 GetDataTypeID(const char *typeName)
Inverse of GetDataTypeName(): look up the numeric datatype id for a type name.
std::string GetDataTypeName(uint32 datatype)
Translate a CMSDK datatype id (e.g.
Wire/storage layout of one log record: fixed header immediately followed by the message text.
std::string toJSON()
Serialize the entry (header fields + text) as a JSON object string.
bool setText(char *text, uint32 len)
Copy len bytes of text into the payload area and update size.
const char * getText(uint32 &len)
Access the text payload stored after the header.
std::string toXML()
Serialize the entry as an XML fragment.
Bookkeeping record for one periodic "drum beat" timer.
Existence, type, permission and timestamp information for one file, as returned by GetFileDetails().
Description of one local network interface (IPv4 address, MAC and names).
char friendlyName[MAXKEYNAMELEN+1]
char name[MAXKEYNAMELEN+1]
One (time, entry) pair inside a TimeQueue.
One scheduled entry inside a Timer: id, active window and platform timer handle.
A single timer expiry: which timer fired and when.