ReXGlue SDK
Loading...
Searching...
No Matches
rex::platform Namespace Reference

Classes

struct  CrashReporterOptions
class  DynamicLibrary
class  Event
class  Exception
class  ExceptionHandler
class  Fence
struct  Fiber
class  HighResolutionTimer
class  HostCallDepth
class  HostThreadContext
class  InstanceLock
class  Mutant
struct  OpenFileLimit
class  Profiler
class  RankedMutex
class  RankedSharedMutex
struct  SEHScope
struct  SEHThreadState
class  Semaphore
class  Socket
struct  SocketWait
class  Thread
struct  ThreadPriority
class  Timer
struct  TimerQueueWaitItem
struct  VectorRegister
class  WaitHandle

Typedefs

using LockOrderHandler = void (*)(LockRank held, LockRank acquiring)
using CrashAddressDescriber = u32 (*)(u64 host_address, std::span<char> out)
using SocketHandle = i64
using TLSHandle = u32

Enumerations

enum class  SymbolResolution : u8 { kLazy , kImmediate }
enum class  ARM64Register : u8 {
  kX0 , kX1 , kX2 , kX3 ,
  kX4 , kX5 , kX6 , kX7 ,
  kX8 , kX9 , kX10 , kX11 ,
  kX12 , kX13 , kX14 , kX15 ,
  kX16 , kX17 , kX18 , kX19 ,
  kX20 , kX21 , kX22 , kX23 ,
  kX24 , kX25 , kX26 , kX27 ,
  kX28 , kX29 , kX30 , kSP ,
  kPC , kPstate , kFpsr , kFpcr ,
  kV0 , kV1 , kV2 , kV3 ,
  kV4 , kV5 , kV6 , kV7 ,
  kV8 , kV9 , kV10 , kV11 ,
  kV12 , kV13 , kV14 , kV15 ,
  kV16 , kV17 , kV18 , kV19 ,
  kV20 , kV21 , kV22 , kV23 ,
  kV24 , kV25 , kV26 , kV27 ,
  kV28 , kV29 , kV30 , kV31
}
enum class  HostRegister
enum class  ARM64LoadStoreOp : u32 {
  kSTRBW = UINT32_C(0x00000000) , kSTRHW = UINT32_C(0x40000000) , kSTRW = UINT32_C(0x80000000) , kSTRX = UINT32_C(0xC0000000) ,
  kLDRBW = UINT32_C(0x00400000) , kLDRHW = UINT32_C(0x40400000) , kLDRW = UINT32_C(0x80400000) , kLDRX = UINT32_C(0xC0400000) ,
  kLDRSBX = UINT32_C(0x00800000) , kLDRSHX = UINT32_C(0x40800000) , kLDRSWX = UINT32_C(0x80800000) , kLDRSBW = UINT32_C(0x00C00000) ,
  kLDRSHW = UINT32_C(0x40C00000) , kSTRB = UINT32_C(0x04000000) , kSTRH = UINT32_C(0x44000000) , kSTRS = UINT32_C(0x84000000) ,
  kSTRD = UINT32_C(0xC4000000) , kSTRQ = UINT32_C(0x04800000) , kLDRB = UINT32_C(0x04400000) , kLDRH = UINT32_C(0x44400000) ,
  kLDRS = UINT32_C(0x84400000) , kLDRD = UINT32_C(0xC4400000) , kLDRQ = UINT32_C(0x04C00000) , kPRFM = UINT32_C(0xC0800000)
}
enum class  ARM64LoadStoreOffsetFixed : u32 { kUnscaledOffset = UINT32_C(0x38000000) , kPostIndex = UINT32_C(0x38000400) , kPreIndex = UINT32_C(0x38000C00) , kRegisterOffset = UINT32_C(0x38200800) }
enum class  LockRank : u8 { kLeaf = 0xFF }
enum class  CounterID : u8 { kFrameTimeUs , kFps }
enum class  CounterType : u8 { kAccumulator , kGauge }
enum class  SocketReady : u8 { kNone = 0 , kRead = 1 << 0 , kWrite = 1 << 1 , kExcept = 1 << 2 }
enum class  WaitResult : u8 {
  kSuccess , kUserCallback , kTimeout , kAbandoned ,
  kFailed
}
enum class  SleepResult : u8 { kSuccess , kAlerted }

Functions

bool IsARM64LoadPrefetchStore (u32 instruction, bool &is_store_out)
u64 SignalPC (void *signal_context)
void ReportFatalSignal (int signal_number, siginfo_t *info, void *signal_context)
void ForwardSignal (struct sigaction &original, int signal_number, siginfo_t *info, void *signal_context)
void DieWithDefaultDisposition (int signal_number)
std::filesystem::path GetExecutablePath ()
std::filesystem::path GetExecutableFolder ()
std::filesystem::path GetLibraryFolder ()
std::filesystem::path GetUserFolder ()
bool IsPackagedApp ()
std::filesystem::path GetUserConfigFolder (std::string_view app_name)
std::filesystem::path GetAppRoot (std::string_view app_name)
bool IsDirectoryWritable (const std::filesystem::path &dir)
std::string SanitizeFolderName (std::string_view name, std::string_view fallback="default")
Result< std::vector< u8 > > ReadHostFile (const std::filesystem::path &path, u64 offset=0, u64 length=0)
Result< void > WriteHostFile (const std::filesystem::path &path, std::span< const u8 > data)
Result< void > WriteHostFile (const std::filesystem::path &path, std::string_view text)
std::filesystem::path ResolveEntryCase (const std::filesystem::path &parent, std::string_view name)
bool OpenStorageFile (std::fstream &file, const std::filesystem::path &path)
u64 GetStorageFileSize (const std::filesystem::path &path)
size_t ReadStorageFile (std::fstream &file, void *data, size_t size)
void AppendStorageFile (std::fstream &file, const void *data, size_t size)
void ResetStorageFile (std::fstream &file, const std::filesystem::path &path, u64 length)
LockOrderHandler SetLockOrderHandler (LockOrderHandler handler)
void PushLockRank (LockRank rank)
void PopLockRank (LockRank rank)
Result< CounterID > RegisterCounter (const char *name, CounterType type=CounterType::kAccumulator)
std::optional< CounterID > FindCounter (std::string_view name)
const char * GetCounterName (CounterID id)
void SetCounter (CounterID id, i64 value)
void IncrementCounter (CounterID id, i64 delta=1)
i64 GetCounter (CounterID id)
void ResetFrameCounters ()
i64 GetSnapshotCounter (CounterID id)
void InitCounters ()
void SetCSVLogPath (const std::string &path)
void WriteCSVFrame ()
void CloseCSV ()
Result< void > Relaunch (std::span< const std::string > args)
Result< void > Relaunch (const std::filesystem::path &exe, std::span< const std::string > args, const std::filesystem::path &working_directory={})
bool CanRelaunch ()
Result< OpenFileLimit > RaiseOpenFileLimit ()
std::string DescribeResourceUse ()
bool IsTerminal (FILE *stream)
bool EnableANSIEscapes (FILE *stream)
void SetUTF8OutputCodePage ()
bool IsDebuggerAttached ()
void Break ()
std::optional< std::string > GetEnvironmentValue (std::string_view name)
bool SetEnvironmentValue (std::string_view name, std::string_view value)
bool UnsetEnvironmentValue (std::string_view name)
std::vector< std::pair< std::string, std::string > > EnumerateEnvironment ()
Result< void > InstallCrashReporter (const CrashReporterOptions &options)
void UninstallCrashReporter ()
void SetCrashAddressDescriber (CrashAddressDescriber describer)
void PrepareThreadForCrash ()
int SocketClose (SocketHandle handle)
int SocketIOCTL (SocketHandle handle, u32 cmd, u8 *arg)
int SocketPrepare (SocketHandle handle, WaitHandle *event)
bool IsSocketWouldBlock ()
u32 GetSocketError ()
int PollSockets (std::span< const SocketWait > sockets, std::span< SocketReady > ready)
WaitResult WaitSockets (std::span< const SocketWait > sockets, bool alertable, std::chrono::milliseconds timeout)
WaitResult Wait (WaitHandle *wait_handle, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
WaitResult SignalAndWait (WaitHandle *wait_handle_to_signal, WaitHandle *wait_handle_to_wait_on, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
std::pair< WaitResult, size_t > WaitMultiple (WaitHandle *wait_handles[], size_t wait_handle_count, bool wait_all, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
WaitResult WaitAll (WaitHandle *wait_handles[], size_t wait_handle_count, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
WaitResult WaitAll (std::vector< WaitHandle * > wait_handles, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
std::pair< WaitResult, size_t > WaitAny (WaitHandle *wait_handles[], size_t wait_handle_count, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
std::pair< WaitResult, size_t > WaitAny (std::vector< WaitHandle * > wait_handles, bool is_alertable, std::chrono::milliseconds timeout=std::chrono::milliseconds::max())
u32 GetLogicalProcessorCount ()
void WidenProcessAffinity ()
u32 GetCallerSystemThreadID ()
u32 GetCallerThreadID ()
void SetCallerThreadID (u32 id)
void SetCurrentThreadName (const std::string_view name)
void SetCurrentThreadPriority (i32 priority)
void MaybeYield ()
void SyncMemory ()
void SleepFor (std::chrono::microseconds duration)
template<typename Rep, typename Period>
void SleepFor (std::chrono::duration< Rep, Period > duration)
std::chrono::milliseconds GetCurrentThreadCPUTime ()
SleepResult AlertableSleep (std::chrono::microseconds duration)
template<typename Rep, typename Period>
SleepResult AlertableSleep (std::chrono::duration< Rep, Period > duration)
TLSHandle AllocateTLSHandle ()
bool FreeTLSHandle (TLSHandle handle)
uintptr_t GetTLSValue (TLSHandle handle)
bool SetTLSValue (TLSHandle handle, uintptr_t value)
template<typename F>
std::jthread Spawn (std::string_view name, F &&fn)
std::weak_ptr< TimerQueueWaitItem > QueueTimerOnce (std::function< void(void *)> callback, void *userdata, TimerQueueWaitItem::clock::time_point due)
std::weak_ptr< TimerQueueWaitItem > QueueTimerRecurring (std::function< void(void *)> callback, void *userdata, TimerQueueWaitItem::clock::time_point due, TimerQueueWaitItem::clock::duration interval)
REX_PPC_API SEHThreadState & GetSEHThreadState ()
REX_PPC_API int SEHFilter (u32 code, void *exception_pointers)
REX_PPC_API void SEHRethrow ()
REX_PPC_API void SEHInitialize ()
void SEHEnter (SEHScope &scope)
void SEHLeave (SEHScope &scope)

Variables

constexpr bool kWindows = REX_PLATFORM_WIN32
constexpr bool kLinux = REX_PLATFORM_LINUX
constexpr bool kMac = REX_PLATFORM_MAC
constexpr bool kPosix = kLinux || kMac
constexpr char kPathSeparator = '/'
constexpr u32 kARM64LoadLiteralFMask = UINT32_C(0x3B000000)
constexpr u32 kARM64LoadLiteralFixed = UINT32_C(0x18000000)
constexpr u32 kARM64LoadStoreAnyFMask = UINT32_C(0x0A000000)
constexpr u32 kARM64LoadStoreAnyFixed = UINT32_C(0x08000000)
constexpr u32 kARM64LoadStorePairAnyFMask = UINT32_C(0x3A000000)
constexpr u32 kARM64LoadStorePairAnyFixed = UINT32_C(0x28000000)
constexpr u32 kARM64LoadStorePairLoadBit = UINT32_C(1) << 22
constexpr u32 kARM64LoadStoreMask = UINT32_C(0xC4C00000)
constexpr u32 kARM64LoadStoreOffsetFMask = UINT32_C(0x3B200C00)
constexpr u32 kARM64LoadStoreUnsignedOffsetFMask = UINT32_C(0x3B000000)
constexpr u32 kARM64LoadStoreUnsignedOffsetFixed = UINT32_C(0x39000000)
constexpr size_t kMaxCounters = 64
constexpr SocketHandle kInvalidSocket = -1
constexpr TLSHandle kInvalidTLSHandle = UINT_MAX

Detailed Description

Host threads, events, timers and other platform primitives.

Typedef Documentation

◆ CrashAddressDescriber

using rex::platform::CrashAddressDescriber = u32 (*)(u64 host_address, std::span<char> out)

Writes a host fault address as title terms, such as a guest address or a register. Runs in a signal handler, so it must not allocate or lock.

Parameters
host_addressThe fault address, or 0 when there is none.
outBuffer for the text.
Returns
The text length, 0 for none.

◆ LockOrderHandler

using rex::platform::LockOrderHandler = void (*)(LockRank held, LockRank acquiring)

Receives an order violation in a debug build.

Parameters
heldThe rank on top of the held stack.
acquiringThe rank being taken.

◆ SocketHandle

Native socket handle widened to 64 bits, a SOCKET on Windows or a file descriptor on POSIX.

Enumeration Type Documentation

◆ ARM64LoadStoreOffsetFixed

Fixed bits of each load and store offset addressing mode.

Enumerator
kUnscaledOffset 

Unscaled immediate offset.

kPostIndex 

Post indexed immediate.

kPreIndex 

Pre indexed immediate.

◆ ARM64LoadStoreOp

enum class rex::platform::ARM64LoadStoreOp : u32
strong

Single register load and store operations under kARM64LoadStoreMask.

Enumerator
kSTRBW 

Store byte from W.

kSTRHW 

Store halfword from W.

kSTRW 

Store word from W.

kSTRX 

Store doubleword from X.

kLDRBW 

Load byte into W.

kLDRHW 

Load halfword into W.

kLDRW 

Load word into W.

kLDRX 

Load doubleword into X.

kLDRSBX 

Load signed byte into X.

kLDRSHX 

Load signed halfword into X.

kLDRSWX 

Load signed word into X.

kLDRSBW 

Load signed byte into W.

kLDRSHW 

Load signed halfword into W.

kSTRB 

Store 8 bit SIMD register.

kSTRH 

Store 16 bit SIMD register.

kSTRS 

Store 32 bit SIMD register.

kSTRD 

Store 64 bit SIMD register.

kSTRQ 

Store 128 bit SIMD register.

kLDRB 

Load 8 bit SIMD register.

kLDRH 

Load 16 bit SIMD register.

kLDRS 

Load 32 bit SIMD register.

kLDRD 

Load 64 bit SIMD register.

kLDRQ 

Load 128 bit SIMD register.

kPRFM 

Prefetch.

◆ ARM64Register

enum class rex::platform::ARM64Register : u8
strong

ARM64 registers, indexed as in the instruction encoding.

Enumerator
kX29 

Frame pointer.

kX30 

Link register.

kV0 

All 128 bits, named Q0.

◆ CounterID

enum class rex::platform::CounterID : u8
strong

Performance counter slots. A module registers its own counters with RegisterCounter.

◆ CounterType

enum class rex::platform::CounterType : u8
strong

How ResetFrameCounters treats a counter.

Enumerator
kAccumulator 

Zeroed each frame after its value is snapshotted.

kGauge 

Keeps its live value across frames.

◆ HostRegister

enum class rex::platform::HostRegister
strong

Register enumeration of the host architecture, empty on other architectures.

◆ LockRank

enum class rex::platform::LockRank : u8
strong

A lock may be taken only when its rank is greater than every rank the thread holds. Modules define lower ranks as values of this type, for example LockRank kObjectTable{3};.

Enumerator
kLeaf 

The highest rank. Nothing may be taken while it is held.

◆ SleepResult

enum class rex::platform::SleepResult : u8
strong

Outcome of AlertableSleep.

Enumerator
kAlerted 

A user callback ran and ended the sleep early.

◆ SocketReady

enum class rex::platform::SocketReady : u8
strong
Enumerator
kRead 

Data, a connection or a peer close to read.

kWrite 

Space to send, or a finished connect.

kExcept 

Out of band data, or a failed connect.

◆ SymbolResolution

enum class rex::platform::SymbolResolution : u8
strong
Enumerator
kLazy 

Resolve on first use. RTLD_LAZY on POSIX.

kImmediate 

Resolve all at load. RTLD_NOW on POSIX, the Windows behavior.

◆ WaitResult

enum class rex::platform::WaitResult : u8
strong
Enumerator
kSuccess 

The object is signaled. WaitAny also reports its index.

kUserCallback 

A user callback queued to the thread ended an alertable wait.

kTimeout 

The timeout elapsed and the object is not signaled.

kAbandoned 

A mutant owner exited without a release. The caller owns it now.

Function Documentation

◆ AlertableSleep() [1/2]

template<typename Rep, typename Period>
SleepResult rex::platform::AlertableSleep ( std::chrono::duration< Rep, Period > duration)

Sleeps the calling thread in an alertable state.

Returns
kAlerted when a user callback ran, kSuccess otherwise.

◆ AlertableSleep() [2/2]

SleepResult rex::platform::AlertableSleep ( std::chrono::microseconds duration)

Sleeps the calling thread in an alertable state. A queued user callback ends the sleep early.

Returns
kAlerted when a user callback ran, kSuccess otherwise.

◆ Break()

void rex::platform::Break ( )

Breaks into the attached debugger. Without one, POSIX raises SIGTRAP.

◆ CanRelaunch()

bool rex::platform::CanRelaunch ( )

Reports whether the platform allows starting a new process.

◆ DescribeResourceUse()

std::string rex::platform::DescribeResourceUse ( )
nodiscard

Reports the host resources this process uses, for logging when something runs out.

Returns
The description of descriptors, memory maps or handles the host reports.

◆ DieWithDefaultDisposition()

void rex::platform::DieWithDefaultDisposition ( int signal_number)

Ends the process through the default disposition of a signal.

◆ EnableANSIEscapes()

bool rex::platform::EnableANSIEscapes ( FILE * stream)

Turns on ANSI escape sequence handling for a stream. Does nothing on POSIX.

Parameters
streamStream to configure, may be null.
Returns
True when escapes are handled on return, false for null or a console mode failure.

◆ EnumerateEnvironment()

std::vector< std::pair< std::string, std::string > > rex::platform::EnumerateEnvironment ( )

Lists every environment variable of the process.

Returns
Name and value pairs in UTF-8.

◆ FindCounter()

std::optional< CounterID > rex::platform::FindCounter ( std::string_view name)

Finds a registered counter.

Returns
The counter, or empty when no counter has the name.

◆ ForwardSignal()

void rex::platform::ForwardSignal ( struct sigaction & original,
int signal_number,
siginfo_t * info,
void * signal_context )

Passes a signal no SDK handler claimed to the action it replaced. A default or ignored action, or the same fault 64 times in a row, ends in a report and the default disposition.

Parameters
originalThe replaced action. Cleared to the default when it carries SA_RESETHAND.

◆ GetAppRoot()

std::filesystem::path rex::platform::GetAppRoot ( std::string_view app_name)
nodiscard

Returns the folder an application keeps its writable files in, such as logs. Creates nothing. It is the executable folder, or GetUserConfigFolder when IsPackagedApp is true or the executable folder is not writable. It is empty when neither folder is usable.

Parameters
app_nameApplication name used for the fallback folder.

◆ GetCallerSystemThreadID()

u32 rex::platform::GetCallerSystemThreadID ( )

Returns the OS thread ID of the calling thread. For logs and diagnostics only.

◆ GetCallerThreadID()

u32 rex::platform::GetCallerThreadID ( )

Equals GetCallerSystemThreadID() until SetCallerThreadID overrides it. Guest threads set it to their guest thread handle.

◆ GetCounter()

i64 rex::platform::GetCounter ( CounterID id)

Returns the live value of a counter.

◆ GetCounterName()

const char * rex::platform::GetCounterName ( CounterID id)
Returns
The snake case name, or "unknown".

◆ GetCurrentThreadCPUTime()

std::chrono::milliseconds rex::platform::GetCurrentThreadCPUTime ( )

Returns the CPU time the calling thread has used. It is kernel plus user time.

◆ GetEnvironmentValue()

std::optional< std::string > rex::platform::GetEnvironmentValue ( std::string_view name)

Reads an environment variable.

Parameters
nameVariable name, UTF-8.
Returns
The UTF-8 value, or std::nullopt when not set. An empty value is not std::nullopt.

◆ GetExecutableFolder()

std::filesystem::path rex::platform::GetExecutableFolder ( )
Returns
The parent of GetExecutablePath.

◆ GetExecutablePath()

std::filesystem::path rex::platform::GetExecutablePath ( )
Returns
The absolute path, or empty when the host does not report it.

◆ GetLibraryFolder()

std::filesystem::path rex::platform::GetLibraryFolder ( )

Returns the folder the rexbase shared library was loaded from, which is where the SDK keeps its libraries and modules. It is the lib folder of an installed SDK on Linux and macOS, and the bin folder on Windows.

Returns
The absolute folder, or GetExecutableFolder when the host does not report it.

◆ GetSEHThreadState()

REX_PPC_API SEHThreadState & rex::platform::GetSEHThreadState ( )

Returns the SEH state of the calling thread.

◆ GetSnapshotCounter()

i64 rex::platform::GetSnapshotCounter ( CounterID id)

Returns the value of a counter from the last snapshot, which stays stable between frames.

◆ GetSocketError()

u32 rex::platform::GetSocketError ( )

Returns the last socket error of the calling thread. WSAEINVAL when the host error has no WSA equivalent.

◆ GetStorageFileSize()

u64 rex::platform::GetStorageFileSize ( const std::filesystem::path & path)
inline
Returns
Size in bytes, 0 when the size cannot be queried.

◆ GetTLSValue()

uintptr_t rex::platform::GetTLSValue ( TLSHandle handle)

Reads the value the calling thread holds in a slot.

Returns
Stored value, 0 when never set.

◆ GetUserConfigFolder()

std::filesystem::path rex::platform::GetUserConfigFolder ( std::string_view app_name)
nodiscard

Returns the host folder for per user configuration of an application. It is under roaming application data on Windows, Application Support on macOS, or XDG_CONFIG_HOME elsewhere with .config as the fallback. It is empty when no folder is found.

Parameters
app_nameThe application name, passed through SanitizeFolderName.

◆ GetUserFolder()

std::filesystem::path rex::platform::GetUserFolder ( )
Returns
Documents on Windows, the XDG data home on Linux and macOS.

◆ IncrementCounter()

void rex::platform::IncrementCounter ( CounterID id,
i64 delta = 1 )

Atomically adds to the live value of a counter.

Parameters
deltaThe signed amount to add.

◆ InitCounters()

void rex::platform::InitCounters ( )

Zeroes every live and snapshot value.

◆ InstallCrashReporter()

Result< void > rex::platform::InstallCrashReporter ( const CrashReporterOptions & options)
nodiscard

Installs the crash reporter, or replaces its options when installed. Prepares the calling thread.

Returns
Ok, or a Platform error when a handler cannot be installed.

◆ IsARM64LoadPrefetchStore()

bool rex::platform::IsARM64LoadPrefetchStore ( u32 instruction,
bool & is_store_out )

Classifies an ARM64 instruction as a load, prefetch or store.

Parameters
instructionThe instruction word.
is_store_outTrue for a store. Unchanged for a PC relative literal load or a false return.
Returns
True when the instruction is a load, prefetch or store.

◆ IsDebuggerAttached()

bool rex::platform::IsDebuggerAttached ( )

Reports whether a debugger is attached. The check is expensive.

◆ IsDirectoryWritable()

bool rex::platform::IsDirectoryWritable ( const std::filesystem::path & dir)
nodiscard

Reports whether a file can be created in a folder.

Returns
True when a temporary file could be created there.

◆ IsPackagedApp()

bool rex::platform::IsPackagedApp ( )
nodiscard

Reports whether the application runs from a read only package.

Returns
True for an AppImage or a macOS app bundle, false on Windows and for a loose build.

◆ IsSocketWouldBlock()

bool rex::platform::IsSocketWouldBlock ( )

Reports whether the last socket call of the calling thread failed only because it would block.

Returns
True when the error is a would block error or a connect in progress.

◆ IsTerminal()

bool rex::platform::IsTerminal ( FILE * stream)

Reports whether a stream is attached to a terminal.

Parameters
streamStream to test, may be null.

◆ MaybeYield()

void rex::platform::MaybeYield ( )

Yields the calling thread to the scheduler and issues a full memory barrier.

◆ OpenStorageFile()

bool rex::platform::OpenStorageFile ( std::fstream & file,
const std::filesystem::path & path )

Opens a storage file for reading and writing, creating it when missing.

◆ PollSockets()

int rex::platform::PollSockets ( std::span< const SocketWait > sockets,
std::span< SocketReady > ready )

Reports the readiness of each socket without waiting.

Parameters
readyReceives, for each socket, the requested readiness that is currently set.
Returns
The count of ready sockets, or -1 with GetSocketError set.

◆ PrepareThreadForCrash()

void rex::platform::PrepareThreadForCrash ( )

Reserves the stack a report needs on the calling thread, so stack overflow reports work.

◆ PushLockRank()

void rex::platform::PushLockRank ( LockRank rank)

Pushes the rank of a lock being taken and reports an order violation in a debug build.

◆ QueueTimerOnce()

std::weak_ptr< TimerQueueWaitItem > rex::platform::QueueTimerOnce ( std::function< void(void *)> callback,
void * userdata,
TimerQueueWaitItem::clock::time_point due )

Queues a callback that runs once.

Parameters
callbackFunction called on the dispatch thread.
Returns
Handle to the queued item, used to Disarm it.

◆ QueueTimerRecurring()

std::weak_ptr< TimerQueueWaitItem > rex::platform::QueueTimerRecurring ( std::function< void(void *)> callback,
void * userdata,
TimerQueueWaitItem::clock::time_point due,
TimerQueueWaitItem::clock::duration interval )

Queues a callback that runs at due and then after each interval.

Parameters
callbackFunction called on the dispatch thread.
intervalRepeat interval, 0 for a single run.
Returns
Handle to the queued item, used to Disarm it.

◆ RaiseOpenFileLimit()

Result< OpenFileLimit > rex::platform::RaiseOpenFileLimit ( )
nodiscard

Raises the soft open file limit to the hard limit, or to 10240 when the hard limit is unlimited or refused. Windows has no such limit, gives zeros and changes nothing.

Returns
The limits, or ErrorCategory::kPlatform with the OS error.

◆ ReadHostFile()

Result< std::vector< u8 > > rex::platform::ReadHostFile ( const std::filesystem::path & path,
u64 offset = 0,
u64 length = 0 )
nodiscard

Reads a host file into memory.

Parameters
offsetThe first byte to read. An offset at the end gives an empty vector.
lengthThe byte count, 0 for all. A length past the end is a short read.
Returns
The bytes, or an IO error when unreadable or the offset is past the end.

◆ ReadStorageFile()

size_t rex::platform::ReadStorageFile ( std::fstream & file,
void * data,
size_t size )

Reads bytes at the current read position.

Returns
Number of bytes read.

◆ RegisterCounter()

Result< CounterID > rex::platform::RegisterCounter ( const char * name,
CounterType type = CounterType::kAccumulator )
nodiscard

Registers a counter, or finds the one registered under the name. CSV columns follow registration order.

Parameters
nameThe snake case name, shorter than 48 characters.
typeHow ResetFrameCounters treats the counter. A repeated name keeps its first type.
Returns
The counter, or an error when all kMaxCounters slots are used and the name is new.

◆ Relaunch() [1/2]

Result< void > rex::platform::Relaunch ( const std::filesystem::path & exe,
std::span< const std::string > args,
const std::filesystem::path & working_directory = {} )
nodiscard

Starts an executable as a new process and returns without waiting.

Parameters
argsArguments after the executable.
working_directoryThe start directory of the new process, the current one when empty.
Returns
Ok, or ErrorCategory::kPlatform with the OS error.

◆ Relaunch() [2/2]

Result< void > rex::platform::Relaunch ( std::span< const std::string > args)
nodiscard

Starts this executable again as a new process and returns without waiting.

Returns
Ok, or ErrorCategory::kPlatform with the OS error.

◆ ReportFatalSignal()

void rex::platform::ReportFatalSignal ( int signal_number,
siginfo_t * info,
void * signal_context )

Writes a report for a fatal signal when the reporter is installed and no report has run.

Parameters
infoThe signal info, or null.
signal_contextThe ucontext of the fault, or null.

◆ ResetFrameCounters()

void rex::platform::ResetFrameCounters ( )

Copies every live value into the snapshot and zeroes the accumulators. Gauges keep theirs.

◆ ResetStorageFile()

void rex::platform::ResetStorageFile ( std::fstream & file,
const std::filesystem::path & path,
u64 length )

Truncates a storage file and reopens it positioned at the end.

Parameters
fileStorage stream, closed and reopened in place.

◆ ResolveEntryCase()

std::filesystem::path rex::platform::ResolveEntryCase ( const std::filesystem::path & parent,
std::string_view name )
nodiscard

Joins a name onto a folder, keeping the case of an existing entry that matches ignoring case.

Parameters
nameThe entry name, a single path component.
Returns
The existing entry path, preferring an exact match, or parent joined with name.

◆ SanitizeFolderName()

std::string rex::platform::SanitizeFolderName ( std::string_view name,
std::string_view fallback = "default" )
nodiscard

Turns a name into a folder name that is safe on every host. Removes control characters and reserved punctuation, trims spaces and dots, and appends an underscore to Windows device names such as CON or COM1.

Parameters
fallbackThe result when nothing is left of the name.
Returns
The safe name, or the fallback.

◆ SEHEnter()

void rex::platform::SEHEnter ( SEHScope & scope)
inline

Links a scope into the chain of the calling thread.

Parameters
scopeThe scope REX_SEH_TRY opens.

◆ SEHFilter()

REX_PPC_API int rex::platform::SEHFilter ( u32 code,
void * exception_pointers )

Filter for the Windows __except clause that captures the exception. Always 0 on POSIX.

Returns
Nonzero to run the handler, 0 to continue the search.

◆ SEHInitialize()

REX_PPC_API void rex::platform::SEHInitialize ( )

Installs the SIGSEGV, SIGBUS, SIGFPE and SIGILL handlers once on POSIX. No effect on Windows.

◆ SEHLeave()

void rex::platform::SEHLeave ( SEHScope & scope)
inline

Unlinks a scope when it is still the innermost one.

Parameters
scopeThe scope REX_SEH_TRY opened.

◆ SEHRethrow()

REX_PPC_API void rex::platform::SEHRethrow ( )

Raises the captured exception again. On POSIX it resumes the next open scope or ends the process.

◆ SetCallerThreadID()

void rex::platform::SetCallerThreadID ( u32 id)

Overrides the ID GetCallerThreadID returns on the calling thread.

◆ SetCrashAddressDescriber()

void rex::platform::SetCrashAddressDescriber ( CrashAddressDescriber describer)

Sets the function the report calls to write the fault address as title terms.

Parameters
describerThe describer, or null for none.

◆ SetCSVLogPath()

void rex::platform::SetCSVLogPath ( const std::string & path)

Closes any open CSV log and opens a new one with a header row of counter names.

Parameters
pathThe CSV file path. Empty closes logging.

◆ SetCurrentThreadName()

void rex::platform::SetCurrentThreadName ( const std::string_view name)

Names the calling thread for debuggers and OS tools.

Parameters
nameThread name, UTF-8.

◆ SetCurrentThreadPriority()

void rex::platform::SetCurrentThreadPriority ( i32 priority)

Sets the priority of the calling thread, with the same mapping as Thread::SetPriority. A failure is logged and leaves the priority unchanged.

Parameters
priorityUsually a ThreadPriority value.

◆ SetEnvironmentValue()

bool rex::platform::SetEnvironmentValue ( std::string_view name,
std::string_view value )

Sets an environment variable, replacing any existing value.

Parameters
nameVariable name, UTF-8.
valueNew value, UTF-8.

◆ SetLockOrderHandler()

LockOrderHandler rex::platform::SetLockOrderHandler ( LockOrderHandler handler)

Replaces the violation handler. The default handler asserts.

Parameters
handlerThe new handler, or null to restore the default.
Returns
The previous handler.

◆ SetTLSValue()

bool rex::platform::SetTLSValue ( TLSHandle handle,
uintptr_t value )

Writes the value the calling thread holds in a slot.

◆ SetUTF8OutputCodePage()

void rex::platform::SetUTF8OutputCodePage ( )

Switches the process console output code page to UTF-8. Does nothing on POSIX.

◆ SignalAndWait()

WaitResult rex::platform::SignalAndWait ( WaitHandle * wait_handle_to_signal,
WaitHandle * wait_handle_to_wait_on,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )

Signals an object and waits on another as one operation. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.

◆ SignalPC()

u64 rex::platform::SignalPC ( void * signal_context)

Returns the instruction pointer a signal interrupted.

Parameters
signal_contextThe ucontext_t the signal handler receives.

◆ SleepFor()

void rex::platform::SleepFor ( std::chrono::microseconds duration)

Sleeps the calling thread for at least the duration. A duration of 0 yields.

◆ SocketClose()

int rex::platform::SocketClose ( SocketHandle handle)

Closes a socket.

Returns
0 on success, or the platform error return value.

◆ SocketIOCTL()

int rex::platform::SocketIOCTL ( SocketHandle handle,
u32 cmd,
u8 * arg )

Runs an ioctl request on a socket.

Parameters
argThe argument buffer, read and written in place.
Returns
0 on success, or the platform error return value.

◆ SocketPrepare()

int rex::platform::SocketPrepare ( SocketHandle handle,
WaitHandle * event )

Makes a socket nonblocking and binds an event to its waits. On Windows the socket sets the event when it becomes ready.

Parameters
eventA manual reset event whose Set ends a WaitSockets on the socket.
Returns
0 on success, or the platform error return value.

◆ Spawn()

template<typename F>
std::jthread rex::platform::Spawn ( std::string_view name,
F && fn )

Starts a host thread the SDK tracks until it exits.

Template Parameters
FCallable taking a std::stop_token.
Parameters
nameThread name shown in debuggers and logs.
Returns
The running thread. Its destructor requests stop and joins.

◆ SyncMemory()

void rex::platform::SyncMemory ( )

Issues a full memory barrier.

◆ UninstallCrashReporter()

void rex::platform::UninstallCrashReporter ( )

Removes the crash reporter and restores the handlers it replaced.

◆ UnsetEnvironmentValue()

bool rex::platform::UnsetEnvironmentValue ( std::string_view name)

Removes an environment variable.

Parameters
nameVariable name, UTF-8.
Returns
True when the OS call succeeds.

◆ Wait()

WaitResult rex::platform::Wait ( WaitHandle * wait_handle,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )

Waits on one object. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.

◆ WaitAll() [1/2]

WaitResult rex::platform::WaitAll ( std::vector< WaitHandle * > wait_handles,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )
inline

Waits until every object is signaled. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.

◆ WaitAll() [2/2]

WaitResult rex::platform::WaitAll ( WaitHandle * wait_handles[],
size_t wait_handle_count,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )
inline

Waits until every object is signaled. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.

◆ WaitAny() [1/2]

std::pair< WaitResult, size_t > rex::platform::WaitAny ( std::vector< WaitHandle * > wait_handles,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )
inline

Waits until any object is signaled. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.
Returns
Why the wait ended and the index of the object that satisfied or abandoned it.

◆ WaitAny() [2/2]

std::pair< WaitResult, size_t > rex::platform::WaitAny ( WaitHandle * wait_handles[],
size_t wait_handle_count,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )
inline

Waits until any object is signaled. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.
Returns
Why the wait ended and the index of the object that satisfied or abandoned it.

◆ WaitMultiple()

std::pair< WaitResult, size_t > rex::platform::WaitMultiple ( WaitHandle * wait_handles[],
size_t wait_handle_count,
bool wait_all,
bool is_alertable,
std::chrono::milliseconds timeout = std::chrono::milliseconds::max() )

Waits on several objects. A timeout of 0 polls and max() waits forever.

Parameters
is_alertableTrue to let a queued user callback end the wait.
Returns
Why the wait ended and, for kSuccess or kAbandoned, the index of the object.

◆ WaitSockets()

WaitResult rex::platform::WaitSockets ( std::span< const SocketWait > sockets,
bool alertable,
std::chrono::milliseconds timeout )

Waits until a socket may be ready.

Parameters
alertableTrue when a queued user callback ends the wait.
timeoutThe longest wait, milliseconds::max() for no limit.
Returns
kSuccess when a socket may be ready or its event is set, kUserCallback, kTimeout or kFailed.

◆ WidenProcessAffinity()

void rex::platform::WidenProcessAffinity ( )

Widens the process affinity to every processor. Does nothing on POSIX.

◆ WriteCSVFrame()

void rex::platform::WriteCSVFrame ( )

Appends a row of snapshot values to the CSV log. The file is flushed every 60 rows.

◆ WriteHostFile() [1/2]

Result< void > rex::platform::WriteHostFile ( const std::filesystem::path & path,
std::span< const u8 > data )
nodiscard

Replaces a host file atomically through a temporary file and a rename. Creates missing parent folders.

Returns
An IO error when a folder, the temporary file or the rename fails.

◆ WriteHostFile() [2/2]

Result< void > rex::platform::WriteHostFile ( const std::filesystem::path & path,
std::string_view text )
nodiscard

Replaces a host file with text, as the span form does.

Variable Documentation

◆ kARM64LoadLiteralFMask

u32 rex::platform::kARM64LoadLiteralFMask = UINT32_C(0x3B000000)
constexpr

Mask for PC relative literal loads, which include PRFM_lit.

◆ kARM64LoadStoreMask

u32 rex::platform::kARM64LoadStoreMask = UINT32_C(0xC4C00000)
constexpr

Selects the ARM64LoadStoreOp bits of a load or store.

◆ kARM64LoadStoreOffsetFMask

u32 rex::platform::kARM64LoadStoreOffsetFMask = UINT32_C(0x3B200C00)
constexpr

Mask for the load and store offset addressing modes.

◆ kARM64LoadStorePairLoadBit

u32 rex::platform::kARM64LoadStorePairLoadBit = UINT32_C(1) << 22
constexpr

Bit set on the load form of a load or store pair.

◆ kARM64LoadStoreUnsignedOffsetFMask

u32 rex::platform::kARM64LoadStoreUnsignedOffsetFMask = UINT32_C(0x3B000000)
constexpr

Mask for the unsigned immediate offset addressing mode.

◆ kMaxCounters

size_t rex::platform::kMaxCounters = 64
inlineconstexpr

The number of counter slots, registered counters included.