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:8238
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:7548
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:7610
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
Definition Utils.cpp:7952
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:8318
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:8067
char * ReadAFile(const char *filename, uint32 &length, bool binary=false)
Read an entire file into a new buffer.
Definition Utils.cpp:8259
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:8903
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
Definition Utils.cpp:8987
std::string TextJoin(std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
Join vector elements with split.
Definition Utils.cpp:7871
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::ProcessData
 POSIX capture bookkeeping for children started via NewProcessEx(captureOutput). 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...
struct  cmlabs::utils::ProcessWaitInfo
 Snapshot from ProbeProcessWait(): is the child (group) alive, is it blocked reading stdin, and how much CPU has the group burned so far (caller diffs successive samples). 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
typedef std::pair< uint32, ProcessData * > cmlabs::utils::Proc_Pair

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
static std::map< uint32, ProcessData * > * cmlabs::utils::ProcessInformationMap = 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.

Threading and CPU statistics

typedef void(* cmlabs::utils::ShutdownSignalCallback) (int sig, int count)
 Callback invoked (on the dedicated signal thread) when a graceful-shutdown signal is caught.
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::BlockShutdownSignals ()
 Block the graceful-shutdown signals (SIGINT, SIGTERM, SIGHUP) on the CALLING thread.
bool cmlabs::utils::StartSignalThread (ShutdownSignalCallback cb)
 Start the dedicated signal-handling thread (POSIX only).
bool cmlabs::utils::StopSignalThread ()
 Stop the dedicated signal thread and join it.
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).

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

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.
void cmlabs::utils::ClearStaleSharedSegments (uint16 port)
 Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.

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.

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, int posixParentDeathSig=0, bool posixUseShell=false)
 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::WriteProcessInput (uint32 proc, const char *data, uint32 len)
 Write to the stdin of a child launched with captureOutput=true (T1.1 step 2.7c).
bool cmlabs::utils::CloseProcessInput (uint32 proc)
 Close a child's stdin, delivering EOF (T1.1 step 2.7c).
void cmlabs::utils::ReleaseProcessCapture (uint32 proc)
 POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captureOutput=true), WITHOUT signalling or reaping the child.
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.
bool cmlabs::utils::ProbeProcessWait (uint32 pid, ProcessWaitInfo &out)
 Probe whether a child process (group) appears blocked reading stdin (fd 0).

Terminal-mode child launch (T1.1 step 2.7d, POSIX PTY; Windows ConPTY lands in 2.7e)

A child launched here runs with a real controlling terminal (isatty()==true): stdout+stderr are MERGED into one terminal stream (inherent to terminals) and libc line-buffers instead of fully-buffering, so output appears promptly.

Lifecycle (reap/kill) is via GetProcessStatus()/WaitForProcess()/EndProcess() on the returned pid, exactly like NewProcessEx children; only the master-side terminal fd is bookkept here. NOTE: on child exit a PTY master read reports EIO rather than a clean EOF - ReadProcessTerminal treats that as normal end-of-stream, never as an error.

uint32 cmlabs::utils::NewProcessTerminal (const char *cmdline, const char *initdir, const std::map< std::string, std::string > *env, uint16 cols=0, uint16 rows=0)
 Launch a child on a new pseudo-terminal (POSIX: posix_openpt + fork; child setsid() + TIOCSCTTY so it owns the terminal and leads its own process group for group kill).
bool cmlabs::utils::ReadProcessTerminal (uint32 proc, std::string &out, bool &eofOut)
 Non-blocking read of the merged terminal stream.
bool cmlabs::utils::WriteProcessTerminal (uint32 proc, const char *data, uint32 len)
 Write bytes to the child's terminal input (its stdin).
bool cmlabs::utils::ResizeProcessTerminal (uint32 proc, uint16 cols, uint16 rows)
 Resize the pseudo-terminal (TIOCSWINSZ + SIGWINCH to the child's group).
void cmlabs::utils::CloseProcessTerminal (uint32 proc)
 Close the master side (terminal hangup: the child's foreground group gets SIGHUP and any blocked terminal read ends).

Macro Definition Documentation

◆ CHILD_READ_FD

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

Definition at line 1290 of file Utils.h.

◆ CHILD_WRITE_FD

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

Definition at line 1291 of file Utils.h.

◆ NUM_PIPES

#define NUM_PIPES   2

Definition at line 1281 of file Utils.h.

◆ PARENT_READ_FD

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

Definition at line 1288 of file Utils.h.

◆ PARENT_READ_PIPE

#define PARENT_READ_PIPE   1

Definition at line 1283 of file Utils.h.

◆ PARENT_WRITE_FD

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

Definition at line 1289 of file Utils.h.

◆ PARENT_WRITE_PIPE

#define PARENT_WRITE_PIPE   0

Definition at line 1282 of file Utils.h.

◆ PROC_ERROR

#define PROC_ERROR   0

Definition at line 1275 of file Utils.h.

◆ PROC_NOTSTARTED

#define PROC_NOTSTARTED   2

Definition at line 1277 of file Utils.h.

◆ PROC_RUNNING

#define PROC_RUNNING   3

Definition at line 1278 of file Utils.h.

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

◆ PROC_TERMINATED

#define PROC_TERMINATED   1

◆ PROC_TIMEOUT

#define PROC_TIMEOUT   4

Definition at line 1279 of file Utils.h.

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

◆ PROCBUFSIZE

#define PROCBUFSIZE   4096

Definition at line 1293 of file Utils.h.

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

◆ READ_FD

#define READ_FD   0

Definition at line 1286 of file Utils.h.

◆ SharedMemoryFileHandleMapType

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

◆ WRITE_FD

#define WRITE_FD   1

Definition at line 1287 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.

◆ Proc_Pair

typedef std::pair<uint32, ProcessData*> cmlabs::utils::Proc_Pair

Definition at line 650 of file Utils.h.

◆ SharedMemoryEventMapPair

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

Definition at line 612 of file Utils.h.

◆ SharedMemoryMutexMapPair

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

Definition at line 606 of file Utils.h.

◆ SharedMemorySemaphoreMapPair

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

Definition at line 609 of file Utils.h.

◆ ShutdownSignalCallback

typedef void(* cmlabs::utils::ShutdownSignalCallback) (int sig, int count)

Callback invoked (on the dedicated signal thread) when a graceful-shutdown signal is caught.

Parameters
sigSignal number received (SIGINT/SIGTERM/SIGHUP).
count1-based count of graceful-shutdown signals seen so far this run, so the app can escalate (e.g. hard-exit after repeated CTRL+C). Runs in ordinary thread context (NOT an async-signal handler), so it may call normal library code. Keep it quick and non-blocking: record intent (set a flag / post an event) and return; the actual teardown runs on the main thread.

Definition at line 1147 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 3101 of file Utils.cpp.

Referenced by _wrap_AtomicDecrement32().

◆ 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 3111 of file Utils.cpp.

Referenced by _wrap_AtomicDecrement64().

◆ 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 3081 of file Utils.cpp.

Referenced by _wrap_AtomicIncrement32().

◆ 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 3091 of file Utils.cpp.

Referenced by _wrap_AtomicIncrement64().

◆ BlockShutdownSignals()

bool cmlabs::utils::BlockShutdownSignals ( )

Block the graceful-shutdown signals (SIGINT, SIGTERM, SIGHUP) on the CALLING thread.

Returns
true on success (no-op returning true on Windows).
Note
Call ONCE from main() before spawning ANY other thread: on POSIX the signal mask is inherited by every thread created afterwards, so those signals can then only be dequeued by the dedicated signal thread (see StartSignalThread) and never delivered to an arbitrary worker's async handler. This is what stops a signal-driven exit()/teardown from running on a random worker and deadlocking against the main thread's own teardown.

Definition at line 3433 of file Utils.cpp.

References SignalShutdownSigset().

Referenced by _wrap_BlockShutdownSignals().

◆ 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 2723 of file Utils.cpp.

Referenced by _wrap_Calc32BitFieldSize(), 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 3233 of file Utils.cpp.

References ThreadHandle.

◆ ClearStaleSharedSegments()

void cmlabs::utils::ClearStaleSharedSegments ( uint16 port)

Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.

Linux: unlinks /dev/shm entries (Shmem_*, sem.Semaphore_*) containing the delimited port token. macOS: unlinks /tmp/Psyclone_Shmem_* files containing the delimited port token. Windows: no-op.

Parameters
portThe node port; only segments whose name contains the port as a delimited token are removed.

Definition at line 2678 of file Utils.cpp.

References ClearSegmentsIn(), LOG_SYSTEM, and LogPrint.

Referenced by _wrap_ClearStaleSharedSegments(), and cmlabs::MemoryManager::create().

◆ CloseProcessInput()

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

Close a child's stdin, delivering EOF (T1.1 step 2.7c).

Parameters
procProcess id.
Returns
true if a stdin pipe existed and was closed.
Note
Idempotent. A child blocked reading stdin only sees EOF once EVERY copy of the write end is closed, which is why NewProcessEx closes the child's inherited read end in the parent immediately after CreateProcess.

Definition at line 5331 of file Utils.cpp.

References ProcessInformationMap.

Referenced by _wrap_CloseProcessInput().

◆ CloseProcessTerminal()

void cmlabs::utils::CloseProcessTerminal ( uint32 proc)

Close the master side (terminal hangup: the child's foreground group gets SIGHUP and any blocked terminal read ends).

Does NOT reap the child - callers still waitpid via GetProcessStatus()/WaitForProcess(). No-op if unknown.

Definition at line 5538 of file Utils.cpp.

References TerminalMasterMap.

Referenced by _wrap_CloseProcessTerminal().

◆ CloseSharedMemorySegment()

◆ ContinueThread()

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

Resume a thread paused with PauseThread().

Parameters
hThreadThread handle.
Returns
true on success.

Definition at line 3493 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 495 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 2368 of file Utils.cpp.

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

Referenced by _wrap_CreateSharedMemorySegment__SWIG_0(), _wrap_CreateSharedMemorySegment__SWIG_1(), 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 3187 of file Utils.cpp.

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

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

◆ DestroyEvent()

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

Destroy a named global event.

Parameters
nameEvent name.
Returns
true on success.

Definition at line 939 of file Utils.cpp.

References SharedMemoryEventMap, and SharedMemoryEventMapMutex.

Referenced by _wrap_DestroyEvent().

◆ 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 724 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 858 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 4602 of file Utils.cpp.

References ProcessInformationMap, and ReleaseProcessCapture().

Referenced by _wrap_EndProcess(), cmlabs::ConcRunCrossProcess(), and UnitTest_ProbeProcessWait().

◆ 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 671 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 4066 of file Utils.cpp.

Referenced by _wrap_FromOSPriority(), and 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 2983 of file Utils.cpp.

Referenced by _wrap_GetBit(), and 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 3033 of file Utils.cpp.

Referenced by _wrap_GetBitFieldAsString(), and 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 3596 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 3647 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 3544 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 3524 of file Utils.cpp.

Referenced by _wrap_GetCurrentThreadOSID(), 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 3504 of file Utils.cpp.

Referenced by _wrap_GetCurrentThreadUniqueID(), and 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 4106 of file Utils.cpp.

Referenced by _wrap_GetDesktopSize().

◆ 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 2733 of file Utils.cpp.

Referenced by _wrap_GetFirstFreeBitLoc(), 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 2765 of file Utils.cpp.

References BITFREE, MAXVALUINT16, and MAXVALUINT32.

Referenced by _wrap_GetFirstFreeBitLocN(), 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 3008 of file Utils.cpp.

Referenced by _wrap_GetLastOccupiedBitLoc(), and UnitTest_Utils().

◆ GetLocalProcessID()

uint32 cmlabs::utils::GetLocalProcessID ( )

Get the OS process id of the current process.

Returns
PID.

Definition at line 4185 of file Utils.cpp.

Referenced by _wrap_GetLocalProcessID().

◆ 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 7515 of file Utils.cpp.

Referenced by _wrap_GetNextLineEnd(), 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 3919 of file Utils.cpp.

Referenced by _wrap_GetOSCPUUsage().

◆ 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 3801 of file Utils.cpp.

References GetProcAndOSCPUUsage().

Referenced by _wrap_GetProcAndOSCPUUsage__SWIG_0(), _wrap_GetProcAndOSCPUUsage__SWIG_1(), and 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 3810 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 3690 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 3754 of file Utils.cpp.

Referenced by _wrap_GetProcessCPUTicks__SWIG_0(), and _wrap_GetProcessCPUTicks__SWIG_1().

◆ 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 4519 of file Utils.cpp.

References PROC_ERROR, PROC_RUNNING, PROC_TERMINATED, and ProcessInformationMap.

Referenced by _wrap_GetProcessStatus(), cmlabs::ConcRunCrossProcess(), and 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 3146 of file Utils.cpp.

Referenced by _wrap_GetProgramTrace(), and 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 748 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 965 of file Utils.cpp.

References SharedSystemInstance.

Referenced by _wrap_GetSharedSystemInstance().

◆ 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 3976 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 3584 of file Utils.cpp.

References THREAD_STATS_ADHOC, THREAD_STATS_AUTO, and THREAD_STATS_OFF.

Referenced by _wrap_GetThreadStatColAbility(), and 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.

Referenced by _wrap_hton64().

◆ IsThreadRunning()

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

Check whether a thread is still alive.

Parameters
hThreadThread handle.
Returns
true when running.

Definition at line 3554 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 8649 of file Utils.cpp.

References stricmp, and strnicmp.

Referenced by _wrap_laststristr(), and 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 8624 of file Utils.cpp.

Referenced by _wrap_laststrstr(), 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 711 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 4148 of file Utils.cpp.

Referenced by _wrap_MoveConsoleWindow__SWIG_0(), _wrap_MoveConsoleWindow__SWIG_1(), _wrap_MoveConsoleWindow__SWIG_2(), _wrap_MoveConsoleWindow__SWIG_3(), and _wrap_MoveConsoleWindow__SWIG_4().

◆ 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 4387 of file Utils.cpp.

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

Referenced by _wrap_NewProcess__SWIG_0(), _wrap_NewProcess__SWIG_1(), _wrap_NewProcess__SWIG_2(), _wrap_NewProcess__SWIG_3(), _wrap_NewProcess__SWIG_4(), _wrap_NewProcess__SWIG_5(), _wrap_NewProcess__SWIG_6(), and cmlabs::ConcRunCrossProcess().

◆ 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,
int posixParentDeathSig = 0,
bool posixUseShell = false )

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).
posixParentDeathSigPOSIX only: if non-zero, the child dies with the parent PROCESS. Linux: PR_SET_PDEATHSIG(sig), armed from a persistent internal launcher thread so it is safe to call from transient threads (PDEATHSIG binds to the launching thread, not process). macOS: emulated via a kqueue nanny + own process group (whole tree gets SIGKILL when the parent exits). 0 = no parent-death signal. Ignored on Windows (use Job Objects).
posixUseShellPOSIX only: if true, the child is run as "/bin/sh -c <cmdline>" so shell semantics (redirects, builtins like exit, $VAR expansion, quoting) apply, instead of the default tokenize-and-execvp launch. Ignored on Windows (cmd/CreateProcess already parse the command line).
Returns
Process id for GetProcessStatus()/EndProcess()/ReadProcessOutput()/SendProcessBreak(), or 0 on failure.

Definition at line 5052 of file Utils.cpp.

References cmlabs::utils::PosixLaunchRequest::argv, cmlabs::utils::PosixLaunchRequest::captureOutput, cmlabs::utils::PosixLaunchRequest::cmdline, DeleteCommandline(), cmlabs::utils::PosixLaunchRequest::done, DoPosixForkExec(), cmlabs::utils::PosixLaunchRequest::env, cmlabs::utils::ProcessData::errFD, cmlabs::utils::PosixLaunchRequest::errPipe0, cmlabs::utils::PosixLaunchRequest::errPipe1, cmlabs::utils::PosixLaunchRequest::ignoreOutput, cmlabs::utils::PosixLaunchRequest::initdir, LOG_SYSTEM, LogPrint, cmlabs::utils::PosixLaunchRequest::newProcessGroup, cmlabs::utils::ProcessData::outFD, cmlabs::utils::PosixLaunchRequest::outPipe0, cmlabs::utils::PosixLaunchRequest::outPipe1, cmlabs::utils::PosixLaunchRequest::pid, cmlabs::utils::PosixLaunchRequest::posixParentDeathSig, cmlabs::utils::PosixLaunchRequest::posixUseShell, ProcessInformationMap, SplitCommandline(), SubmitLaunchRequest(), and TRUE.

Referenced by _wrap_NewProcessEx(), _wrap_NewProcessEx__SWIG_0(), _wrap_NewProcessEx__SWIG_1(), _wrap_NewProcessEx__SWIG_2(), and UnitTest_ProbeProcessWait().

◆ NewProcessTerminal()

uint32 cmlabs::utils::NewProcessTerminal ( const char * cmdline,
const char * initdir,
const std::map< std::string, std::string > * env,
uint16 cols = 0,
uint16 rows = 0 )

Launch a child on a new pseudo-terminal (POSIX: posix_openpt + fork; child setsid() + TIOCSCTTY so it owns the terminal and leads its own process group for group kill).

The command runs via "/bin/sh -c <cmdline>" (shell semantics, matching the CLISession interactive path). Windows: stub returning 0 until ConPTY lands in step 2.7e.

Parameters
cmdlineCommand line.
initdirWorking directory (NULL/"" = inherit).
envExtra environment variables merged over the parent's (NULL = none).
cols,rowsInitial terminal size (0,0 = 80x25).
Returns
Process id (also usable with GetProcessStatus()/WaitForProcess()), or 0 on failure.

Definition at line 5405 of file Utils.cpp.

References LOG_SYSTEM, LogPrint, and TerminalMasterMap.

Referenced by _wrap_NewProcessTerminal__SWIG_0(), _wrap_NewProcessTerminal__SWIG_1(), and _wrap_NewProcessTerminal__SWIG_2().

◆ 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 2702 of file Utils.cpp.

Referenced by _wrap_ntoh64(), 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 3484 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 7441 of file Utils.cpp.

Referenced by _wrap_PrintBinary().

◆ 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 3052 of file Utils.cpp.

References GetBitFieldAsString(), and StringFormat().

Referenced by _wrap_PrintBitFieldString(), and 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 3131 of file Utils.cpp.

References GetProgramTrace().

Referenced by _wrap_PrintProgramTrace__SWIG_0(), _wrap_PrintProgramTrace__SWIG_1(), and _wrap_PrintProgramTrace__SWIG_2().

◆ ProbeProcessWait()

bool cmlabs::utils::ProbeProcessWait ( uint32 pid,
ProcessWaitInfo & out )

Probe whether a child process (group) appears blocked reading stdin (fd 0).

waitExact is Linux-only: only Linux can name the exact blocking syscall via /proc/<pid>/syscall. On macOS/Windows waitExact is always false and waitingStdin is a heuristic (all threads waiting, fd 0 is a pipe): a network wait or a sleep() is indistinguishable from an stdin wait without waitExact. Windows is a stub until step 2.7c (alive + cpuTimeMs only; waitingStdin always false). Graceful degradation: if OS introspection is unavailable, returns true with waitExact=false.

Parameters
pidChild process id (as returned by NewProcessEx).
[out]outFilled snapshot.
Returns
true if a probe was performed (even degraded), false only on invalid pid.

Definition at line 4847 of file Utils.cpp.

References cmlabs::utils::ProcessWaitInfo::alive, cmlabs::closedir(), cmlabs::utils::ProcessWaitInfo::cpuTimeMs, cmlabs::dirent::d_name, cmlabs::opendir(), cmlabs::readdir(), cmlabs::utils::ProcessWaitInfo::waitExact, and cmlabs::utils::ProcessWaitInfo::waitingStdin.

Referenced by _wrap_ProbeProcessWait(), and UnitTest_ProbeProcessWait().

◆ 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 5347 of file Utils.cpp.

References cmlabs::utils::ProcessData::errFD, cmlabs::utils::ProcessData::outFD, and ProcessInformationMap.

Referenced by _wrap_ReadProcessOutput().

◆ ReadProcessTerminal()

bool cmlabs::utils::ReadProcessTerminal ( uint32 proc,
std::string & out,
bool & eofOut )

Non-blocking read of the merged terminal stream.

Appends raw bytes to 'out'.

Parameters
procProcess id from NewProcessTerminal().
[out]outAppended terminal bytes.
[out]eofOutSet true when the stream has ended (child exited/hung up; EIO == normal EOF).
Returns
true if the terminal handle is known (even if nothing was read).

Definition at line 5474 of file Utils.cpp.

References TerminalMasterFind().

Referenced by _wrap_ReadProcessTerminal().

◆ ReapThread()

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

Definition at line 3267 of file Utils.cpp.

References ThreadHandle.

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

◆ ReleaseProcessCapture()

void cmlabs::utils::ReleaseProcessCapture ( uint32 proc)

POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captureOutput=true), WITHOUT signalling or reaping the child.

Safe to call after the child has already been reaped (e.g. by GetProcessStatus()/WaitForProcess()), where EndProcess() would risk SIGKILL to a recycled pid. No-op if the pid has no capture entry. Ignored on Windows.

Parameters
procProcess id.

Definition at line 4584 of file Utils.cpp.

References cmlabs::utils::ProcessData::errFD, cmlabs::utils::ProcessData::outFD, and ProcessInformationMap.

Referenced by _wrap_ReleaseProcessCapture(), and EndProcess().

◆ 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 4126 of file Utils.cpp.

References StringFormat().

Referenced by _wrap_RenameConsoleWindow__SWIG_0(), and _wrap_RenameConsoleWindow__SWIG_1().

◆ 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 2727 of file Utils.cpp.

Referenced by _wrap_Reset32BitField(), and UnitTest_Utils().

◆ ResizeProcessTerminal()

bool cmlabs::utils::ResizeProcessTerminal ( uint32 proc,
uint16 cols,
uint16 rows )

Resize the pseudo-terminal (TIOCSWINSZ + SIGWINCH to the child's group).

Returns
true on success.

Definition at line 5521 of file Utils.cpp.

References TerminalMasterFind().

Referenced by _wrap_ResizeProcessTerminal().

◆ 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 4194 of file Utils.cpp.

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

Referenced by _wrap_RunOSCommand(), and 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 5550 of file Utils.cpp.

Referenced by _wrap_SendProcessBreak().

◆ 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 2920 of file Utils.cpp.

References MAXVALUINT16, and MAXVALUINT32.

Referenced by _wrap_SetBitN(), 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 960 of file Utils.cpp.

References SharedSystemInstance.

Referenced by _wrap_SetSharedSystemInstance().

◆ 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 3999 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 926 of file Utils.cpp.

References SharedMemoryEventMap, and SharedMemoryEventMapMutex.

Referenced by _wrap_SignalEvent().

◆ 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 4090 of file Utils.cpp.

References ThreadHandle.

◆ Sleep()

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

Suspend the calling thread.

Parameters
msSleep duration in milliseconds.
Returns
true on success.

Definition at line 3121 of file Utils.cpp.

References Sleep().

Referenced by _wrap_Sleep(), cmlabs::ConcResizer(), cmlabs::ConcRunCrossProcess(), cmlabs::ConcRunThreaded(), cmlabs::ConcWriter(), cmlabs::TCPConnection::connect(), CreateThread(), cmlabs::NetworkChannel::endConnection(), cmlabs::NetworkChannel::HTTPClientRun(), cmlabs::Internal_RetrieveTest(), cmlabs::Internal_SignalPing(), cmlabs::Internal_SignalPong(), cmlabs::NetworkChannel::MessageConnectionRun(), cmlabs::PsyTime_UnitTest(), cmlabs::HTTPProtocol::ReceiveHTTPRequest(), cmlabs::HTTPProtocol::ReceiveWebsocketData(), cmlabs::TestRequestClient::run(), cmlabs::TestWebRequestClient::run(), cmlabs::TestWebSocketRequestClient::run(), cmlabs::NetworkChannel::shutdown(), cmlabs::PsySpace::shutdown(), cmlabs::ThreadManager::shutdown(), Sleep(), cmlabs::Runnable::stop(), cmlabs::NetworkChannel::stopListener(), cmlabs::StopProcessTestThread(), cmlabs::NetworkChannel::TelnetServerRun(), cmlabs::ThreadManager::terminateThread(), cmlabs::NetworkManager::TestHTTP(), cmlabs::ThreadManager::threadMonitoring(), cmlabs::MessageIndex::UnitTest(), cmlabs::NetworkManager::UnitTest(), cmlabs::ProcessMemory::UnitTest(), cmlabs::RequestGateway::UnitTest(), cmlabs::TemporalMemory::UnitTest(), cmlabs::ThreadManager::UnitTest(), UnitTest_ProbeProcessWait(), cmlabs::RequestClient::waitForConnection(), cmlabs::MessagePlayer::waitForNextMessage(), WaitForProcess(), WaitForThreadToFinish(), WriteProcessTerminal(), cmlabs::MemoryManager::~MemoryManager(), and cmlabs::RequestGateway::~RequestGateway().

◆ 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 548 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().

◆ StartSignalThread()

bool cmlabs::utils::StartSignalThread ( ShutdownSignalCallback cb)

Start the dedicated signal-handling thread (POSIX only).

Parameters
cbCallback invoked synchronously on the signal thread for each caught graceful-shutdown signal; see ShutdownSignalCallback.
Returns
true if started (no-op returning true on Windows, where signals arrive via SetConsoleCtrlHandler / signal() instead).
Note
The thread sigwait()s on the shutdown set, so signals are handled in normal (async-signal-safe) context. Requires BlockShutdownSignals() to have run on main first. Idempotent: a second call while running is a no-op.

Definition at line 3445 of file Utils.cpp.

References g_shutdownCallback, g_shutdownSignalCount, g_signalThread, g_signalThreadRunning, g_signalThreadStop, SignalShutdownSigset(), and SignalThreadMain().

Referenced by _wrap_StartSignalThread().

◆ 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 594 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().

◆ StopSignalThread()

bool cmlabs::utils::StopSignalThread ( )

Stop the dedicated signal thread and join it.

Returns
true on success (no-op on Windows or if not started).
Note
Safe during teardown; used mainly so tests can start/stop it cleanly.

Definition at line 3468 of file Utils.cpp.

References g_shutdownCallback, g_signalThread, g_signalThreadRunning, and g_signalThreadStop.

Referenced by _wrap_StopSignalThread().

◆ 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 7497 of file Utils.cpp.

Referenced by _wrap_strcpyavail(), 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 3359 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 )

◆ 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 8613 of file Utils.cpp.

Referenced by _wrap_TextReplaceCharsInPlace().

◆ TextStartsWith()

bool cmlabs::utils::TextStartsWith ( const char * str,
const char * start,
bool caseSensitive = true )

◆ 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 1996 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 4018 of file Utils.cpp.

Referenced by _wrap_ToOSPriority(), and SetThreadPriority().

◆ TryReapThread()

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

◆ UnitTest_ProbeProcessWait()

◆ UnitTest_Timer()

bool cmlabs::utils::UnitTest_Timer ( )

◆ UnitTest_Utils()

bool cmlabs::utils::UnitTest_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 7399 of file Utils.cpp.

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

Referenced by _wrap_UtilsTest().

◆ 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 5561 of file Utils.cpp.

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

Referenced by _wrap_WaitForProcess(), and UnitTest_ProbeProcessWait().

◆ 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 787 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 3309 of file Utils.cpp.

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

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

◆ 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.

◆ WriteProcessInput()

bool cmlabs::utils::WriteProcessInput ( uint32 proc,
const char * data,
uint32 len )

Write to the stdin of a child launched with captureOutput=true (T1.1 step 2.7c).

Windows only has a stdin pipe to write to since 2.7c; before that the child inherited the parent's STD_INPUT_HANDLE and there was no handle here at all.

Parameters
procProcess id.
dataBytes to write (not NUL-terminated).
lenByte count.
Returns
true if ALL bytes were written; false if the pid is unknown, has no stdin pipe, the child has closed its end, or the write failed.
Note
POSIX returns false: the fork/pipe path in CLISession owns its own stdin fd and writes to it directly, so routing that through the shared map would be a second owner of the same descriptor.
See also
CloseProcessInput()

Definition at line 5301 of file Utils.cpp.

References ProcessInformationMap.

Referenced by _wrap_WriteProcessInput().

◆ WriteProcessTerminal()

bool cmlabs::utils::WriteProcessTerminal ( uint32 proc,
const char * data,
uint32 len )

Write bytes to the child's terminal input (its stdin).

May block briefly if the child is not reading.

Returns
true if all bytes were written.

Definition at line 5499 of file Utils.cpp.

References Sleep(), and TerminalMasterFind().

Referenced by _wrap_WriteProcessTerminal().

Variable Documentation

◆ DrumBeatMap

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

◆ ProcessInformationMap

std::map<uint32, ProcessData*>* cmlabs::utils::ProcessInformationMap = NULL
static

◆ SharedMemoryEventMap

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

Definition at line 611 of file Utils.h.

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

◆ SharedMemoryEventMapMutex

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

Definition at line 610 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 605 of file Utils.h.

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

◆ SharedMemoryMutexMapMutex

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

Definition at line 604 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