CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
Utility functions and objects

Cross-platform helper layer of the CMSDK: synchronization primitives, threads and processes, shared memory, timers, bit fields, sockets and name lookup, registry access (Windows), file I/O, rich string/text manipulation, numeric parsing/formatting and random numbers. More...

Detailed Description

Cross-platform helper layer of the CMSDK: synchronization primitives, threads and processes, shared memory, timers, bit fields, sockets and name lookup, registry access (Windows), file I/O, rich string/text manipulation, numeric parsing/formatting and random numbers.

Functions are grouped below by theme. All of them are plain free functions in cmlabs::utils unless noted otherwise.

Why this layer exists
Everything above it in the CMSDK — Shared-Memory Subsystem, Threading, Messaging, the request fabric — must behave identically on Windows, Linux and macOS. utils is where the platform differences are absorbed exactly once: one Mutex/Semaphore API over CRITICAL_SECTION vs pthread_mutex/named semaphores, one CreateThread over Win32 vs pthreads, one shared-memory primitive over CreateFileMapping vs shm_open/mmap, one socket/name-lookup wrapper over WinSock vs BSD sockets. The rest — the Text* string toolkit, StringFormat(), ReadAFile()/WriteAFile(), the Ascii2* parsers, WaitQueue/TimeQueue — exists because CMSDK predates the std:: equivalents (or none exist) and because the codebase needs one consistent, C-string-friendly way to do these chores everywhere.
Why not std:: / OS calls directly
Portability and consistency: locale-independent numeric parsing (Ascii2Float64 always uses '.'), identical text-splitting semantics on every platform, cross-process named mutexes/semaphores (which std has no equivalent of), and integration — the shared-memory and semaphore helpers here are the exact primitives the Shared-Memory Subsystem segments and queues are built on.
Common tasks
using namespace cmlabs::utils;
// String formatting and manipulation
std::string s = StringFormat("%u items in %.2f s", n, secs);
std::vector<std::string> parts = TextListSplit("a, b,,c", ",", false, true); // {"a","b","c"}
std::string joined = TextJoin(parts, ";");
std::string up = TextUppercase(TextTrim(" hello ").c_str()); // "HELLO"
// File I/O
std::string cfg = ReadAFileString("config.xml"); // text, empty on error
uint32 len; char* raw = ReadAFile("image.bin", len, true); // binary; delete [] raw
WriteAFile("out.txt", s.c_str(), (uint32)s.size());
// Numeric parsing (locale-independent)
int64 v = Ascii2Int64("12345");
float64 f = Ascii2Float64("3.14"); // always '.' decimal point
// Cross-thread/-process synchronisation
Mutex m("my.global.lock"); // named => visible to other processes
if (m.enter(1000, __FUNCTION__)) {
// ... critical section ...
m.leave();
}
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:463
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:7055
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:6365
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:6427
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
Definition Utils.cpp:6769
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:7135
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:6884
char * ReadAFile(const char *filename, uint32 &length, bool binary=false)
Read an entire file into a new buffer.
Definition Utils.cpp:7076
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:7720
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
Definition Utils.cpp:7804
std::string TextJoin(std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
Join vector elements with split.
Definition Utils.cpp:6688
Note
char*-returning helpers generally allocate with new char[] and the caller must delete []; prefer the std::string variants where both exist.

Classes

struct  cmlabs::utils::DrumBeatInfo
 Bookkeeping record for one periodic "drum beat" timer. More...
class  cmlabs::utils::Mutex
 Recursive mutual-exclusion lock, optionally named for cross-process use. More...
class  cmlabs::utils::Semaphore
 Counting semaphore, optionally named for cross-process use. More...
class  cmlabs::utils::Event
 Auto-reset notification event (condition variable style), optionally named for cross-process use. More...
struct  cmlabs::utils::TimerSchedule
 One scheduled entry inside a Timer: id, active window and platform timer handle. More...
struct  cmlabs::utils::TimerTrigger
 A single timer expiry: which timer fired and when. More...
class  cmlabs::utils::Timer
 Multiplexing timer: schedule many periodic timers and consume their expiries from one queue. More...
class  cmlabs::utils::WaitQueue< T >
 Thread-safe FIFO queue with blocking waits, the workhorse producer/consumer channel in CMSDK. More...
class  cmlabs::utils::WaitQueuePointer< T >
 WaitQueue specialization for owned heap pointers: clear()/destructor delete remaining entries. More...
struct  cmlabs::utils::TimeQueueEntry< T >
 One (time, entry) pair inside a TimeQueue. More...
class  cmlabs::utils::TimeQueue< T >
 Thread-safe queue of entries ordered by due time; entries become retrievable once their timestamp passes. More...
class  cmlabs::utils::TimeQueuePointer< T >
 TimeQueue specialization for owned heap pointers: clear()/destructor delete remaining entries. More...

Macros

#define SharedMemoryFileHandleMapType   std::map<void*, std::string>
#define PROC_ERROR   0
#define PROC_TERMINATED   1
#define PROC_NOTSTARTED   2
#define PROC_RUNNING   3
#define PROC_TIMEOUT   4
#define NUM_PIPES   2
#define PARENT_WRITE_PIPE   0
#define PARENT_READ_PIPE   1
#define READ_FD   0
#define WRITE_FD   1
#define PARENT_READ_FD   ( (*pipes)[PARENT_READ_PIPE][READ_FD] )
#define PARENT_WRITE_FD   ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )
#define CHILD_READ_FD   ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )
#define CHILD_WRITE_FD   ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )
#define PROCBUFSIZE   4096

Typedefs

typedef std::pair< std::string, Mutex * > cmlabs::utils::SharedMemoryMutexMapPair
typedef std::pair< std::string, Semaphore * > cmlabs::utils::SharedMemorySemaphoreMapPair
typedef std::pair< std::string, Event * > cmlabs::utils::SharedMemoryEventMapPair

Functions

uint8 cmlabs::utils::WaitForProcess (uint32 proc, uint32 timeout, int &returncode)
 Wait for a child to exit.
uint32 cmlabs::utils::GetLocalProcessID ()
 Get the OS process id of the current process.

Variables

static SharedMemoryFileHandleMapTypecmlabs::utils::SharedMemoryFileHandleMap = NULL
static uint16 cmlabs::utils::SharedSystemInstance = 0
static Mutexcmlabs::utils::SharedMemoryMutexMapMutex = NULL
static std::map< std::string, Mutex * > * cmlabs::utils::SharedMemoryMutexMap = NULL
static Mutexcmlabs::utils::SharedMemorySemaphoreMapMutex = NULL
static std::map< std::string, Semaphore * > * cmlabs::utils::SharedMemorySemaphoreMap = NULL
static Mutexcmlabs::utils::SharedMemoryEventMapMutex = NULL
static std::map< std::string, Event * > * cmlabs::utils::SharedMemoryEventMap = NULL

Synchronization primitives (mutexes, semaphores, events, drum beats)

Named primitives are backed by OS objects shared between processes (Windows kernel objects, POSIX shared memory + pthread process-shared objects, or dispatch/mach objects on macOS); unnamed ones are process-local.

typedef bool(* cmlabs::utils::DrumBeatFunc) (uint32 id, uint32 count)
 Callback invoked on every drum-beat tick.
static std::map< uint32, DrumBeatInfo > * cmlabs::utils::DrumBeatMap = NULL
bool cmlabs::utils::SetSharedSystemInstance (uint32 inst)
 Set the instance number used to namespace shared OS objects, allowing several independent CMSDK systems on one host.
uint32 cmlabs::utils::GetSharedSystemInstance ()
 Get the current shared-system instance number.
bool cmlabs::utils::CreateDrumBeat (uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false)
 Create a periodic timer ("drum beat") that calls func every interval ms.
bool cmlabs::utils::StartDrumBeat (uint32 id)
 Start (or resume) a previously created drum beat.
bool cmlabs::utils::StopDrumBeat (uint32 id)
 Stop a running drum beat without destroying it.
bool cmlabs::utils::EndDrumBeat (uint32 id)
 Destroy a drum beat and release its OS timer.
bool cmlabs::utils::EnterMutex (const char *name, uint32 ms, bool autocreate=true)
 Acquire a named global mutex, creating it on first use.
bool cmlabs::utils::LeaveMutex (const char *name)
 Release a named global mutex previously acquired with EnterMutex().
bool cmlabs::utils::DestroyMutex (const char *name)
 Destroy a named global mutex and remove it from the registry.
Semaphorecmlabs::utils::GetSemaphore (const char *name, bool autocreate=true)
 Look up (and optionally create) a named semaphore in the global registry.
bool cmlabs::utils::WaitForSemaphore (const char *name, uint32 ms, bool autocreate=true)
 Wait on a named global semaphore.
bool cmlabs::utils::SignalSemaphore (const char *name)
 Signal a named global semaphore.
bool cmlabs::utils::DestroySemaphore (const char *name)
 Destroy a named global semaphore.
bool cmlabs::utils::WaitNextEvent (const char *name, uint32 ms, bool autocreate=true)
 Wait for the next signal on a named global event.
bool cmlabs::utils::SignalEvent (const char *name)
 Signal a named global event.
bool cmlabs::utils::DestroyEvent (const char *name)
 Destroy a named global event.

C-string helpers

Low-level, allocation-free operations on raw char buffers.

bool cmlabs::utils::UtilsTest ()
 Run the built-in self test of the utils module.
void cmlabs::utils::PrintBinary (void *p, uint32 size, bool asInt, const char *title)
 Hex/decimal dump a memory region to stdout for debugging.
const char * cmlabs::utils::stristr (const char *str, const char *substr, uint32 len=0)
 Case-insensitive strstr.
bool cmlabs::utils::GetNextLineEnd (const char *str, uint32 size, uint32 &len, uint32 &crSize)
 Find the end of the current line.
uint32 cmlabs::utils::TextReplaceCharsInPlace (char *str, uint32 size, char find, char replace)
 Replace every occurrence of a character, in place.
bool cmlabs::utils::TextEndsWith (const char *str, const char *end, bool caseSensitive=true)
 Test whether str ends with end.
bool cmlabs::utils::TextStartsWith (const char *str, const char *start, bool caseSensitive=true)
 Test whether str starts with start.
uint32 cmlabs::utils::strcpyavail (char *dst, const char *src, uint32 maxlen, bool copyAvailable)
 Bounded strcpy that always NUL-terminates.
const char * cmlabs::utils::laststrstr (const char *str1, const char *str2)
 Find the last occurrence of str2 in str1.
const char * cmlabs::utils::laststristr (const char *str1, const char *str2)
 Case-insensitive laststrstr().

Timers and queues

static void cmlabs::utils::TimerCallback (int sig, siginfo_t *siginfo, void *context)
 POSIX signal-based timer callback trampoline (SIGEV_SIGNAL); routes the expiry into the owning Timer's trigger queue.
bool cmlabs::utils::UnitTest_Timer ()
 Self test for the Timer class.
bool cmlabs::utils::UnitTest_Utils ()
 Aggregate self test for miscellaneous utils functionality.

Shared memory

Named segments are implemented with CreateFileMapping on Windows and shm_open/mmap on POSIX; names are prefixed with the shared system instance so independent CMSDK deployments do not collide.

char * cmlabs::utils::CreateSharedMemorySegment (const char *name, uint64 size, bool force=false)
 Create a named shared memory segment and map it into this process.
char * cmlabs::utils::OpenSharedMemorySegment (const char *name, uint64 size)
 Open and map an existing named shared memory segment.
bool cmlabs::utils::CloseSharedMemorySegment (char *data, uint64 size)
 Unmap a segment previously created/opened here.

Bit field operations

Helpers for compact allocation bitmaps (used e.g.

by the shared-memory block allocators). Bit 0 is the least significant bit of the first byte.

uint64 cmlabs::utils::ntoh64 (const uint64 *input)
 Convert a 64-bit value from network to host byte order.
uint64 cmlabs::utils::hton64 (const uint64_t *input)
 Convert a 64-bit value from host to network byte order.
uint32 cmlabs::utils::Calc32BitFieldSize (uint32 bitsize)
 Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.
bool cmlabs::utils::Reset32BitField (char *bitfield, uint32 bytesize)
 Zero the whole bitfield, marking every bit as free.
bool cmlabs::utils::GetFirstFreeBitLoc (const char *bitfield, uint32 bytesize, uint32 &loc)
 Find the first 0 (free) bit.
bool cmlabs::utils::GetFirstFreeBitLocN (const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
 Find the first run of num consecutive 0 bits.
bool cmlabs::utils::SetBit (uint32 loc, bit value, char *bitfield, uint32 bytesize)
 Set bit loc to value.
bool cmlabs::utils::SetBitN (uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
 Set num consecutive bits starting at loc to value.
bool cmlabs::utils::GetBit (uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
 Read bit loc.
bool cmlabs::utils::GetLastOccupiedBitLoc (const char *bitfield, uint32 bytesize, uint32 &loc)
 Find the highest set (occupied) bit.
std::string cmlabs::utils::GetBitFieldAsString (const char *bitfield, uint32 bytesize, uint32 size)
 Render the first size bits as a '0'/'1' string, for debugging.
std::string cmlabs::utils::PrintBitFieldString (const char *bitfield, uint32 bytesize, uint32 size, const char *title)
 Like GetBitFieldAsString() but prefixed with title and formatted for printing.

Threading and CPU statistics

std::string cmlabs::utils::PrintProgramTrace (uint32 startLine=0, uint32 endLine=0)
 Format the current call stack as printable text.
std::list< std::string > cmlabs::utils::GetProgramTrace ()
 Capture the current call stack.
int32 cmlabs::utils::AtomicIncrement32 (int32 volatile &v)
 Atomically increment a 32-bit value.
int64 cmlabs::utils::AtomicIncrement64 (int64 volatile &v)
 Atomically increment a 64-bit value.
int32 cmlabs::utils::AtomicDecrement32 (int32 volatile &v)
 Atomically decrement a 32-bit value.
int64 cmlabs::utils::AtomicDecrement64 (int64 volatile &v)
 Atomically decrement a 64-bit value.
bool cmlabs::utils::Sleep (uint32 ms)
 Suspend the calling thread.
bool cmlabs::utils::CreateThread (THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
 Start a new OS thread.
bool cmlabs::utils::WaitForThreadToFinish (ThreadHandle hThread, uint32 timeoutMS=0)
 Join a thread.
bool cmlabs::utils::ReapThread (ThreadHandle &hThread)
bool cmlabs::utils::TryReapThread (ThreadHandle &hThread)
bool cmlabs::utils::CheckForThreadFinished (ThreadHandle hThread)
 Non-blocking check whether a thread has terminated.
bool cmlabs::utils::TerminateThread (ThreadHandle hThread)
 Forcibly kill a thread.
bool cmlabs::utils::PauseThread (ThreadHandle hThread)
 Suspend a thread's execution.
bool cmlabs::utils::ContinueThread (ThreadHandle hThread)
 Resume a thread paused with PauseThread().
bool cmlabs::utils::GetCurrentThreadUniqueID (uint32 &tid)
 Get a process-unique id for the calling thread.
bool cmlabs::utils::GetCurrentThreadOSID (uint32 &tid)
 Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
bool cmlabs::utils::GetCurrentThread (ThreadHandle &thread)
 Get the handle of the calling thread.
bool cmlabs::utils::IsThreadRunning (ThreadHandle hThread)
 Check whether a thread is still alive.
uint32 cmlabs::utils::GetThreadStatColAbility ()
 Report this platform's capability for per-thread CPU statistics collection.
bool cmlabs::utils::GetCPUTicks (ThreadHandle hThread, uint64 &ticks)
 Get accumulated CPU time of a specific thread.
bool cmlabs::utils::GetCPUTicks (uint64 &ticks)
 Get accumulated CPU time of the calling thread.
bool cmlabs::utils::GetProcessCPUTicks (uint64 &ticks)
 Get accumulated CPU time of the current process.
bool cmlabs::utils::GetProcessCPUTicks (uint32 osProcID, uint64 &ticks)
 Get accumulated CPU time of another process.
bool cmlabs::utils::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 cmlabs::utils::GetProcAndOSCPUUsage (uint32 osProcID, double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks)
 As GetProcAndOSCPUUsage() above, but for an arbitrary process.
bool cmlabs::utils::GetOSCPUUsage (double &percentUse)
 Get the instantaneous total OS CPU usage.
bool cmlabs::utils::GetThreadPriority (ThreadHandle hThread, uint16 priority)
 Query a thread's scheduling priority.
bool cmlabs::utils::SetThreadPriority (ThreadHandle hThread, uint16 priority)
 Set a thread's scheduling priority.
int cmlabs::utils::ToOSPriority (int pri)
 Map a CMSDK priority value to the platform's native priority scale.
int cmlabs::utils::FromOSPriority (int pri)
 Map a native OS priority back to the CMSDK priority scale.
bool cmlabs::utils::SignalThread (ThreadHandle hThread, int32 signal)
 Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).

Desktop and console

bool cmlabs::utils::GetDesktopSize (uint32 &width, uint32 &height)
 Get the primary desktop resolution.
bool cmlabs::utils::RenameConsoleWindow (const char *name, bool prepend=false)
 Set the console window title.
bool cmlabs::utils::MoveConsoleWindow (int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
 Move/resize the console window.

Process management

int cmlabs::utils::RunOSCommand (const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString)
 Run a command synchronously and capture its output.
uint32 cmlabs::utils::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.
uint8 cmlabs::utils::GetProcessStatus (uint32 proc, int &returncode)
 Poll a child started with NewProcess().
bool cmlabs::utils::EndProcess (uint32 proc)
 Forcibly terminate a child process.

Managed child launch (T1.4 external-executable support)

Extended launch/lifecycle helpers used by ExternalExecManager.

On POSIX these are thin conveniences; on Windows they carry the env block, working directory, optional stdout/stderr capture pipes and console-group/graceful-stop plumbing that plain NewProcess() does not.

uint32 cmlabs::utils::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 cmlabs::utils::ReadProcessOutput (uint32 proc, std::string &out, std::string &err)
 Read any pending captured stdout/stderr from a child launched with captureOutput=true.
bool cmlabs::utils::SendProcessBreak (uint32 proc, int sig)
 Attempt a graceful stop: POSIX sends the given signal; Windows posts a CTRL_BREAK to the child's process group (requires newProcessGroup=true at launch) and falls back to nothing if unsupported.

Macro Definition Documentation

◆ CHILD_READ_FD

#define CHILD_READ_FD   ( (*pipes)[PARENT_WRITE_PIPE][READ_FD] )

Definition at line 1206 of file Utils.h.

◆ CHILD_WRITE_FD

#define CHILD_WRITE_FD   ( (*pipes)[PARENT_READ_PIPE][WRITE_FD] )

Definition at line 1207 of file Utils.h.

◆ NUM_PIPES

#define NUM_PIPES   2

Definition at line 1197 of file Utils.h.

◆ PARENT_READ_FD

#define PARENT_READ_FD   ( (*pipes)[PARENT_READ_PIPE][READ_FD] )

Definition at line 1204 of file Utils.h.

◆ PARENT_READ_PIPE

#define PARENT_READ_PIPE   1

Definition at line 1199 of file Utils.h.

◆ PARENT_WRITE_FD

#define PARENT_WRITE_FD   ( (*pipes)[PARENT_WRITE_PIPE][WRITE_FD] )

Definition at line 1205 of file Utils.h.

◆ PARENT_WRITE_PIPE

#define PARENT_WRITE_PIPE   0

Definition at line 1198 of file Utils.h.

◆ PROC_ERROR

#define PROC_ERROR   0

Definition at line 1191 of file Utils.h.

◆ PROC_NOTSTARTED

#define PROC_NOTSTARTED   2

Definition at line 1193 of file Utils.h.

◆ PROC_RUNNING

#define PROC_RUNNING   3

Definition at line 1194 of file Utils.h.

Referenced by cmlabs::utils::GetProcessStatus(), and cmlabs::utils::WaitForProcess().

◆ PROC_TERMINATED

#define PROC_TERMINATED   1

Definition at line 1192 of file Utils.h.

Referenced by cmlabs::utils::GetProcessStatus(), and cmlabs::utils::WaitForProcess().

◆ PROC_TIMEOUT

#define PROC_TIMEOUT   4

Definition at line 1195 of file Utils.h.

Referenced by cmlabs::utils::WaitForProcess().

◆ PROCBUFSIZE

#define PROCBUFSIZE   4096

Definition at line 1209 of file Utils.h.

Referenced by cmlabs::utils::RunOSCommand().

◆ READ_FD

#define READ_FD   0

Definition at line 1202 of file Utils.h.

◆ SharedMemoryFileHandleMapType

#define SharedMemoryFileHandleMapType   std::map<void*, std::string>

◆ WRITE_FD

#define WRITE_FD   1

Definition at line 1203 of file Utils.h.

Typedef Documentation

◆ DrumBeatFunc

typedef bool(* cmlabs::utils::DrumBeatFunc) (uint32 id, uint32 count)

Callback invoked on every drum-beat tick.

Parameters
idDrum beat id it was registered under.
countTick counter, increasing from 1.
Returns
Return false to request no further processing of this tick.

Definition at line 418 of file Utils.h.

◆ SharedMemoryEventMapPair

typedef std::pair<std::string, Event*> cmlabs::utils::SharedMemoryEventMapPair

Definition at line 595 of file Utils.h.

◆ SharedMemoryMutexMapPair

typedef std::pair<std::string, Mutex*> cmlabs::utils::SharedMemoryMutexMapPair

Definition at line 589 of file Utils.h.

◆ SharedMemorySemaphoreMapPair

typedef std::pair<std::string, Semaphore*> cmlabs::utils::SharedMemorySemaphoreMapPair

Definition at line 592 of file Utils.h.

Function Documentation

◆ AtomicDecrement32()

int32 cmlabs::utils::AtomicDecrement32 ( int32 volatile & v)

Atomically decrement a 32-bit value.

Parameters
vValue to modify.
Returns
The new value.

Definition at line 2810 of file Utils.cpp.

◆ AtomicDecrement64()

int64 cmlabs::utils::AtomicDecrement64 ( int64 volatile & v)

Atomically decrement a 64-bit value.

Parameters
vValue to modify.
Returns
The new value.

Definition at line 2820 of file Utils.cpp.

◆ AtomicIncrement32()

int32 cmlabs::utils::AtomicIncrement32 ( int32 volatile & v)

Atomically increment a 32-bit value.

Parameters
vValue to modify.
Returns
The new (incremented) value.

Definition at line 2790 of file Utils.cpp.

◆ AtomicIncrement64()

int64 cmlabs::utils::AtomicIncrement64 ( int64 volatile & v)

Atomically increment a 64-bit value.

Parameters
vValue to modify.
Returns
The new value.

Definition at line 2800 of file Utils.cpp.

◆ Calc32BitFieldSize()

uint32 cmlabs::utils::Calc32BitFieldSize ( uint32 bitsize)

Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.

Parameters
bitsizeNumber of bits.
Returns
Byte size.

Definition at line 2463 of file Utils.cpp.

Referenced by cmlabs::TemporalMemory::create(), cmlabs::MemoryRequestQueues::InitRequestMap(), cmlabs::ThreadManager::resizeThreadStorage(), and UnitTest_Utils().

◆ CheckForThreadFinished()

bool cmlabs::utils::CheckForThreadFinished ( ThreadHandle hThread)

Non-blocking check whether a thread has terminated.

Parameters
hThreadThread handle.
Returns
true when finished.

Definition at line 2942 of file Utils.cpp.

References ThreadHandle.

◆ CloseSharedMemorySegment()

◆ ContinueThread()

bool cmlabs::utils::ContinueThread ( ThreadHandle hThread)

Resume a thread paused with PauseThread().

Parameters
hThreadThread handle.
Returns
true on success.

Definition at line 3107 of file Utils.cpp.

References ThreadHandle.

Referenced by cmlabs::ThreadManager::continueThread().

◆ CreateDrumBeat()

bool cmlabs::utils::CreateDrumBeat ( uint32 id,
uint32 interval,
DrumBeatFunc func,
bool autostart = false )

Create a periodic timer ("drum beat") that calls func every interval ms.

Parameters
idCaller-chosen unique id for the beat.
intervalPeriod in milliseconds.
funcCallback to invoke on each tick.
autostartStart immediately when true; otherwise call StartDrumBeat().
Returns
true if the timer was created.

Definition at line 482 of file Utils.cpp.

References cmlabs::utils::DrumBeatInfo::count, cmlabs::utils::DrumBeatInfo::createdTime, DrumBeatCallback(), DrumBeatMap, cmlabs::utils::DrumBeatInfo::func, cmlabs::GetTimeNow(), cmlabs::utils::DrumBeatInfo::handle, cmlabs::utils::DrumBeatInfo::id, cmlabs::utils::DrumBeatInfo::interval, LOG_SYSTEM, LogPrint, and StartDrumBeat().

◆ CreateSharedMemorySegment()

char * cmlabs::utils::CreateSharedMemorySegment ( const char * name,
uint64 size,
bool force = false )

Create a named shared memory segment and map it into this process.

Parameters
nameGlobal segment name.
sizeSize in bytes.
forceRecreate the segment even if one with this name already exists.
Returns
Pointer to the mapped memory, or NULL on failure.

Definition at line 2166 of file Utils.cpp.

References GetLastOSErrorMessage(), LOG_SYSTEM, LogPrint, MAXSHMEMNAMELEN, SharedMemoryFileHandleMap, SharedMemoryFileHandleMapType, and WINSHMEMSPACE.

Referenced by cmlabs::ComponentMemory::create(), cmlabs::MasterMemory::create(), cmlabs::ProcessMemory::create(), cmlabs::TemporalMemory::create(), cmlabs::utils::Event::Event(), cmlabs::MemoryRequestServer::init(), cmlabs::PsycloneIndex::init(), cmlabs::utils::Mutex::Mutex(), and cmlabs::utils::Semaphore::Semaphore().

◆ CreateThread()

bool cmlabs::utils::CreateThread ( THREAD_FUNCTION func,
void * args,
ThreadHandle & thread,
uint32 & osID )

Start a new OS thread.

Parameters
funcEntry point (THREAD_FUNCTION signature; platform calling convention hidden by the macros above).
argsOpaque pointer passed to func.
[out]threadReceives the thread handle.
[out]osIDReceives the OS thread id.
Returns
true when the thread was created.

Definition at line 2896 of file Utils.cpp.

References CreateThread(), Sleep(), and ThreadHandle.

Referenced by CreateThread(), and cmlabs::ThreadManager::createThread().

◆ DestroyEvent()

bool cmlabs::utils::DestroyEvent ( const char * name)

Destroy a named global event.

Parameters
nameEvent name.
Returns
true on success.

Definition at line 917 of file Utils.cpp.

References SharedMemoryEventMap, and SharedMemoryEventMapMutex.

◆ DestroyMutex()

bool cmlabs::utils::DestroyMutex ( const char * name)

Destroy a named global mutex and remove it from the registry.

Parameters
nameMutex name.
Returns
true on success.

Definition at line 702 of file Utils.cpp.

References SharedMemoryMutexMap, and SharedMemoryMutexMapMutex.

◆ DestroySemaphore()

bool cmlabs::utils::DestroySemaphore ( const char * name)

Destroy a named global semaphore.

Parameters
nameSemaphore name.
Returns
true on success.

Definition at line 836 of file Utils.cpp.

References SharedMemorySemaphoreMap, and SharedMemorySemaphoreMapMutex.

◆ EndDrumBeat()

bool cmlabs::utils::EndDrumBeat ( uint32 id)

◆ EndProcess()

bool cmlabs::utils::EndProcess ( uint32 proc)

Forcibly terminate a child process.

Parameters
procProcess id from NewProcess().
Returns
true on success.

Definition at line 4188 of file Utils.cpp.

◆ EnterMutex()

bool cmlabs::utils::EnterMutex ( const char * name,
uint32 ms,
bool autocreate = true )

Acquire a named global mutex, creating it on first use.

Parameters
nameMutex name.
msTimeout in milliseconds.
autocreateCreate the mutex if it does not yet exist.
Returns
true when acquired.

Definition at line 649 of file Utils.cpp.

References cmlabs::utils::Mutex::enter(), SharedMemoryMutexMap, and SharedMemoryMutexMapMutex.

◆ FromOSPriority()

int cmlabs::utils::FromOSPriority ( int pri)

Map a native OS priority back to the CMSDK priority scale.

Parameters
priOS priority.
Returns
CMSDK priority.

Definition at line 3680 of file Utils.cpp.

Referenced by GetThreadPriority().

◆ GetBit()

bool cmlabs::utils::GetBit ( uint32 loc,
const char * bitfield,
uint32 bytesize,
bit & val )

Read bit loc.

Parameters
locBit index.
bitfieldField data.
bytesizeField size in bytes.
[out]valReceives the bit.
Returns
false when out of range.

Definition at line 2692 of file Utils.cpp.

Referenced by cmlabs::GenericMemoryMap< T, ID >::CreateEntry().

◆ GetBitFieldAsString()

std::string cmlabs::utils::GetBitFieldAsString ( const char * bitfield,
uint32 bytesize,
uint32 size )

Render the first size bits as a '0'/'1' string, for debugging.

Parameters
bitfieldField data.
bytesizeField size in bytes.
sizeNumber of bits to render.
Returns
Text representation.

Definition at line 2742 of file Utils.cpp.

Referenced by PrintBitFieldString().

◆ GetCPUTicks() [1/2]

bool cmlabs::utils::GetCPUTicks ( ThreadHandle hThread,
uint64 & ticks )

Get accumulated CPU time of a specific thread.

Parameters
hThreadThread handle.
[out]ticksReceives CPU time in microseconds.
Returns
true on success.
Note
Cross-thread queries are Windows-only until pthreads exposes per-thread getrusage.

Definition at line 3210 of file Utils.cpp.

References ThreadHandle.

Referenced by cmlabs::ThreadManager::addLocalThreadStats(), cmlabs::PsyAPI::postOutputMessage(), cmlabs::ThreadManager::threadMonitoring(), and cmlabs::PsyAPI::waitForNewMessage().

◆ GetCPUTicks() [2/2]

bool cmlabs::utils::GetCPUTicks ( uint64 & ticks)

Get accumulated CPU time of the calling thread.

Parameters
[out]ticksReceives CPU time in microseconds.
Returns
true on success.

Definition at line 3261 of file Utils.cpp.

References GetCurrentThread().

◆ GetCurrentThread()

bool cmlabs::utils::GetCurrentThread ( ThreadHandle & thread)

Get the handle of the calling thread.

Parameters
[out]threadReceives the handle.
Returns
true on success.

Definition at line 3158 of file Utils.cpp.

References GetCurrentThread(), and ThreadHandle.

Referenced by GetCPUTicks(), and GetCurrentThread().

◆ GetCurrentThreadOSID()

bool cmlabs::utils::GetCurrentThreadOSID ( uint32 & tid)

Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).

Parameters
[out]tidReceives the id.
Returns
true on success.

Definition at line 3138 of file Utils.cpp.

Referenced by cmlabs::utils::Mutex::enter(), and cmlabs::utils::Mutex::enter().

◆ GetCurrentThreadUniqueID()

bool cmlabs::utils::GetCurrentThreadUniqueID ( uint32 & tid)

Get a process-unique id for the calling thread.

Parameters
[out]tidReceives the id.
Returns
true on success.

Definition at line 3118 of file Utils.cpp.

Referenced by cmlabs::ThreadManager::getLocalThreadID().

◆ GetDesktopSize()

bool cmlabs::utils::GetDesktopSize ( uint32 & width,
uint32 & height )

Get the primary desktop resolution.

Parameters
[out]widthPixels.
[out]heightPixels.
Returns
true on success (false on headless systems).

Definition at line 3720 of file Utils.cpp.

◆ GetFirstFreeBitLoc()

bool cmlabs::utils::GetFirstFreeBitLoc ( const char * bitfield,
uint32 bytesize,
uint32 & loc )

Find the first 0 (free) bit.

Parameters
bitfieldField data.
bytesizeField size in bytes.
[out]locReceives the bit index.
Returns
true when a free bit exists.

Definition at line 2473 of file Utils.cpp.

Referenced by cmlabs::MemoryRequestQueues::AddNewRequest(), cmlabs::GenericMemoryMap< T, ID >::CreateFirstFreeEntry(), cmlabs::ThreadManager::createThread(), cmlabs::TemporalMemory::insertMessage(), and UnitTest_Utils().

◆ GetFirstFreeBitLocN()

bool cmlabs::utils::GetFirstFreeBitLocN ( const char * bitfield,
uint32 bytesize,
uint32 num,
uint32 & loc )

Find the first run of num consecutive 0 bits.

Parameters
bitfieldField data.
bytesizeField size in bytes.
numRun length required.
[out]locReceives the start bit index.
Returns
true when such a run exists.

Definition at line 2496 of file Utils.cpp.

References BITFREE, MAXVALUINT16, and MAXVALUINT32.

Referenced by cmlabs::TemporalMemory::insertMessage(), and UnitTest_Utils().

◆ GetLastOccupiedBitLoc()

bool cmlabs::utils::GetLastOccupiedBitLoc ( const char * bitfield,
uint32 bytesize,
uint32 & loc )

Find the highest set (occupied) bit.

Parameters
bitfieldField data.
bytesizeField size in bytes.
[out]locReceives the bit index.
Returns
false when the field is all zero.

Definition at line 2717 of file Utils.cpp.

Referenced by UnitTest_Utils().

◆ GetLocalProcessID()

uint32 cmlabs::utils::GetLocalProcessID ( )

Get the OS process id of the current process.

Returns
PID.

Definition at line 3799 of file Utils.cpp.

◆ GetNextLineEnd()

bool cmlabs::utils::GetNextLineEnd ( const char * str,
uint32 size,
uint32 & len,
uint32 & crSize )

Find the end of the current line.

Parameters
strText.
sizeBytes available.
[out]lenLine length excluding the terminator.
[out]crSizeTerminator size (1 for \n, 2 for \r\n).
Returns
true when a line terminator was found.

Definition at line 6332 of file Utils.cpp.

Referenced by cmlabs::HTTPReply::processHeader(), and cmlabs::HTTPRequest::processHeader().

◆ GetOSCPUUsage()

bool cmlabs::utils::GetOSCPUUsage ( double & percentUse)

Get the instantaneous total OS CPU usage.

Parameters
[out]percentUseUsage in percent.
Returns
true on success.

Definition at line 3533 of file Utils.cpp.

◆ GetProcAndOSCPUUsage() [1/2]

bool cmlabs::utils::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.

Parameters
[out]procPercentUseProcess CPU usage in percent.
[out]osPercentUseTotal OS CPU usage in percent.
[in,out]prevOSTicksCaller-kept previous total-OS tick counter.
[in,out]prevOSIdleTicksCaller-kept previous idle tick counter.
[in,out]prevProcTicksCaller-kept previous process tick counter.
Returns
true on success.
Note
Pass the same three counters on every call; the first call establishes the baseline.

Definition at line 3415 of file Utils.cpp.

References GetProcAndOSCPUUsage().

Referenced by GetProcAndOSCPUUsage().

◆ GetProcAndOSCPUUsage() [2/2]

bool cmlabs::utils::GetProcAndOSCPUUsage ( uint32 osProcID,
double & procPercentUse,
double & osPercentUse,
uint64 & prevOSTicks,
uint64 & prevOSIdleTicks,
uint64 & prevProcTicks )

As GetProcAndOSCPUUsage() above, but for an arbitrary process.

Parameters
osProcIDOS process id.
[out]procPercentUseProcess CPU usage in percent.
[out]osPercentUseTotal OS CPU usage in percent.
[in,out]prevOSTicksCaller-kept previous total-OS tick counter.
[in,out]prevOSIdleTicksCaller-kept previous idle tick counter.
[in,out]prevProcTicksCaller-kept previous process tick counter.

Definition at line 3424 of file Utils.cpp.

References FALSE, and StringFormat().

◆ GetProcessCPUTicks() [1/2]

bool cmlabs::utils::GetProcessCPUTicks ( uint32 osProcID,
uint64 & ticks )

Get accumulated CPU time of another process.

Parameters
osProcIDOS process id.
[out]ticksReceives CPU time in microseconds.
Returns
true on success.

Definition at line 3304 of file Utils.cpp.

References FALSE.

◆ GetProcessCPUTicks() [2/2]

bool cmlabs::utils::GetProcessCPUTicks ( uint64 & ticks)

Get accumulated CPU time of the current process.

Parameters
[out]ticksReceives CPU time in microseconds.
Returns
true on success.

Definition at line 3368 of file Utils.cpp.

◆ GetProcessStatus()

uint8 cmlabs::utils::GetProcessStatus ( uint32 proc,
int & returncode )

Poll a child started with NewProcess().

Parameters
procProcess id from NewProcess().
[out]returncodeExit code when terminated.
Returns
One of PROC_ERROR / PROC_TERMINATED / PROC_NOTSTARTED / PROC_RUNNING.

Definition at line 4128 of file Utils.cpp.

References PROC_ERROR, PROC_RUNNING, and PROC_TERMINATED.

Referenced by WaitForProcess().

◆ GetProgramTrace()

std::list< std::string > cmlabs::utils::GetProgramTrace ( )

Capture the current call stack.

Returns
One string per stack frame, top first.

Definition at line 2855 of file Utils.cpp.

Referenced by PrintProgramTrace().

◆ GetSemaphore()

Semaphore * cmlabs::utils::GetSemaphore ( const char * name,
bool autocreate = true )

Look up (and optionally create) a named semaphore in the global registry.

Parameters
nameSemaphore name.
autocreateCreate when missing.
Returns
Registry-owned pointer (do not delete), or NULL.

Definition at line 726 of file Utils.cpp.

References SharedMemorySemaphoreMap, and SharedMemorySemaphoreMapMutex.

◆ GetSharedSystemInstance()

uint32 cmlabs::utils::GetSharedSystemInstance ( )

Get the current shared-system instance number.

Returns
Instance set via SetSharedSystemInstance(), default 0.

Definition at line 943 of file Utils.cpp.

References SharedSystemInstance.

◆ GetThreadPriority()

bool cmlabs::utils::GetThreadPriority ( ThreadHandle hThread,
uint16 priority )

Query a thread's scheduling priority.

Parameters
hThreadThread handle.
priorityReceives/compares the CMSDK priority value.
Returns
true on success.

Definition at line 3590 of file Utils.cpp.

References FromOSPriority(), GetThreadPriority(), and ThreadHandle.

Referenced by GetThreadPriority().

◆ GetThreadStatColAbility()

uint32 cmlabs::utils::GetThreadStatColAbility ( )

Report this platform's capability for per-thread CPU statistics collection.

Returns
One of THREAD_STATS_OFF / THREAD_STATS_AUTO / THREAD_STATS_ADHOC.

Definition at line 3198 of file Utils.cpp.

References THREAD_STATS_ADHOC, THREAD_STATS_AUTO, and THREAD_STATS_OFF.

Referenced by cmlabs::ThreadManager::resizeThreadStorage().

◆ hton64()

uint64 cmlabs::utils::hton64 ( const uint64_t * input)

Convert a 64-bit value from host to network byte order.

Parameters
inputHost-order value.
Returns
Big-endian value.

References ThreadHandle.

◆ IsThreadRunning()

bool cmlabs::utils::IsThreadRunning ( ThreadHandle hThread)

Check whether a thread is still alive.

Parameters
hThreadThread handle.
Returns
true when running.

Definition at line 3168 of file Utils.cpp.

References ThreadHandle.

Referenced by cmlabs::ThreadManager::isThreadRunning().

◆ laststristr()

const char * cmlabs::utils::laststristr ( const char * str1,
const char * str2 )

Case-insensitive laststrstr().

Returns
Pointer to the last match, or NULL.

Definition at line 7466 of file Utils.cpp.

References stricmp, and strnicmp.

Referenced by TextEndsWith().

◆ laststrstr()

const char * cmlabs::utils::laststrstr ( const char * str1,
const char * str2 )

Find the last occurrence of str2 in str1.

Returns
Pointer to the last match, or NULL.

Definition at line 7441 of file Utils.cpp.

Referenced by AddToJSONRoot(), cmlabs::JSONM::getJSON(), cmlabs::JSONM::isValid(), and TextEndsWith().

◆ LeaveMutex()

bool cmlabs::utils::LeaveMutex ( const char * name)

Release a named global mutex previously acquired with EnterMutex().

Parameters
nameMutex name.
Returns
true on success.

Definition at line 689 of file Utils.cpp.

References SharedMemoryMutexMap, and SharedMemoryMutexMapMutex.

◆ MoveConsoleWindow()

bool cmlabs::utils::MoveConsoleWindow ( int32 x = -1,
int32 y = -1,
int32 w = -1,
int32 h = -1 )

Move/resize the console window.

Parameters
x,yPosition (-1 = keep).
w,hSize (-1 = keep).
Returns
true on success.
Note
Windows-only effect.

Definition at line 3762 of file Utils.cpp.

◆ NewProcess()

uint32 cmlabs::utils::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.

Parameters
cmdlineCommand line.
initdirWorking directory (NULL = inherit).
titleConsole title (Windows).
x,y,w,hInitial console window geometry (-1 = default; Windows only).
Returns
Process handle id for use with GetProcessStatus()/EndProcess()/WaitForProcess(), or 0 on failure.

Definition at line 4001 of file Utils.cpp.

References DeleteCommandline(), LOG_SYSTEM, LogPrint, SplitCommandline(), StringFormat(), and TRUE.

Referenced by NewProcessEx().

◆ NewProcessEx()

uint32 cmlabs::utils::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.

Parameters
cmdlineCommand line (already substituted).
initdirWorking directory (NULL/"" = inherit).
titleConsole/space title.
envExtra environment variables merged over the parent's (NULL = none).
captureOutputtrue to redirect the child's stdout/stderr into pipes readable via ReadProcessOutput().
ignoreOutputtrue to send the child's stdout/stderr to the null device (ignored unless captureOutput is false).
newProcessGrouptrue to start the child in its own process group so it can be sent a graceful console break via SendProcessBreak() independently of the parent (recommended for graceful stop).
Returns
Process id for GetProcessStatus()/EndProcess()/ReadProcessOutput()/SendProcessBreak(), or 0 on failure.

Definition at line 4222 of file Utils.cpp.

References LOG_SYSTEM, LogPrint, NewProcess(), StringFormat(), and TRUE.

◆ ntoh64()

uint64 cmlabs::utils::ntoh64 ( const uint64 * input)

Convert a 64-bit value from network to host byte order.

Parameters
inputBig-endian value.
Returns
Host-order value.

Definition at line 2442 of file Utils.cpp.

Referenced by hton64(), cmlabs::WebsocketData::processHeader(), and cmlabs::WebsocketData::setData().

◆ OpenSharedMemorySegment()

char * cmlabs::utils::OpenSharedMemorySegment ( const char * name,
uint64 size )

◆ PauseThread()

bool cmlabs::utils::PauseThread ( ThreadHandle hThread)

Suspend a thread's execution.

Parameters
hThreadThread handle.
Returns
true on success.
Note
Windows: SuspendThread; POSIX: signal-based, may not be supported everywhere.

Definition at line 3098 of file Utils.cpp.

References ThreadHandle.

Referenced by cmlabs::ThreadManager::pauseThread().

◆ PrintBinary()

void cmlabs::utils::PrintBinary ( void * p,
uint32 size,
bool asInt,
const char * title )

Hex/decimal dump a memory region to stdout for debugging.

Parameters
pData.
sizeBytes.
asIntPrint as integers instead of hex bytes.
titleHeading.

Definition at line 6258 of file Utils.cpp.

◆ PrintBitFieldString()

std::string cmlabs::utils::PrintBitFieldString ( const char * bitfield,
uint32 bytesize,
uint32 size,
const char * title )

Like GetBitFieldAsString() but prefixed with title and formatted for printing.

Parameters
bitfieldField data.
bytesizeField size in bytes.
sizeNumber of bits.
titleHeading text.
Returns
Printable text.

Definition at line 2761 of file Utils.cpp.

References GetBitFieldAsString(), and StringFormat().

Referenced by UnitTest_Utils().

◆ PrintProgramTrace()

std::string cmlabs::utils::PrintProgramTrace ( uint32 startLine = 0,
uint32 endLine = 0 )

Format the current call stack as printable text.

Parameters
startLineFirst stack frame to include (0 = top).
endLineLast frame (0 = all).
Returns
Multi-line backtrace text.
Note
Uses backtrace() on POSIX; symbol quality depends on build flags.

Definition at line 2840 of file Utils.cpp.

References GetProgramTrace().

◆ ReadProcessOutput()

bool cmlabs::utils::ReadProcessOutput ( uint32 proc,
std::string & out,
std::string & err )

Read any pending captured stdout/stderr from a child launched with captureOutput=true.

Non-blocking. Appends raw bytes (may be partial lines) to the supplied strings.

Parameters
procProcess id.
[out]outAppended stdout bytes.
[out]errAppended stderr bytes.
Returns
true if the process is known and its pipes were polled (even if nothing was read).

Definition at line 4357 of file Utils.cpp.

◆ ReapThread()

bool cmlabs::utils::ReapThread ( ThreadHandle & hThread)

Definition at line 2976 of file Utils.cpp.

References ThreadHandle.

◆ RenameConsoleWindow()

bool cmlabs::utils::RenameConsoleWindow ( const char * name,
bool prepend = false )

Set the console window title.

Parameters
nameNew title.
prependPrepend to the existing title instead of replacing it.
Returns
true on success.
Note
Windows-only effect; no-op elsewhere.

Definition at line 3740 of file Utils.cpp.

References StringFormat().

◆ Reset32BitField()

bool cmlabs::utils::Reset32BitField ( char * bitfield,
uint32 bytesize )

Zero the whole bitfield, marking every bit as free.

Parameters
bitfieldField data.
bytesizeField size in bytes.
Returns
true on success.

Definition at line 2467 of file Utils.cpp.

Referenced by UnitTest_Utils().

◆ RunOSCommand()

int cmlabs::utils::RunOSCommand ( const char * cmdline,
const char * initdir,
uint32 timeout,
std::string & stdoutString,
std::string & stderrString )

Run a command synchronously and capture its output.

Parameters
cmdlineCommand line to execute.
initdirWorking directory (NULL = inherit).
timeoutMax run time in milliseconds before the child is killed.
[out]stdoutStringCaptured standard output.
[out]stderrStringCaptured standard error.
Returns
Child exit code, or a negative value on launch failure.

Definition at line 3808 of file Utils.cpp.

References FALSE, cmlabs::GetTimeAgeMS(), cmlabs::GetTimeNow(), PROCBUFSIZE, StringFormat(), and TRUE.

Referenced by GetComputerName().

◆ SendProcessBreak()

bool cmlabs::utils::SendProcessBreak ( uint32 proc,
int sig )

Attempt a graceful stop: POSIX sends the given signal; Windows posts a CTRL_BREAK to the child's process group (requires newProcessGroup=true at launch) and falls back to nothing if unsupported.

Callers should wait, then EndProcess() as the forceful fallback.

Parameters
procProcess id.
sigPOSIX signal number (ignored on Windows).
Returns
true if the request was delivered.

Definition at line 4384 of file Utils.cpp.

◆ SetBit()

bool cmlabs::utils::SetBit ( uint32 loc,
bit value,
char * bitfield,
uint32 bytesize )

◆ SetBitN()

bool cmlabs::utils::SetBitN ( uint32 loc,
uint32 num,
bit value,
char * bitfield,
uint32 bytesize )

Set num consecutive bits starting at loc to value.

Parameters
locFirst bit index.
numRun length.
value0 or 1.
bitfieldField data.
bytesizeField size in bytes.
Returns
false when out of range.

Definition at line 2629 of file Utils.cpp.

References MAXVALUINT16, and MAXVALUINT32.

Referenced by cmlabs::TemporalMemory::insertMessage(), and UnitTest_Utils().

◆ SetSharedSystemInstance()

bool cmlabs::utils::SetSharedSystemInstance ( uint32 inst)

Set the instance number used to namespace shared OS objects, allowing several independent CMSDK systems on one host.

Parameters
instInstance number (0 = default namespace).
Returns
true on success.

Definition at line 938 of file Utils.cpp.

References SharedSystemInstance.

◆ SetThreadPriority()

bool cmlabs::utils::SetThreadPriority ( ThreadHandle hThread,
uint16 priority )

Set a thread's scheduling priority.

Parameters
hThreadThread handle.
priorityCMSDK priority value (converted via ToOSPriority()).
Returns
true on success.

Definition at line 3613 of file Utils.cpp.

References SetThreadPriority(), ThreadHandle, and ToOSPriority().

Referenced by SetThreadPriority().

◆ SignalEvent()

bool cmlabs::utils::SignalEvent ( const char * name)

Signal a named global event.

Parameters
nameEvent name.
Returns
true on success.

Definition at line 904 of file Utils.cpp.

References SharedMemoryEventMap, and SharedMemoryEventMapMutex.

◆ SignalSemaphore()

bool cmlabs::utils::SignalSemaphore ( const char * name)

◆ SignalThread()

bool cmlabs::utils::SignalThread ( ThreadHandle hThread,
int32 signal )

Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).

Parameters
hThreadThread handle.
signalSignal number.
Returns
true on success.

Definition at line 3704 of file Utils.cpp.

References ThreadHandle.

◆ Sleep()

bool cmlabs::utils::Sleep ( uint32 ms)

◆ StartDrumBeat()

bool cmlabs::utils::StartDrumBeat ( uint32 id)

Start (or resume) a previously created drum beat.

Parameters
idBeat id.
Returns
true on success.

Definition at line 535 of file Utils.cpp.

References cmlabs::utils::DrumBeatInfo::createdTime, DrumBeatCallback(), DrumBeatMap, cmlabs::utils::DrumBeatInfo::handle, cmlabs::utils::DrumBeatInfo::id, cmlabs::utils::DrumBeatInfo::interval, LOG_SYSTEM, LogPrint, and cmlabs::utils::DrumBeatInfo::started.

Referenced by CreateDrumBeat().

◆ StopDrumBeat()

bool cmlabs::utils::StopDrumBeat ( uint32 id)

Stop a running drum beat without destroying it.

Parameters
idBeat id.
Returns
true on success.

Definition at line 581 of file Utils.cpp.

References cmlabs::utils::DrumBeatInfo::createdTime, DrumBeatMap, cmlabs::utils::DrumBeatInfo::handle, cmlabs::utils::DrumBeatInfo::id, LOG_SYSTEM, LogPrint, and cmlabs::utils::DrumBeatInfo::started.

Referenced by DrumBeatCallback(), and EndDrumBeat().

◆ strcpyavail()

uint32 cmlabs::utils::strcpyavail ( char * dst,
const char * src,
uint32 maxlen,
bool copyAvailable )

Bounded strcpy that always NUL-terminates.

Parameters
dstDestination buffer.
srcSource.
maxlenDestination capacity.
copyAvailableWhen true, copy as much as fits; when false, copy nothing unless the whole string fits.
Returns
Number of bytes copied (excluding NUL).

Definition at line 6314 of file Utils.cpp.

Referenced by cmlabs::MessagePlayer::addMessage(), BytifySizes(), cmlabs::PostSpec::contentFromXML(), cmlabs::ProcessMemory::create(), cmlabs::ComponentData::CreateComponent(), cmlabs::ComponentMemory::createComponent(), cmlabs::GenericMemoryMap< T, ID >::CreateEntry(), cmlabs::GenericMemoryMap< T, ID >::CreateFirstFreeEntry(), cmlabs::MemoryMaps::CreateNewCrank(), cmlabs::DataMapsMemory::createNewCrank(), cmlabs::ProcessMemory::createNewProcess(), cmlabs::ComponentMemory::createParameter(), cmlabs::ObsString::extractDataFromMessage(), cmlabs::ObsString::extractRangeFrom(), cmlabs::ObsString::extractRangeTo(), cmlabs::FilterSpec::fromXML(), cmlabs::PostSpec::fromXML(), cmlabs::QuerySpec::fromXML(), cmlabs::RetrieveSpec::fromXML(), cmlabs::SignalSpec::fromXML(), cmlabs::ComponentMemory::getComponentName(), GetComputerName(), cmlabs::MemoryMaps::GetCrankFunction(), cmlabs::DataMapsMemory::getCrankFunction(), cmlabs::DataMapsMemory::getCrankLanguage(), cmlabs::MemoryMaps::GetCrankLibraryFilename(), cmlabs::DataMapsMemory::getCrankLibraryFilename(), cmlabs::MemoryMaps::GetCrankScript(), cmlabs::DataMapsMemory::getCrankScript(), cmlabs::GetDateAndTime(), cmlabs::GenericMemoryMap< T, ID >::GetEntryName(), GetFileList(), GetLocalInterfaces(), cmlabs::html::GetMimeType(), cmlabs::ComponentMemory::getParameter(), cmlabs::ProcessMemory::getProcessCommandLine(), cmlabs::ProcessMemory::getProcessName(), GetSocketError(), GetSystemArchitecture(), GetSystemOSName(), GetSystemOSVersion(), cmlabs::GetTimeFromString(), cmlabs::MemoryRequestServer::init(), LookupHostname(), cmlabs::opendir(), cmlabs::PrintTimeDif(), cmlabs::ComponentData::RecordRemoteComponent(), cmlabs::ComponentData::ReserveComponentID(), cmlabs::PsyAPI::retrieveStringParam(), cmlabs::utils::Semaphore::Semaphore(), cmlabs::PsyAPI::setCommandlineBasedir(), cmlabs::MemoryMaps::SetCrankScript(), cmlabs::LogSystem::SetLogFileOutput(), cmlabs::ComponentMemory::setParameter(), cmlabs::ProcessMemory::setProcessCommandLine(), cmlabs::DataMessage::setRawData(), StringFormatInto(), cmlabs::ComponentMemory::UnitTest(), cmlabs::MessageIndex::UnitTest(), cmlabs::TriggerSpec::UnitTest(), cmlabs::PsyAPI::waitForNewMessage(), and cmlabs::MessagePlayer::waitForNextMessage().

◆ stristr()

◆ TerminateThread()

bool cmlabs::utils::TerminateThread ( ThreadHandle hThread)

Forcibly kill a thread.

Parameters
hThreadThread handle.
Returns
true on success.
Note
Last resort only: locks and heap state held by the thread stay corrupted/leaked.

Definition at line 3068 of file Utils.cpp.

References LOG_SYSTEM, LogPrint, TerminateThread(), and ThreadHandle.

Referenced by cmlabs::ThreadManager::interruptThread(), TerminateThread(), and cmlabs::ThreadManager::terminateThread().

◆ TextEndsWith()

bool cmlabs::utils::TextEndsWith ( const char * str,
const char * end,
bool caseSensitive = true )

Test whether str ends with end.

Parameters
strText.
endSuffix.
caseSensitiveCompare case-sensitively when true.
Returns
true on match.

Definition at line 7491 of file Utils.cpp.

References laststristr(), and laststrstr().

Referenced by GetFileList(), cmlabs::DataMessage::getKeyType(), cmlabs::html::GetMimeType(), cmlabs::MessagePlayer::initRead(), cmlabs::MessagePlayer::initWrite(), cmlabs::DataMessage::isArrayContent(), cmlabs::DataMessage::isMapContent(), and cmlabs::utils::Library::patchLibraryFilename().

◆ TextReplaceCharsInPlace()

uint32 cmlabs::utils::TextReplaceCharsInPlace ( char * str,
uint32 size,
char find,
char replace )

Replace every occurrence of a character, in place.

Parameters
strBuffer.
sizeBytes to scan.
findCharacter to replace.
replaceReplacement.
Returns
Number of replacements.

Definition at line 7430 of file Utils.cpp.

◆ TextStartsWith()

◆ TimerCallback()

void cmlabs::utils::TimerCallback ( int sig,
siginfo_t * siginfo,
void * context )
static

POSIX signal-based timer callback trampoline (SIGEV_SIGNAL); routes the expiry into the owning Timer's trigger queue.

Definition at line 1854 of file Utils.cpp.

References cmlabs::utils::TimerSchedule::globalID, cmlabs::utils::TimerSchedule::id, cmlabs::utils::Timer::timers, and cmlabs::utils::Timer::triggerTimer().

Referenced by cmlabs::utils::Timer::addTimer().

◆ ToOSPriority()

int cmlabs::utils::ToOSPriority ( int pri)

Map a CMSDK priority value to the platform's native priority scale.

Parameters
priCMSDK priority.
Returns
OS priority.

Definition at line 3632 of file Utils.cpp.

Referenced by SetThreadPriority().

◆ TryReapThread()

bool cmlabs::utils::TryReapThread ( ThreadHandle & hThread)

◆ UnitTest_Timer()

bool cmlabs::utils::UnitTest_Timer ( )

◆ UnitTest_Utils()

bool cmlabs::utils::UnitTest_Utils ( )

Aggregate self test for miscellaneous utils functionality.

Returns
true when all checks pass.

Definition at line 1931 of file Utils.cpp.

References BITFREE, BITOCCUPIED, Calc32BitFieldSize(), cmlabs::unittest::detail(), cmlabs::unittest::fail(), GetFirstFreeBitLoc(), GetFirstFreeBitLocN(), GetLastOccupiedBitLoc(), PrintBitFieldString(), cmlabs::unittest::progress(), Reset32BitField(), SetBit(), and SetBitN().

Referenced by cmlabs::Test_Utils().

◆ UtilsTest()

bool cmlabs::utils::UtilsTest ( )

Run the built-in self test of the utils module.

Run the built-in self test of the utils module (duplicate declaration).

Returns
true when all sub-tests pass.
true on success.

Definition at line 6216 of file Utils.cpp.

References GetLocalHostname(), GetLocalInterfaces(), GetLocalIPAddress(), GetLocalIPAddresses(), and LOCALHOSTIP.

◆ WaitForProcess()

uint8 cmlabs::utils::WaitForProcess ( uint32 proc,
uint32 timeout,
int & returncode )

Wait for a child to exit.

Parameters
procProcess id.
timeoutMax wait in ms.
[out]returncodeExit code.
Returns
PROC_TERMINATED, PROC_TIMEOUT or PROC_ERROR.

Definition at line 4395 of file Utils.cpp.

References GetProcessStatus(), cmlabs::GetTimeAgeMS(), cmlabs::GetTimeNow(), PROC_ERROR, PROC_RUNNING, PROC_TERMINATED, PROC_TIMEOUT, and Sleep().

◆ WaitForSemaphore()

bool cmlabs::utils::WaitForSemaphore ( const char * name,
uint32 ms,
bool autocreate = true )

Wait on a named global semaphore.

Parameters
nameSemaphore name.
msTimeout in ms.
autocreateCreate when missing.
Returns
true when acquired.

Definition at line 765 of file Utils.cpp.

References SharedMemorySemaphoreMap, SharedMemorySemaphoreMapMutex, and cmlabs::utils::Semaphore::wait().

Referenced by cmlabs::DataMapsMemory::waitForRequestReply().

◆ WaitForThreadToFinish()

bool cmlabs::utils::WaitForThreadToFinish ( ThreadHandle hThread,
uint32 timeoutMS = 0 )

Join a thread.

Parameters
hThreadThread handle.
timeoutMSMax wait in ms (0 = wait forever).
Returns
true when the thread finished.

Definition at line 3018 of file Utils.cpp.

References CalcTimeout(), Sleep(), and ThreadHandle.

◆ WaitNextEvent()

bool cmlabs::utils::WaitNextEvent ( const char * name,
uint32 ms,
bool autocreate = true )

Wait for the next signal on a named global event.

Parameters
nameEvent name.
msTimeout in ms.
autocreateCreate when missing.
Returns
true when signalled.

Variable Documentation

◆ DrumBeatMap

std::map<uint32, DrumBeatInfo>* cmlabs::utils::DrumBeatMap = NULL
static

◆ SharedMemoryEventMap

std::map<std::string, Event*>* cmlabs::utils::SharedMemoryEventMap = NULL
static

Definition at line 594 of file Utils.h.

Referenced by cmlabs::ClearUtilsMaps(), DestroyEvent(), SignalEvent(), and WaitForNextEvent().

◆ SharedMemoryEventMapMutex

Mutex* cmlabs::utils::SharedMemoryEventMapMutex = NULL
static

Definition at line 593 of file Utils.h.

Referenced by cmlabs::ClearUtilsMaps(), DestroyEvent(), SignalEvent(), and WaitForNextEvent().

◆ SharedMemoryFileHandleMap

SharedMemoryFileHandleMapType* cmlabs::utils::SharedMemoryFileHandleMap = NULL
static

◆ SharedMemoryMutexMap

std::map<std::string, Mutex*>* cmlabs::utils::SharedMemoryMutexMap = NULL
static

Definition at line 588 of file Utils.h.

Referenced by cmlabs::ClearUtilsMaps(), DestroyMutex(), EnterMutex(), and LeaveMutex().

◆ SharedMemoryMutexMapMutex

Mutex* cmlabs::utils::SharedMemoryMutexMapMutex = NULL
static

Definition at line 587 of file Utils.h.

Referenced by cmlabs::ClearUtilsMaps(), DestroyMutex(), EnterMutex(), and LeaveMutex().

◆ SharedMemorySemaphoreMap

std::map<std::string, Semaphore*>* cmlabs::utils::SharedMemorySemaphoreMap = NULL
static

◆ SharedMemorySemaphoreMapMutex

Mutex* cmlabs::utils::SharedMemorySemaphoreMapMutex = NULL
static

◆ SharedSystemInstance

uint16 cmlabs::utils::SharedSystemInstance = 0
static

Definition at line 397 of file Utils.h.

Referenced by GetSharedSystemInstance(), and SetSharedSystemInstance().