Overview / Foundation

platform

System introspection: modules, processes, threads, regions and another process's memory, exports, image integrity, privileges, system and CPU facts, disks, network interfaces and machine fingerprinting. Every piece is checked against an independent oracle.

Always compiled: part of the core build.Include #include <ethereal/cpp/platform/cpu_facts.hpp>C layer

cpu_facts.hpp

#include <ethereal/cpp/platform/cpu_facts.hpp>

Processor facts.

The library already has Cpu::ESimdLevel, a ladder (scalar, SSE2, SSSE3, SSE4.1, SSE4.2, AVX2, NEON) that picks between implementations of one kernel, where each step contains the previous one. Spec 05 asks for something else, and real processors are not a ladder: some have AES-NI without AVX2 and the other way around, AVX-512 comes in variants that do not always go together, and the SHA extensions are independent of everything else. So here the features are a bit map, and the ladder stays where it is. Where the two overlap they must agree, and the suite checks it: if this map says AVX2, the ladder cannot stop at SSE4.2. They are two independent detectors reading the same processor.

Having the instruction is not enough, the operating system must save the state. AVX and AVX-512 add registers, and if the system does not save them on a context switch, using them corrupts the program intermittently, depending on load. CPUID answers about the silicon, XGETBV answers about the system, and a usable bit is set only when both agree.

The spec asks that results stable for the process lifetime be computed once and cached. CpuFacts computes on the first call and returns the same reference afterwards. The suite checks that the address is the same.

const

ETL_CPU_SSE

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SSE = 1ull << 0;

x86 instruction set extensions, one bit each.

const

ETL_CPU_SSE2

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SSE2 = 1ull << 1;
const

ETL_CPU_SSE3

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SSE3 = 1ull << 2;
const

ETL_CPU_SSSE3

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SSSE3 = 1ull << 3;
const

ETL_CPU_SSE41

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SSE41 = 1ull << 4;
const

ETL_CPU_SSE42

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SSE42 = 1ull << 5;
const

ETL_CPU_POPCNT

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_POPCNT = 1ull << 6;
const

ETL_CPU_AVX

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX = 1ull << 7;
const

ETL_CPU_AVX2

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX2 = 1ull << 8;
const

ETL_CPU_FMA

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_FMA = 1ull << 9;
const

ETL_CPU_BMI1

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_BMI1 = 1ull << 10;
const

ETL_CPU_BMI2

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_BMI2 = 1ull << 11;
const

ETL_CPU_AES

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AES = 1ull << 12;
const

ETL_CPU_PCLMUL

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_PCLMUL = 1ull << 13;
const

ETL_CPU_SHA

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_SHA = 1ull << 14;
const

ETL_CPU_RDRAND

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_RDRAND = 1ull << 15;
const

ETL_CPU_RDSEED

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_RDSEED = 1ull << 16;
const

ETL_CPU_F16C

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_F16C = 1ull << 17;
const

ETL_CPU_MOVBE

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_MOVBE = 1ull << 18;
const

ETL_CPU_LZCNT

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_LZCNT = 1ull << 19;
const

ETL_CPU_AVX512F

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512F = 1ull << 20;

The AVX-512 family.

const

ETL_CPU_AVX512DQ

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512DQ = 1ull << 21;
const

ETL_CPU_AVX512BW

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512BW = 1ull << 22;
const

ETL_CPU_AVX512VL

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512VL = 1ull << 23;
const

ETL_CPU_AVX512CD

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512CD = 1ull << 24;
const

ETL_CPU_AVX512VNNI

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512VNNI = 1ull << 25;
const

ETL_CPU_AVX512VBMI

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512VBMI = 1ull << 26;
const

ETL_CPU_AVX512BITALG

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512BITALG = 1ull << 27;
const

ETL_CPU_AVX512VPOPCNTDQ

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_AVX512VPOPCNTDQ = 1ull << 28;
const

ETL_CPU_NEON

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_NEON = 1ull << 32;

ARM extensions. Never set on the same processor as the ones above.

const

ETL_CPU_ARM_CRC32

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_ARM_CRC32 = 1ull << 33;
const

ETL_CPU_ARM_AES

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_ARM_AES = 1ull << 34;
const

ETL_CPU_ARM_SHA1

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_ARM_SHA1 = 1ull << 35;
const

ETL_CPU_ARM_SHA2

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_ARM_SHA2 = 1ull << 36;
const

ETL_CPU_ARM_SVE

Ethereal::Platform#
constexpr ETL_UINT64 ETL_CPU_ARM_SVE = 1ull << 37;
struct

SCpuFacts

Ethereal::Platform#
C++
struct   SCpuFacts   final
{
    /// @brief  'sizeof( SCpuFacts )'.
    ETL_UINT32        iStructSize = sizeof( SCpuFacts );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  What can be used: what the silicon has and the system supports.
    ///
    /// @details  This is the field that decides whether an instruction can be
    ///            emitted. It is uFeaturesRaw filtered by CpuFeaturesUsableWith.
    ETL_UINT64        uFeatures = 0;

    /// @brief  What the silicon declares, without the system state.
    ///
    /// @details  Do not use it to pick a code path. It is for reports and
    ///            diagnostics: "the machine has AVX-512, the system does not support
    ///            it" is a useful sentence in a support message, and it cannot be
    ///            formed from one field.
    ETL_UINT64        uFeaturesRaw = 0;

    /// @brief  What the system saves on a context switch (the XCR0 register).
    ///
    /// @details  Zero when the machine has no XGETBV, which means the same: without
    ///            it there is no wide state to save. Always zero on ARM, and
    ///            meaningless there.
    ETL_UINT64        uXcr0 = 0;

    /// @brief  Vendor, as the silicon declares it. E.g. "GenuineIntel".
    ETL_CHAR        aVendor[ 16 ] = {};

    /// @brief  Brand name. Empty when the processor does not publish it.
    ETL_CHAR        aBrand[ 64 ] = {};

    /// @brief  Family, model and stepping, with the extensions already added.
    ETL_UINT32        uFamily = 0;
    ETL_UINT32        uModel = 0;
    ETL_UINT32        uStepping = 0;

    /// @brief  Hardware threads this process can use.
    ///
    /// @details  Not what the machine has: what the affinity mask of this process
    ///            allows. On a 32 thread machine with the process pinned to 4, this
    ///            is 4. A caller sizing a thread pool needs this, and 32 threads on
    ///            a slice of 4 only add context switches.
    ETL_UINT32        uLogicalCores = 0;

    /// @brief  Physical cores. Zero when they cannot be told apart.
    ///
    /// @details  Zero here means "could not find out", not zero cores. The physical
    ///            count depends on topology that not every machine publishes, and
    ///            using the logical count instead would silently double a thread
    ///            budget on a machine with hyper-threading.
    ETL_UINT32        uPhysicalCores = 0;

    /// @brief  Cache line size, in bytes.
    ETL_UINT32        uCacheLine = 0;

    /// @brief  Size of each cache level, in bytes. Zero when there is none.
    ETL_UINT32        uCacheL1 = 0;
    ETL_UINT32        uCacheL2 = 0;
    ETL_UINT32        uCacheL3 = 0;

    /// @brief  Whether the cycle counter runs at a constant rate, as announced.
    ///
    /// @details  False means "not announced", not "the silicon does not have it",
    ///            as in iHypervisor. On an i7-6700, which has had the invariant
    ///            counter since the part exists, this field read zero. It was not a
    ///            reading defect: the Linux kernel did not publish 'constant_tsc' on
    ///            the same machine either. The Hyper-V under WSL hides leaf
    ///            0x80000007, and both read the same hidden leaf.
    ///
    ///           A caller choosing between 'rdtsc' and the system clock should treat
    ///            false as "use the system clock", which is safe in both cases.
    ETL_INT32        iInvariantTsc = 0;

    /// @brief  Whether this process runs under a hypervisor.
    ///
    /// @details  The bit is set by the hypervisor itself, and one that wants to hide
    ///            does not set it. True is reliable, false means "nothing announced".
    ETL_INT32        iHypervisor = 0;

    /// @brief  Hypervisor name, when it announces itself. E.g. "Microsoft Hv".
    ETL_CHAR        aHypervisor[ 16 ] = {};
};

What is known about the processor of this machine.

function

CpuFeaturesUsableWith

Ethereal::Platform#
ETL_UINT64 CpuFeaturesUsableWith( const ETL_UINT64 uRawFeatures, const ETL_UINT64 uXcr0 ) noexcept;

Which of these instructions survive what the system saves.

Pure arithmetic, kept apart on purpose. It came from a planted defect that survived: removing the XGETBV gate changed nothing, because the bench machine has a system that saves the wide registers, and there is no way to get one that does not. Apart from the reading, the decision can be called with a made up XCR0, so the gate has a test that does not depend on the machine.

The rules belong to the architecture, not to this library:

  • AVX, AVX2, FMA and F16C need the SSE and AVX state (XCR0 bits 1, 2).
  • The AVX-512 family also needs the masks, the upper half of the ZMM registers and the sixteen extra registers (bits 5, 6 and 7).
  • Everything that fits in 128 bits (the SSE family, AES-NI, SHA, POPCNT, the bit manipulation sets) passes untouched, since the XMM state has always been saved.
uRawFeatures
What the silicon declares. See SCpuFacts::uFeaturesRaw.
uXcr0
Content of XCR0. See SCpuFacts::uXcr0.
The usable subset. Never adds a bit that was not in the input.
Does not allocate, does not touch the system. Thread safety: full.
function

CpuFacts

Ethereal::Platform#
const SCpuFacts & CpuFacts() noexcept;

The processor facts, computed once.

Always the same reference, and the content does not change. Does not allocate, and does no work after the first call.

function

CpuFeatureName

Ethereal::Platform#
const ETL_CHAR * CpuFeatureName( const ETL_UINT64 uFeature ) noexcept;

Name of an instruction, for reports. Never returns null.

uFeature
One ETL_CPU_* bit. A combination returns "?".

exports.hpp

#include <ethereal/cpp/platform/exports.hpp>

Symbol resolution without going through the loader.

The spec says it in one line: "Needed where the loader is untrusted." GetProcAddress and dlsym go through tables that any code in the process may have changed, and a tamper check cannot ask the component that may be tampered with. Here the export table of the mapped image is read byte by byte, as the format says. If a hook replaced the entry the loader looks at, this read returns the original address, and the difference between the two is the finding. That comparison is the main use of this API: equal is clean, different means someone changed it.

What the format forces a reader to handle:

  • On Windows an export can be forwarded. The entry points to text such as "NTDLL.RtlAllocateHeap" and the loader resolves it in another image (Heap32First and much of the modern kernel32 are like that). Returning that address would hand out a pointer into the export table, and calling it would execute text.
  • There are exports by ordinal only, with no name in the name table. A search by name never finds them.
  • In ELF the dynamic symbol table does not carry its own count, it comes from the hash table. That is why the spec names ".dynsym plus GNU hash table" together.
const

ETL_EXPORT_DIRECT

Ethereal::Platform#
constexpr ETL_UINT32 ETL_EXPORT_DIRECT = 0x00u;

A plain export: the address is the code.

const

ETL_EXPORT_FORWARDED

Ethereal::Platform#
constexpr ETL_UINT32 ETL_EXPORT_FORWARDED = 0x01u;

The entry points to another module, by text. See SForward.

const

ETL_EXPORT_INDIRECT

Ethereal::Platform#
constexpr ETL_UINT32 ETL_EXPORT_INDIRECT = 0x02u;

The address is a resolver, not the implementation.

This is what makes a naive check report tampering where there is none. In ELF, a symbol marked STT_GNU_IFUNC holds the address of a function that picks the implementation for the processor. In glibc, memcpy, memset, strlen and most of the string family are like that.

The loader calls the resolver once and publishes the result, and dlsym returns that result. Reading the table returns the resolver. The two numbers differ and both are right. A caller comparing both paths to find hooks must skip entries with this bit, or it accuses half of the C library.

struct

SForward

Ethereal::Platform#
C++
struct   SForward   final
{
    /// @brief  'sizeof( SForward )'.
    ETL_UINT32        iStructSize = sizeof( SForward );

    /// @brief  Length of the text, in bytes.
    ETL_UINT32        uLength = 0;

    /// @brief  The target, as "MODULE.Symbol". Points into the image.
    ///
    /// @details  Not copied: the text lives in the export table of the module, which
    ///            stays mapped. Valid while the module is loaded.
    const ETL_CHAR *    pTarget = nullptr;
};

Target of a forwarded export.

function

ResolveExport

Ethereal::Platform#
EPlatformError ResolveExport( const ETL_UINT64 uModuleBase, const ETL_CHAR * pName, const ETL_UINT64 uNameLen, ETL_UINT64 * pAddrOut, SForward * pForwardOut = nullptr, ETL_UINT32 * pFlagsOut = nullptr ) noexcept;

Resolves an exported symbol by reading the mapped image.

A forwarded export without pForwardOut is an error, not an address. Returning the pointer to the text would hand out something that looks like code. The answer is eNotSupported, so the caller knows it must handle forwarding.

uModuleBase
Base of the module, as SModuleInfo returns it.
pName
The name. Does not need a terminating zero.
uNameLen
Length of the name, in bytes.
pAddrOut
Receives the address. Must not be null.
pForwardOut
When not null and the export is forwarded, receives the target, and pAddrOut stays zero.
pFlagsOut
When not null, receives the ETL_EXPORT_* flags.
eOk, eGone when the symbol does not exist in that image, or eInvalidArgument when the base does not point to an image this system can read.
function

ResolveExportOrdinal

Ethereal::Platform#
EPlatformError ResolveExportOrdinal( const ETL_UINT64 uModuleBase, const ETL_UINT32 uOrdinal, ETL_UINT64 * pAddrOut, SForward * pForwardOut = nullptr, ETL_UINT32 * pFlagsOut = nullptr ) noexcept;

Resolves by ordinal, for exports that have no name.

Windows only. ELF has no ordinals, and the answer is eNotSupported instead of a search that never finds anything.

uModuleBase
Base of the module, as SModuleInfo returns it.
uOrdinal
The published ordinal.
pAddrOut
Receives the address. Must not be null.
pForwardOut
When not null and the export is forwarded, receives the target.
pFlagsOut
When not null, receives the ETL_EXPORT_* flags.
eOk, eGone, eInvalidArgument or eNotSupported.
alias

bool

Ethereal::Platform#
using FVisitExportName = bool ( * )( const ETL_CHAR * pName, ETL_UINT64 uLen, void * pUser );

Called for each exported name. Returning false stops the walk.

pName
The name, zero terminated, inside the mapped image.
uLen
Length, without the zero.
pUser
The caller's context.
function

EnumExportNames

Ethereal::Platform#
EPlatformError EnumExportNames( const ETL_UINT64 uModuleBase, FVisitExportName pVisit, void * pUser ) noexcept;

Walks the exported names of a mapped module.

It lets a caller search without having the name in its own binary. The hash search (comparing the hash of the wanted name with the hash of each name in the table) needs to read the names of the table, not to have them written in the code. This function hands them one by one, and the caller hashes and compares each. It drives the import hardening that lives in the Guard.

The walk reads the same table as ResolveExport. There is no new format parsing: it is the known export directory, walked by name instead of searched by name.

uModuleBase
Base of the module, as SModuleInfo returns it.
pVisit
Called for each name. Must not be null.
pUser
Passed back on each call.
eGone when the image exports nothing.

fingerprint.hpp

#include <ethereal/cpp/platform/fingerprint.hpp>

Hardware fingerprint.

This is an identifier, not a secret. Anyone running this code on the machine computes the same number. There is no key, no signature, and no attempt to hide how it is formed: the spec asks for a documented component list. It answers "is this the same machine as yesterday?". It does not answer "is this machine who it claims to be, to a hostile server", which needs cryptography and a secret that is not on the machine.

The real problem of a fingerprint is drift, not collision. Two machines with the same number is rare and obvious. The same machine with a different number happens every day (a new network card, a VPN, Windows renaming an adapter), and the licensing accuses someone who did nothing. So each component declares its stability, and the default mask takes only the stable ones.

Components, stability and what changes them:

  • CPU identity, high: replacing the processor.
  • CPU topology, medium: replacing the processor, a resized VM.
  • Machine id, high: reinstalling the system, cloning an image.
  • Disk serials, medium: replacing or adding a disk.
  • MAC addresses, low: a VPN, a container, a cable, a dock.
  • Physical memory, medium: adding memory.

MAC addresses are the classic component and the worst. They are here because the spec asks for them as a queryable component, not because they should be part of the composition, and they are left out of the default mask. For callers that want them, virtual interfaces (ETL_NETIF_VIRTUAL) are dropped and the rest are sorted first, or the enumeration order would change the result with nothing changed.

enum

EFingerprintComponent

Ethereal::Platform#
C++
enum class   EFingerprintComponent : ETL_UINT32
{
    /// @brief  Vendor, family, model, stepping and brand string of the processor.
    eCpuIdentity = 0,

    /// @brief  Physical cores, logical threads and the cache sizes.
    eCpuTopology,

    /// @brief  The identifier the system gave itself at install time.
    ///
    /// @details  'MachineGuid' on Windows, '/etc/machine-id' on Linux. Two machines
    ///            cloned from the same image have the same one, which is why it is not
    ///            enough by itself.
    eMachineId,

    /// @brief  Serial numbers of the physical disks, sorted.
    eDiskSerials,

    /// @brief  Physical addresses of the non virtual interfaces, sorted.
    ///
    /// @details  Not in the default mask. See the file header.
    eMacAddresses,

    /// @brief  Physical memory of the machine, in units of 256 MiB.
    ///
    /// @details  The granularity is deliberate: the total the system publishes varies
    ///            by a few megabytes between boots, because what the integrated graphics
    ///            reserves changes. The exact number would make the fingerprint change
    ///            on its own.
    ePhysicalMemory,

    /// @brief  Number of components. Not a component.
    eCount
};

One piece of what identifies the machine.

function

FingerprintComponentName

Ethereal::Platform#
const ETL_CHAR * FingerprintComponentName( const EFingerprintComponent eWhat ) noexcept;

Name of the component, for reports. Never returns null.

enum

EFingerprintStability

Ethereal::Platform#
C++
enum class   EFingerprintStability : ETL_UINT8
{
    /// @brief  Changes only with new hardware or a reinstall.
    eHigh = 0,

    /// @brief  Changes when a part is added or removed.
    eMedium,

    /// @brief  Changes day to day, with nobody touching the hardware.
    eLow
};

How far a component can be trusted not to change on its own.

function

FingerprintComponentStability

Ethereal::Platform#
EFingerprintStability FingerprintComponentStability( const EFingerprintComponent eWhat ) noexcept;

Declared stability of the component. See the table in the file header.

function

FingerprintBit

Ethereal::Platform#
constexpr ETL_UINT32 FingerprintBit( const EFingerprintComponent eWhat ) noexcept

Bit of a component, for the masks.

const

FingerprintBit

Ethereal::Platform#
constexpr ETL_UINT32 FINGERPRINT_DEFAULT_MASK = FingerprintBit( EFingerprintComponent::eCpuIdentity ) | FingerprintBit( EFingerprintComponent::eCpuTopology ) | FingerprintBit( EFingerprintComponent::eMachineId ) | FingerprintBit( EFingerprintComponent::eDiskSerials ) | FingerprintBit( EFingerprintComponent::ePhysicalMemory );

What goes into the fingerprint when the caller does not choose.

Everything except the MAC addresses. Including by default what changes when someone turns on a VPN is the fastest way to accuse someone who did nothing.

function

FingerprintComponentValue

Ethereal::Platform#
EPlatformError FingerprintComponentValue( const EFingerprintComponent eWhat, ETL_UINT64 * pHashOut, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Reads one component, as text and as a hash.

The text form is what makes this debuggable. A user whose license stopped working sends the text, and the changed component shows at a glance. With only the composed number, the answer is "I don't know".

A component that could not be collected returns eNotFound and a zero hash. No substitute is made up: a substitute is equal on two different machines, the worst and quietest defect possible here.

eWhat
The component.
pHashOut
Receives the 64 bit hash of the component. May be null. Zero means "could not collect it", never a legitimate value.
pArena
Where the text form is written, zero terminated. May be null when uArena is zero.
uArena
Size of pArena, in bytes.
pNeeded
Receives the bytes the text needs, with the terminator, even when the answer is eBufferTooSmall.
eOk, eNotFound, eBufferTooSmall or eInvalidArgument.
function

HardwareFingerprint

Ethereal::Platform#
EPlatformError HardwareFingerprint( const ETL_UINT32 uMask, ETL_UINT64 * pOut, ETL_UINT32 * pMissingOut ) noexcept;

Composes the fingerprint from the chosen components.

A missing component is not silently ignored. It enters the composition as "absent", not as empty, or a machine where the disk serial cannot be read would give the same number as one where it reads empty. pMissingOut says which were missing, because a fingerprint made only of absences is the same everywhere and nobody would notice.

If everything is missing, the answer is eNotSupported and no number.

uMask
Combination of FingerprintBit. Zero uses FINGERPRINT_DEFAULT_MASK.
pOut
Receives the number. Never zero when the answer is eOk.
pMissingOut
Receives the mask of the components not collected. May be null.
eOk, eInvalidArgument, eNotSupported, or eNotLicensed when the library is not licensed.
const

FINGERPRINT_TEXT_MAX

Ethereal::Platform#
constexpr ETL_UINT64 FINGERPRINT_TEXT_MAX = 1024u;

Bytes that fit the text of any component, with the terminator.

hardware.hpp

#include <ethereal/cpp/platform/hardware.hpp>

Disks, network interfaces and memory per NUMA node.

This lives here, not in the file or network modules, because it is about neither. Spec 05 puts both in the same section ("hardware and OS facts") and names the consumer: the hardware fingerprint, for licensing. The existing cpp/system/disk.hpp measures usage (bytes this process read and wrote), not which disks exist, their model or serial. cpp/network talks to the network, it does not enumerate its hardware.

The serial number is the field most often missing, and the one that lies most. The spec asks for "serial where permitted": the serial comes from an IOCTL the system may refuse, a USB disk may not answer, and a virtual machine often fills with the same text on every instance. So it is empty when it could not be read, never a substitute. A fingerprint built on a made up serial is the same on two machines, the worst and quietest defect a fingerprint can have.

enum

EDiskKind

Ethereal::Platform#
C++
enum class   EDiskKind : ETL_UINT8
{
    /// @brief  Not found out. Does not mean "none of the others".
    eUnknown = 0,

    /// @brief  Spinning platter: the system reports a seek penalty.
    eRotational,

    /// @brief  Solid state: the system reports no seek penalty.
    eSolidState,

    /// @brief  Removable.
    eRemovable,

    /// @brief  A virtual disk, a RAM disk or a mounted image.
    eVirtual
};

Kind of disk.

function

DiskKindName

Ethereal::Platform#
const ETL_CHAR * DiskKindName( const EDiskKind eKind ) noexcept;

Name of the kind, for reports. Never returns null.

struct

SDiskInfo

Ethereal::Platform#
C++
struct   SDiskInfo   final
{
    /// @brief  'sizeof( SDiskInfo )'. Lets the structure grow without breaking compiled callers.
    ETL_UINT32        iStructSize = sizeof( SDiskInfo );

    /// @brief  Index of the disk in the system. 'PhysicalDrive<N>' on Windows.
    ETL_UINT32        uIndex = 0;

    /// @brief  Size of the disk, in bytes. Zero when the system did not say.
    ETL_UINT64        uSizeBytes = 0;

    /// @brief  Sector size, in bytes. Zero when the system did not say.
    ETL_UINT32        uSectorSize = 0;

    /// @brief  The kind.
    EDiskKind        eKind = EDiskKind::eUnknown;

    /// @brief  Explicit padding. See section 7 of the conventions.
    ETL_UINT8        aPadding[ 3 ] = {};

    /// @brief  Model, in UTF-8, inside the caller's arena. May be null.
    const ETL_CHAR *    pModel = nullptr;

    /// @brief  Length of the model, in bytes, without the terminating zero.
    ETL_UINT32        uModelLength = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding2 = 0;

    /// @brief  Serial number, in UTF-8, in the arena. Null when unknown.
    ///
    /// @details  See the file header: empty is the honest answer, and a substitute
    ///            would give the same fingerprint on two machines.
    const ETL_CHAR *    pSerial = nullptr;

    /// @brief  Length of the serial number, in bytes.
    ETL_UINT32        uSerialLength = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding3 = 0;
};

A physical disk of the machine.

alias

bool

Ethereal::Platform#
using FVisitDisk = bool ( * )( const SDiskInfo & Info, void * pUser );

Called for each disk. Returning false stops the walk.

function

EnumDisks

Ethereal::Platform#
EPlatformError EnumDisks( FVisitDisk pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the physical disks of the machine.

This touches the disk, so it is not for the scan loop. Each disk costs opening a device and two or three IOCTLs. The spec puts the 2 ms budget on the enumeration of modules and threads; this one belongs to the facts section, collected once.

pVisit
Called for each disk. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Where the texts are written. May be null when uArena is zero.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs, even when the answer is eBufferTooSmall.
eOk, eBufferTooSmall, eAccessDenied, eInvalidArgument or eNotSupported.
function

EnumDisks

Ethereal::Platform#
EPlatformError EnumDisks( SDiskInfo * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

The spec asks for both forms, and says why: "there is no form that returns a container". The visitor form keeps nothing, this one fills what the caller already has, and neither allocates. The C layer uses this one: a function pointer crossing the boundary and back costs more to a C# or Rust caller than an array read at once.

pOut
Where to write. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many disks exist, not how many fit. Required.
pArena
Where the texts are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied, eInvalidArgument or eNotSupported.
const

ETL_NETIF_UP

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_UP = 1u << 0;

Up and running.

const

ETL_NETIF_LOOPBACK

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_LOOPBACK = 1u << 1;

Loopback interface (127.0.0.1 / ::1).

const

ETL_NETIF_BROADCAST

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_BROADCAST = 1u << 2;

Supports broadcast.

const

ETL_NETIF_MULTICAST

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_MULTICAST = 1u << 3;

Supports multicast.

const

ETL_NETIF_POINTTOPOINT

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_POINTTOPOINT = 1u << 4;

Point to point (tunnel, PPP).

const

ETL_NETIF_WIRELESS

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_WIRELESS = 1u << 5;

Wireless.

const

ETL_NETIF_VIRTUAL

Ethereal::Platform#
constexpr ETL_UINT32 ETL_NETIF_VIRTUAL = 1u << 6;

The system reports the interface as virtual, and that matters.

A virtual card (virtual machine, VPN, container) has a physical address that changes between boots in several products. A fingerprint built on it changes by itself, and blames the user for it.

const

NETIF_MAC_MAX

Ethereal::Platform#
constexpr ETL_UINT64 NETIF_MAC_MAX = 20u;

Bytes that fit the longest physical address there is.

Six for Ethernet and Wi-Fi, twenty for InfiniBand, the longest the two systems publish.

struct

SNetInterfaceInfo

Ethereal::Platform#
C++
struct   SNetInterfaceInfo   final
{
    /// @brief  'sizeof( SNetInterfaceInfo )'.
    ETL_UINT32        iStructSize = sizeof( SNetInterfaceInfo );

    /// @brief  Index of the interface in the system.
    ETL_UINT32        uIndex = 0;

    /// @brief  Combination of ETL_NETIF_*.
    ETL_UINT32        uFlags = 0;

    /// @brief  Valid bytes of the physical address. Zero when there is none.
    ETL_UINT32        uMacLength = 0;

    /// @brief  Physical address. Only the first uMacLength bytes are valid.
    ETL_UINT8        aMac[ NETIF_MAC_MAX ] = {};

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Nominal speed, in bits per second. Zero when unknown.
    ETL_UINT64        uSpeedBps = 0;

    /// @brief  System name, in UTF-8, inside the caller's arena.
    const ETL_CHAR *    pName = nullptr;

    /// @brief  Length of the name, in bytes.
    ETL_UINT32        uNameLength = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding2 = 0;

    /// @brief  Readable description, when the system gives one. May be null.
    const ETL_CHAR *    pDescription = nullptr;

    /// @brief  Length of the description, in bytes.
    ETL_UINT32        uDescriptionLength = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding3 = 0;
};

A network interface.

alias

bool

Ethereal::Platform#
using FVisitInterface = bool ( * )( const SNetInterfaceInfo & Info, void * pUser );

Called for each interface. Returning false stops the walk.

function

EnumNetworkInterfaces

Ethereal::Platform#
EPlatformError EnumNetworkInterfaces( FVisitInterface pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the network interfaces of the machine.

Interfaces come and go. A pulled cable, a VPN going up, a container starting: the list now is not the list a minute from now. Whoever builds identity on it must choose what counts, so the fingerprint of this module uses only physical interfaces, and says so.

pVisit
Called for each interface. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Where the texts are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the bytes the walk needs.
eOk, eBufferTooSmall, eAccessDenied, eSystemError or eNotSupported.
function

EnumNetworkInterfaces

Ethereal::Platform#
EPlatformError EnumNetworkInterfaces( SNetInterfaceInfo * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

pOut
Where to write. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many interfaces exist, not how many fit.
pArena
Where the texts are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the bytes the walk needs.
eOk, eBufferTooSmall, eAccessDenied, eSystemError or eNotSupported.
function

NumaNodeMemory

Ethereal::Platform#
EPlatformError NumaNodeMemory( const ETL_UINT32 uNode, ETL_UINT64 * pTotalOut, ETL_UINT64 * pFreeOut ) noexcept;

Total and free memory of a NUMA node.

The total per node is harder to get than the free amount, against intuition. Windows has GetNumaAvailableMemoryNodeEx and no pair for the total, which comes from the physical memory table, readable only through privileged paths. It is zero when unknown, as everywhere in this module. On Linux both are in /sys/devices/system/node/node<N>/meminfo.

uNode
Node number, from zero to SOsFacts::uNumaNodes minus one.
pTotalOut
Receives the total of the node. May be null.
pFreeOut
Receives the free amount of the node. May be null.
eOk, eInvalidArgument, eNotFound, eSystemError or eNotSupported.

image_integrity.hpp

#include <ethereal/cpp/platform/image_integrity.hpp>

The image on disk against the image in memory.

This computes no hash, on purpose. The spec says "hash", but section 2 of the conventions forbids a module from including another to get functionality, and SHA-256 lives in the Cryptography module. More important, the value is not in the hash but in knowing what to hash. Comparing the bytes of the image on disk with the loaded image is hard for reasons that have nothing to do with cryptography (relocation, import table, alignment padding), and that is what this file handles. So ReadSectionNormalized hands out bytes that are already comparable, and the caller hashes them with whatever it wants. CompareSection compares both sides without hashing and says where they differ, which is worth more for diagnostics than a yes or no.

What makes the two sides differ with no tampering:

  • Relocation. The image was linked for one address and loaded at another (address randomization does it on every start). The loader fixes each absolute address inside the image.
  • Import table. Each imported function has an entry the loader fills with the real address. On disk it holds the name, in memory the address.
  • Padding. File alignment and memory alignment differ, and the remainder exists on one side only. Comparing without handling these accuses every image of every process. So the comparison neutralizes (zeroes on both sides) every range the loader was allowed to touch, and reports how many bytes were neutralized. That number is part of the result: too much neutralization hides tampering, and a comparison that neutralized everything would always say "equal".

The .text section is the one that matters. The spec asks for a per section result "so a caller can pin only .text": code does not change at run time, data sections do by design. In modern images .text usually has zero relocations (64 bit code addresses relative to the instruction pointer), so uNeutralized equal to zero on .text is the normal and best case: nothing had to be forgiven.

struct

SCompareResult

Ethereal::Platform#
C++
struct   SCompareResult   final
{
    /// @brief  'sizeof( SCompareResult )'.
    ETL_UINT32        iStructSize = sizeof( SCompareResult );

    /// @brief  Whether both sides are equal after neutralization.
    ETL_INT32        iEqual = 0;

    /// @brief  Bytes compared.
    ETL_UINT64        uCompared = 0;

    /// @brief  Bytes set to zero on both sides before comparing.
    ///
    /// @details  Look at this number. It is the size of what the comparison chose to
    ///            forgive. Zero means the whole section was checked byte by byte. A
    ///            large number means much of it was left out, and tampering there would
    ///            go unnoticed.
    ETL_UINT64        uNeutralized = 0;

    /// @brief  Bytes that differ. Zero when iEqual.
    ETL_UINT64        uDifferent = 0;

    /// @brief  Offset of the first differing byte, inside the section.
    ///
    /// @details  Meaningful only when uDifferent is not zero. For diagnostics: a hash
    ///            says there is a difference, this number says where.
    ETL_UINT64        uFirstDifference = 0;

    /// @brief  Address of the section in memory.
    ETL_UINT64        uMappedAddress = 0;
};

The outcome of comparing a section on both sides.

struct

SBuildIdentity

Ethereal::Platform#
C++
struct   SBuildIdentity   final
{
    /// @brief  'sizeof( SBuildIdentity )'.
    ETL_UINT32        iStructSize = sizeof( SBuildIdentity );

    /// @brief  Valid bytes of aId. Zero when there is none.
    ETL_UINT32        uIdLength = 0;

    /// @brief  The raw identifier.
    ///
    /// @details  In ELF it is NT_GNU_BUILD_ID, usually 20 bytes of SHA-1 over the
    ///            linked image. In PE it is the 16 bytes of the PDB GUID followed by the
    ///            age, which together identify the symbol file.
    ETL_UINT8        aId[ 32 ] = {};

    /// @brief  PDB age, in PE. Zero in ELF.
    ETL_UINT32        uAge = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Path of the symbol file, when the binary declares it.
    ///
    /// @details  Text from the file, not trusted. It is a path on the build machine
    ///            and does not exist on this one. It is for matching symbols, never for
    ///            opening anything without checking first.
    ETL_CHAR        aSymbolPath[ 256 ] = {};
};

What identifies this exact build of the binary.

enum

ESignatureStatus

Ethereal::Platform#
C++
enum class   ESignatureStatus : ETL_UINT8
{
    /// @brief  Could not ask.
    eUnknown = 0,

    /// @brief  The system has no such concept. The case of ELF.
    eNotApplicable = 1,

    /// @brief  The file has no signature.
    eUnsigned = 2,

    /// @brief  Signed, and the chain closed with no remarks.
    eValid = 3,

    /// @brief  Signed, but the chain does not end in a trusted root.
    eUntrustedRoot = 4,

    /// @brief  Signed, but the certificate is out of its validity period.
    eExpired = 5,

    /// @brief  Signed, and the signature does not match the file content.
    ///
    /// @details  The only status that points to tampering directly, and even this one
    ///            is a fact, not a verdict.
    eTampered = 6,

    /// @brief  Signed, and the certificate was revoked.
    eRevoked = 7
};

What the chain verification answered. Not a trust decision.

function

SignatureStatusName

Ethereal::Platform#
const ETL_CHAR * SignatureStatusName( ESignatureStatus eStatus ) noexcept;

Name of the status, for reports. Never returns null.

struct

SSignatureInfo

Ethereal::Platform#
C++
struct   SSignatureInfo   final
{
    /// @brief  'sizeof( SSignatureInfo )'.
    ETL_UINT32            iStructSize = sizeof( SSignatureInfo );

    /// @brief  What the chain answered. Not a trust decision.
    ESignatureStatus    eStatus = ESignatureStatus::eUnknown;

    /// @brief  Explicit padding.
    ETL_UINT8            aPad[ 3 ] = {};

    /// @brief  Signer, as the certificate declares it. Empty when there is none.
    ETL_CHAR            aSigner[ 128 ] = {};

    /// @brief  Issuer of the signer's certificate.
    ETL_CHAR            aIssuer[ 128 ] = {};

    /// @brief  Timestamp, in nanoseconds since 1970.
    ///
    /// @details  Zero when there is no timestamp. A timestamp changes the meaning of an
    ///            expired certificate: with it, the signature still says "this was signed
    ///            while the certificate was valid", without it, it says nothing. What to
    ///            do with that is the caller's decision.
    ETL_UINT64            uTimestampNs = 0;
};

What is known about the signature of a file. Facts, not a verdict.

function

ReadSectionNormalized

Ethereal::Platform#
EPlatformError ReadSectionNormalized( const ETL_UINT64 uModuleBase, const ETL_CHAR * pPath, const ETL_CHAR * pSection, ETL_UINT8 * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pNeeded, ETL_UINT64 * pNeutralized = nullptr ) noexcept;

Hands out the bytes of a section, ready to compare or hash.

Follows the two pass protocol of the module: call with pOut null to learn the size, reserve, call again. The bytes come neutralized (every range the loader was allowed to touch is zero), so the same section read from disk and from memory gives the same hash when nothing was tampered with.

uModuleBase
Base of the loaded module, or 0 to read from the file.
pPath
Path of the file. Required (see image_integrity.cpp).
pSection
Name of the section, e.g. ".text". Must not be null.
pOut
Where to write. May be null to only measure.
uOut
Size of pOut, in bytes.
pNeeded
Receives the size of the section. Must not be null.
pNeutralized
Optional. Receives the bytes set to zero.
eOk, eBufferTooSmall, or what prevented it.
Thread safety: full.
function

CompareSection

Ethereal::Platform#
EPlatformError CompareSection( const ETL_UINT64 uModuleBase, const ETL_CHAR * pPath, const ETL_CHAR * pSection, SCompareResult * pOut ) noexcept;

Compares a section of the loaded module with the same section in the file.

Hashes nothing: compares byte by byte and says where they differ. See the file header about what is neutralized and why the number matters.

uModuleBase
Base of the loaded module.
pPath
Path of the file it came from.
pSection
Name of the section, e.g. ".text".
pOut
Receives the result. Must not be null.
eOk when the comparison ran, which does not mean the sides are equal. That is in SCompareResult::iEqual.
Allocates: it needs a copy of each side to neutralize without writing into the loaded image. Thread safety: full.
function

QueryBuildIdentity

Ethereal::Platform#
EPlatformError QueryBuildIdentity( const ETL_UINT64 uModuleBase, const ETL_CHAR * pPath, SBuildIdentity * pOut ) noexcept;

The identifier of this exact build.

uModuleBase
Base of the loaded module, or 0 to read from the file.
pPath
The path. Required.
pOut
Where to write. Must not be null.
eOk, eNotFound, eNotSupported or eInvalidArgument.
function

QuerySignature

Ethereal::Platform#
EPlatformError QuerySignature( const ETL_CHAR * pPath, SSignatureInfo * pOut ) noexcept;

What is known about the signature of a file. Facts, not a verdict.

Read the note above ESignatureStatus before using this to decide anything. This function reports what it found, and the trust policy belongs to the caller.

pPath
Path of the file. Must not be null.
pOut
Where to write. Must not be null.
eOk when the query ran, even if the file is not signed. That is a fact, reported in SSignatureInfo::eStatus. eNotLicensed when the library is not licensed.
Touches the system and may go to the network to check revocation. Do not call it in a hot loop. Thread safety: full.

memory_regions.hpp

#include <ethereal/cpp/platform/memory_regions.hpp>

Memory regions of a process, protection and page locking.

Protection is normalized. The spec: "Protection flags must be normalized into an Ethereal bitmask that maps cleanly both ways. Do not leak PAGE_EXECUTE_READWRITE or PROT_EXEC into the public API." The two systems describe the same thing in incompatible ways. On Windows the protection is a value from a closed list (PAGE_READWRITE and PAGE_EXECUTE_READ are distinct numbers, not bits that add up). On POSIX it is a sum of bits (PROT_READ | PROT_WRITE). A check written against the raw values would have to be written twice, and "is this region executable?" becomes a chain of equality tests on Windows, where forgetting one case is a false negative in a security check. Here it is a bit map everywhere, and the question is a conjunction.

The conversion must close both ways. ProtectMemory takes the normalized map and translates it back to what the system understands. If the two directions were not inverse, the caller would ask for one protection and silently get another. The suite checks that normalizing and denormalizing every representable combination returns the same map.

const

ETL_PAGE_NONE

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_NONE = 0x00u;

No access.

const

ETL_PAGE_READ

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_READ = 0x01u;

Read.

const

ETL_PAGE_WRITE

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_WRITE = 0x02u;

Write.

const

ETL_PAGE_EXECUTE

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_EXECUTE = 0x04u;

Execute.

const

ETL_PAGE_COPY

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_COPY = 0x08u;

Copy on write: writing creates a private copy.

const

ETL_PAGE_GUARD

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_GUARD = 0x10u;

Guard page: the first access signals instead of going through.

const

ETL_PAGE_NOCACHE

Ethereal::Platform#
constexpr ETL_UINT32 ETL_PAGE_NOCACHE = 0x20u;

Not cached.

enum

ERegionState

Ethereal::Platform#
C++
enum class   ERegionState : ETL_UINT32
{
    /// @brief  Nobody reserved it. On Linux this is the space between mappings.
    eFree = 0,

    /// @brief  Reserved, with no memory behind it.
    ///
    /// @details  Windows only. POSIX has no reservation without a mapping: the
    ///            equivalent is a mapping with no protection, and that is how it
    ///            shows up here.
    eReserved,

    /// @brief  Reserved, with memory behind it.
    eCommitted
};

What the system did with a range.

enum

ERegionType

Ethereal::Platform#
C++
enum class   ERegionType : ETL_UINT32
{
    /// @brief  Not applicable (the region is free).
    eNone = 0,

    /// @brief  Private to the process.
    ePrivate,

    /// @brief  Mapped from a file that is not an executable image.
    eMapped,

    /// @brief  Part of a loaded executable image.
    ///
    /// @details  This is the type that matters in a check: injected code almost
    ///            always lives in private executable memory, since the injector has
    ///            no image file to map.
    eImage
};

Where the memory came from.

struct

SMemoryRegion

Ethereal::Platform#
C++
struct   SMemoryRegion   final
{
    /// @brief  'sizeof( SMemoryRegion )'.
    ETL_UINT32        iStructSize = sizeof( SMemoryRegion );

    /// @brief  Combination of ETL_PAGE_*.
    ETL_UINT32        uProtect = 0;

    /// @brief  Where the region starts.
    ETL_UINT64        uBaseAddress = 0;

    /// @brief  Size of the region, in bytes.
    ETL_UINT64        uSize = 0;

    /// @brief  The state.
    ERegionState    eState = ERegionState::eFree;

    /// @brief  The type.
    ERegionType        eType = ERegionType::eNone;

    /// @brief  The mapped file, in UTF-8, or empty when anonymous.
    const ETL_CHAR *    pMappedPath = nullptr;

    /// @brief  Length of the path, in bytes.
    ETL_UINT32        uPathLength = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;
};

A memory region.

alias

bool

Ethereal::Platform#
using FVisitRegion = bool ( * )( const SMemoryRegion & Info, void * pUser );

Called for each region. Returning false stops the walk.

function

EnumMemoryRegions

Ethereal::Platform#
EPlatformError EnumMemoryRegions( const ETL_UINT64 uPid, FVisitRegion pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the memory regions of a process.

Free regions are part of the walk, on purpose. Without them there is no way to tell "this range is free" from "I could not see this range", and the difference matters to a caller looking for what should not be there. On Linux the maps file only lists what exists, so the gaps between mappings are synthesized here as eFree, and both platforms describe the address space the same way.

uPid
Zero means this process.
pVisit
Called for each region. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Where the paths are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied or eNotSupported.
function

EnumMemoryRegions

Ethereal::Platform#
EPlatformError EnumMemoryRegions( const ETL_UINT64 uPid, SMemoryRegion * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

The spec asks for both forms of every enumeration, and this one was missing. See the same note in EnumThreads.

uPid
Zero means this process.
pOut
Where to write. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many regions exist, not how many fit.
pArena
Where the paths are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied or eNotSupported.
function

QueryMemory

Ethereal::Platform#
EPlatformError QueryMemory( const ETL_UINT64 uPid, const ETL_UINT64 uAddress, SMemoryRegion * pOut, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The region that contains an address.

uPid
Zero means this process.
uAddress
The address.
pOut
Receives the region. Must not be null.
pArena
Where the path is written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the walk needs.
eOk, eGone when no region contains the address, or the walk error.
function

ProtectMemory

Ethereal::Platform#
EPlatformError ProtectMemory( const ETL_UINT64 uAddress, const ETL_UINT64 uSize, const ETL_UINT32 uNewProtect, ETL_UINT32 * pOldOut ) noexcept;

Changes the protection of a range of this process.

uAddress
Start of the range.
uSize
Size of the range, in bytes.
uNewProtect
Combination of ETL_PAGE_*.
pOldOut
Receives the previous protection, already normalized. May be null.
eOk, eInvalidArgument, eNotSupported when the combination has no representation, or eAccessDenied.
function

LockMemory

Ethereal::Platform#
EPlatformError LockMemory( void * pAddress, const ETL_UINT64 uSize ) noexcept;

Locks a range of this process in physical memory.

The range is rounded to pages, by both systems, without warning: locking one byte locks the whole page, and unlocking that byte unlocks it. Two ranges in the same page are not independent.

pAddress
Start of the range.
uSize
Size of the range, in bytes.
eOk, eInvalidArgument, eAccessDenied, eSystemError or eNotSupported.
function

UnlockMemory

Ethereal::Platform#
EPlatformError UnlockMemory( void * pAddress, const ETL_UINT64 uSize ) noexcept;

Unlocks a range locked by LockMemory.

Locks do not stack: one VirtualUnlock releases the range however many VirtualLock calls there were, and munlock on Linux is the same. It is the opposite of SuspendThread, and nobody guesses it.

pAddress
Start of the range.
uSize
Size of the range, in bytes.
eOk, eInvalidArgument, eSystemError or eNotSupported.
function

NormalizeProtection

Ethereal::Platform#
ETL_UINT32 NormalizeProtection( const ETL_UINT32 uNative ) noexcept;

Translates the system protection to the normalized map.

function

DenormalizeProtection

Ethereal::Platform#
ETL_UINT32 DenormalizeProtection( const ETL_UINT32 uMask ) noexcept;

Translates the normalized map back to the system protection.

Zero when the combination has no representation on this system.

modules.hpp

#include <ethereal/cpp/platform/modules.hpp>

The loaded modules of a process.

EnumModulesSelf is the hot path of the whole module. The spec: "EnumModulesSelf is the one that runs in the scan loop. It must be syscall-free on Windows and Linux", with a budget under 100 microseconds, zero system calls and zero allocations. All three are possible for the same reason: the list of loaded modules is already in the process memory, put there by the loader.

  • On Windows it is the InMemoryOrderModuleList of the PEB, reached from the thread block. No system call, and not CreateToolhelp32Snapshot, which the spec forbids in the hot loop: it copies the state of the whole system to answer about one process.
  • On Linux it is dl_iterate_phdr, which walks the dynamic loader list. The spec prefers it to /proc/self/maps because "it avoids the filesystem entirely". Reading a /proc file costs three system calls plus parsing.

The text goes to an arena of the caller. The spec: "String storage goes into a caller-provided arena. The module never owns strings." Here this is what makes the no allocation promise possible: on Windows the module name lives in the PEB in UTF-16, and returning it in UTF-8 needs somewhere to convert to. When the arena runs out, the answer is eBufferTooSmall with the needed size, never a name cut in half. A cut name would pass for a name, and a check comparing names would decide on a prefix.

struct

SModuleInfo

Ethereal::Platform#
C++
struct   SModuleInfo   final
{
    /// @brief  'sizeof( SModuleInfo )'. Lets the structure grow without breaking compiled callers.
    ETL_UINT32        iStructSize = sizeof( SModuleInfo );

    /// @brief  Timestamp of the image, when the format has one.
    ///
    /// @details  On Windows it is the PE header field. ELF has none and it is zero:
    ///            the format carries no link date, and making one up from the file
    ///            system would cost the disk access this function exists to avoid.
    ETL_UINT32        uTimestamp = 0;

    /// @brief  Where the image starts in memory.
    ETL_UINT64        uBaseAddress = 0;

    /// @brief  Size of the image, in bytes.
    ETL_UINT64        uSize = 0;

    /// @brief  Entry point, or zero when the platform does not offer it cheaply.
    ETL_UINT64        uEntryPoint = 0;

    /// @brief  Short name, in UTF-8, inside the caller's arena.
    const ETL_CHAR *    pName = nullptr;

    /// @brief  Length of the name, in bytes, without the terminating zero.
    ETL_UINT32        uNameLength = 0;

    /// @brief  Explicit padding. See section 7 of the conventions.
    ETL_UINT32        uPadding = 0;

    /// @brief  Full path, in UTF-8, inside the caller's arena.
    const ETL_CHAR *    pPath = nullptr;

    /// @brief  Length of the path, in bytes.
    ETL_UINT32        uPathLength = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding2 = 0;
};

A loaded module.

alias

bool

Ethereal::Platform#
using FVisitModule = bool ( * )( const SModuleInfo & Info, void * pUser );

Called for each module found.

Returning false stops the walk, for a caller looking for one module that does not want to pay for the rest of the list.

A function pointer with user data, not a standard library callable, for two reasons: it crosses the C boundary without translation, and it cannot allocate (a std::function can).

function

EnumModulesSelf

Ethereal::Platform#
EPlatformError EnumModulesSelf( FVisitModule pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the modules loaded in this process.

pVisit
Called for each module. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Where the names are written. May be null when uArena is zero.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs. Written even when the answer is eBufferTooSmall, which is the point: size once and reuse.
eOk, eBufferTooSmall, eInvalidArgument or eNotSupported.
Does not allocate. Makes no system call. Thread safety: full.
function

EnumModulesSelf

Ethereal::Platform#
EPlatformError EnumModulesSelf( SModuleInfo * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

Calling with uOut zero asks "how many are there?" without writing anything. The spec asks for both forms, and this one serves callers that want to size first.

pOut
Where to write. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many modules exist, not how many fit.
pArena
Where the names are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs.
eOk, eBufferTooSmall, eInvalidArgument or eNotSupported.
function

EnumModules

Ethereal::Platform#
EPlatformError EnumModules( const ETL_UINT64 uPid, FVisitModule pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the modules loaded in another process.

Needs privilege. Without it the answer is eAccessDenied, which is not eNotSupported: the information exists, and another privilege level reaches it. On Windows the modules of a 64 bit process cannot be read from a 32 bit process, and the system refuses with a status that comes out here as eAccessDenied.

uPid
The process. Zero means this one, and then the call goes to EnumModulesSelf, which is much cheaper.
pVisit
Called for each module. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Where the names are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied, eGone, eSystemError or eNotSupported.
function

EnumModules

Ethereal::Platform#
EPlatformError EnumModules( const ETL_UINT64 uPid, SModuleInfo * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

uPid
The process. Zero means this one.
pOut
Where to write. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many modules exist, not how many fit.
pArena
Where the names are written.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied, eGone, eSystemError or eNotSupported.
function

LastSyscallCount

Ethereal::Platform#
ETL_UINT64 LastSyscallCount() noexcept;

Number of system calls made by the last walk of this thread.

The spec asks for it as a metric: "Syscall count is a tracked metric. Every enumeration function documents how many syscalls it performs." For EnumModulesSelf the answer must be zero, and a test checks it. The no system call promise is invisible otherwise: one day someone replaces the PEB walk with a convenient call, everything stays correct, and the scan loop starts to cost what it could not.

os_facts.hpp

#include <ethereal/cpp/platform/os_facts.hpp>

Operating system facts.

What does not change while the process lives is computed once and cached in SOsFacts. What changes has its own function: free memory changes between two lines of code, and caching it with the facts would hand out a stale number that looks like a measurement. The suite checks both sides: the facts must be byte identical between two calls, and the available memory is allowed to vary.

On Windows, GetVersionEx and VerifyVersionInfo answer 6.2 (Windows 8) on any Windows 10 or 11 unless the executable has a manifest declaring the newer versions. A library does not control the manifest of the program that hosts it, so the version comes from RtlGetVersion in ntdll.dll, which answers the truth without a manifest. The suite checks it against the registry, a third path.

Container detection looks for traces (a file, a cgroup line, a variable). An environment that leaves none is invisible, so a true iContainer is reliable and false means "no trace found". Same rule as the hypervisor bit in SCpuFacts.

struct

SOsFacts

Ethereal::Platform#
C++
struct   SOsFacts   final
{
    /// @brief  'sizeof( SOsFacts )'.
    ETL_UINT32        iStructSize = sizeof( SOsFacts );

    /// @brief  Version numbers. On Linux this is the kernel version, not the distribution.
    ETL_UINT32        uMajor = 0;
    ETL_UINT32        uMinor = 0;
    ETL_UINT32        uBuild = 0;

    /// @brief  Fourth part. The UBR on Windows, the number after the patch on Linux.
    ETL_UINT32        uRevision = 0;

    /// @brief  "Windows", "Linux", "macOS".
    ETL_CHAR        aName[ 16 ] = {};

    /// @brief  The version as text, as the system writes it.
    ///
    /// @details  On Windows it is "10.0.19045.5011". On Linux it is the raw kernel
    ///            string, which often has more than numbers
    ///            ("6.6.87.2-microsoft-standard-WSL2"). That is on purpose: the suffix
    ///            identifies the environment better than any number.
    ETL_CHAR        aVersion[ 96 ] = {};

    /// @brief  The distribution, on Linux. Empty elsewhere and when it cannot be found.
    ETL_CHAR        aDistro[ 64 ] = {};

    /// @brief  Architecture of the machine: "x86_64", "x86", "arm64", "arm".
    ///
    /// @details  The machine, not this binary. A 32 bit process on a 64 bit machine
    ///            reads "x86_64" here, which is what a caller deciding whether it can
    ///            open a process of the other size needs.
    ETL_CHAR        aArch[ 16 ] = {};

    /// @brief  Page size, in bytes.
    ETL_UINT32        uPageSize = 0;

    /// @brief  Large page size, in bytes. Zero when the system does not offer them.
    ETL_UINT32        uLargePageSize = 0;

    /// @brief  Granularity of reserved address space.
    ///
    /// @details  64 KiB on Windows, which is not the page size: reserving in 4 KiB
    ///            steps wastes fifteen sixteenths of each reservation. On Linux it is
    ///            the page size.
    ETL_UINT32        uAllocationGranularity = 0;

    /// @brief  Physical memory of the machine, in bytes.
    ETL_UINT64        uPhysicalTotal = 0;

    /// @brief  Number of NUMA nodes. One on a common machine, zero means "not found".
    ETL_UINT32        uNumaNodes = 0;

    /// @brief  Whether a container trace was found. False means "no trace found".
    ETL_INT32        iContainer = 0;

    /// @brief  Which trace: "docker", "wsl", "lxc", "podman". Empty when none.
    ETL_CHAR        aContainer[ 16 ] = {};
};

What does not change in the system while this process lives.

function

OsFacts

Ethereal::Platform#
const SOsFacts & OsFacts() noexcept;

The system facts, computed once.

Always the same reference, and the content does not change. Does not allocate, and does no work after the first call.

function

AvailablePhysicalMemory

Ethereal::Platform#
ETL_UINT64 AvailablePhysicalMemory() noexcept;

Physical memory available now, in bytes.

Not a fact, so it is not in the structure: it changes between two lines of code. The suite checks that the facts do not change and that this value may change.

Zero when the system does not answer.
Asks the system on every call. Does not allocate. Thread safety: full.

platform_common.hpp

#include <ethereal/cpp/platform/platform_common.hpp>

Status codes and capabilities of the Platform module.

Every function of the module either works or returns eNotSupported, and there is a compile time query (Compiled) and a runtime query (Supports) so the caller can branch before calling. The spec forbids silent degradation into an empty result: a Praetor detection that silently sees nothing is worse than one that reports it cannot run. A caller that looks for an injected module and gets "no modules" cannot tell "there is nothing" from "I could not look".

The rules:

  • An empty list only when there really is nothing.
  • Inability returns eNotSupported, always.
  • Lack of permission returns eAccessDenied, which is different: the caller can ask for privilege and retry.
  • Supports answers before the call, for callers that prefer to branch.
enum

EPlatformError

Ethereal::Platform#
C++
enum class   EPlatformError : ETL_INT32
{
    /// @brief  The query answered.
    eOk = 0,

    /// @brief  An argument has no usable value.
    eInvalidArgument,

    /// @brief  The space given by the caller does not fit the result.
    ///
    /// @details  The enumerating functions still report how many entries exist,
    ///            so the caller sizes the buffer once and reuses it, as the spec
    ///            asks of the scan loop.
    eBufferTooSmall,

    /// @brief  This platform does not offer the information. This is not a failure.
    ///
    /// @details  It is the value that prevents silent degradation (see the file
    ///            header).
    eNotSupported,

    /// @brief  The system refused for lack of permission.
    ///
    /// @details  Distinct from eNotSupported on purpose: the information exists
    ///            and another privilege level would reach it. Mixing the two would
    ///            make the caller give up when asking for more was enough.
    eAccessDenied,

    /// @brief  The target went away in the middle of the query.
    ///
    /// @details  Process enumeration chases something that changes while it is
    ///            looked at. A process that dies during the walk is not a defect.
    eGone,

    /// @brief  The system refused for another reason.
    eSystemError,

    /// @brief  What was asked for does not exist.
    ///
    /// @details  Distinct from its three neighbors:
    ///            - eNotSupported: this platform cannot answer, retrying does not help.
    ///            - eAccessDenied: it exists, another privilege would reach it.
    ///            - eGone: it existed and went away while it was looked at.
    ///            - eNotFound: there is none. The requested file is not there, or no
    ///              section with that name exists in the image. No privilege or
    ///              platform changes that.
    ///
    ///           Added at the end, never in the middle: these values cross the ABI
    ///            boundary and reordering them would break every linked binary.
    eNotFound,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong in a platform query.

function

PlatformErrorName

Ethereal::Platform#
const ETL_CHAR * PlatformErrorName( EPlatformError eError ) noexcept;

Name of the status, for diagnostic messages. Never returns null.

enum

ECapability

Ethereal::Platform#
C++
enum class   ECapability : ETL_UINT32
{
    /// @brief  Enumerate the modules loaded in the calling process.
    eEnumModulesSelf = 0,

    /// @brief  Enumerate the modules of another process.
    eEnumModulesOther,

    /// @brief  Enumerate the processes of the machine.
    eEnumProcesses,

    /// @brief  Enumerate the threads of a process.
    eEnumThreads,

    /// @brief  Walk the memory regions of a process.
    eEnumMemoryRegions,

    /// @brief  Read the memory of another process.
    eReadRemoteMemory,

    /// @brief  Resolve an exported symbol without going through the loader.
    eResolveExport,

    /// @brief  Read the code signature of an image.
    eCodeSignature,

    /// The values below were added at the end, never in the middle, for the same
    /// reason as the status codes: they cross the ABI boundary.

    /// @brief  Suspend and resume a thread.
    eSuspendThread,

    /// @brief  Capture the register context of a thread.
    eThreadContext,

    /// @brief  Lock pages in physical memory.
    eLockMemory,

    /// @brief  Enumerate the disks of the machine.
    eEnumDisks,

    /// @brief  Enumerate the network interfaces.
    eEnumNetworkInterfaces,

    /// @brief  Compute the hardware fingerprint.
    eHardwareFingerprint,

    /// @brief  Number of capabilities. Not a capability.
    eCount

};

What can be asked before calling.

function

Compiled

Ethereal::Platform#
constexpr bool Compiled( const ECapability eWhat ) noexcept

Whether this build has the code for a capability. Answered at compile time.

The answer is compiled in, the system is not asked. It lets the caller drop the useless branch from the binary, so a scan loop does not pay for a call that cannot work on every pass.

Not the same as Supports: this asks whether the code exists, Supports asks whether it works on this machine, now, with this privilege.

eWhat
The capability.
true when the code for it is compiled in.
function

Supports

Ethereal::Platform#
bool Supports( const ECapability eWhat ) noexcept;

Whether this machine, now, with this privilege, can do it.

May be stricter than Compiled: the code exists and the system refuses. It may also be more expensive to answer, so the result is computed once and cached.

eWhat
The capability.
true when the capability works.
function

CapabilityName

Ethereal::Platform#
const ETL_CHAR * CapabilityName( const ECapability eWhat ) noexcept;

Name of the capability, for reports. Never returns null.

privileges.hpp

#include <ethereal/cpp/platform/privileges.hpp>

Process identity, privileges and debugger signals.

Unlike the rest of the module, nothing here is cached. CpuFacts and OsFacts compute once because the processor and the system do not change while the process lives. Identity does: a process can drop privilege (setuid on POSIX, AdjustTokenPrivileges on Windows), and a well written program does exactly that after using what it needed. A cached answer would say "I am root" to a process that just stopped being root, and make the caller try what it no longer can. So QueryToken asks the system on every call.

About debugger detection, the spec asks this part to be "honest about its limitations". None of these probes detects a debugger that does not want to be detected. They all read a signal the system publishes (a flag in the PEB, a line in /proc, the result of a call), and any of them can be erased: some debugger extensions clear the PEB flag before the program starts, and on Linux it is enough for the debugger not to use ptrace.

What it is good for: logging and diagnostics ("this crash report came from a session with a debugger attached"), deciding whether to print to the debugger instead of a file, and raising the cost for someone who is not trying to hide. It does not protect anything. "if( DebuggerPresent() ) exit()" as anti tampering is a paper lock. The function also returns which signals fired: one signal out of four means something other than a common debugger.

enum

EIntegrityLevel

Ethereal::Platform#
C++
enum class   EIntegrityLevel : ETL_UINT8
{
    /// @brief  Could not find out.
    eUnknown = 0,

    /// @brief  The system has no such concept.
    eNotApplicable = 1,

    /// @brief  No trust at all. Typical of a browser content process.
    eUntrusted = 2,

    /// @brief  Low. Sandbox.
    eLow = 3,

    /// @brief  Medium. The normal level of a user program.
    eMedium = 4,

    /// @brief  High. Elevated.
    eHigh = 5,

    /// @brief  System. Service.
    eSystem = 6
};

How much the system trusts this process.

A Windows concept. On POSIX there is only eNotApplicable. Inventing an equivalent ("root is high, a user is medium") would be a bad translation: the two models answer different questions.

function

IntegrityLevelName

Ethereal::Platform#
const ETL_CHAR * IntegrityLevelName( EIntegrityLevel eLevel ) noexcept;

Name of the level, for reports. Never returns null.

struct

STokenInfo

Ethereal::Platform#
C++
struct   STokenInfo   final
{
    /// @brief  'sizeof( STokenInfo )'.
    ETL_UINT32        iStructSize = sizeof( STokenInfo );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  The identifier, in the form the system uses.
    ///
    /// @details  On Windows it is the SID as text ("S-1-5-21-..."). On POSIX it is the
    ///            effective user number in decimal. They are different on purpose: a
    ///            caller comparing identities must know which system it talks to.
    ETL_CHAR        aIdentity[ 96 ] = {};

    /// @brief  Account name. Empty when it cannot be found.
    ETL_CHAR        aAccount[ 64 ] = {};

    /// @brief  The POSIX ids. Zero on Windows, where they do not exist.
    ETL_UINT32        uRealUid = 0;
    ETL_UINT32        uEffectiveUid = 0;
    ETL_UINT32        uRealGid = 0;
    ETL_UINT32        uEffectiveGid = 0;

    /// @brief  Whether this process runs with administrative privilege now.
    ///
    /// @details  On Windows it is the token elevation. On POSIX it is the effective
    ///            user being zero. Not the same question, but the answer serves the
    ///            same use: "can I do what only the administrator does?".
    ETL_INT32        iElevated = 0;

    /// @brief  Whether this process could elevate if it asked.
    ///
    /// @details  On Windows: the token is split, that is, the user belongs to the
    ///            administrators and the system gave it the limited version. On POSIX:
    ///            the binary has the setuid bit, the case where the real and the
    ///            effective user differ.
    ///
    ///           False does not promise that elevation will fail, since a user may know
    ///            the password of another account. True means "there is a path that
    ///            does not ask for another identity".
    ETL_INT32        iCanElevate = 0;

    /// @brief  How much the system trusts this process. See EIntegrityLevel.
    EIntegrityLevel    eIntegrity = EIntegrityLevel::eUnknown;

    /// @brief  Explicit padding.
    ETL_UINT8        aPad2[ 7 ] = {};

    /// @brief  Effective capabilities, on POSIX. Zero on Windows.
    ///
    /// @details  The capget mask. A common process has zero. One with CAP_SYS_PTRACE
    ///            can read the memory of another process without being its parent.
    ETL_UINT64        uCapabilities = 0;
};

Who this process is, and what it is allowed to do.

function

QueryToken

Ethereal::Platform#
EPlatformError QueryToken( STokenInfo * pOut ) noexcept;

Measures the identity of this process now.

Not cached (see the file header). Every call asks the system.

pOut
Where to write. Must not be null.
eOk, or what prevented it.
Does not allocate. Thread safety: full.
const

ETL_DBG_SIGNAL_PEB

Ethereal::Platform#
constexpr ETL_UINT32 ETL_DBG_SIGNAL_PEB = 1u << 0;

The flag the system sets in the process block (Windows).

const

ETL_DBG_SIGNAL_REMOTE

Ethereal::Platform#
constexpr ETL_UINT32 ETL_DBG_SIGNAL_REMOTE = 1u << 1;

The direct question to the system: is there a debugger in another process? (Windows)

const

ETL_DBG_SIGNAL_TRACER

Ethereal::Platform#
constexpr ETL_UINT32 ETL_DBG_SIGNAL_TRACER = 1u << 2;

The 'TracerPid' line of '/proc/self/status' (POSIX).

const

ETL_DBG_SIGNAL_HEAP

Ethereal::Platform#
constexpr ETL_UINT32 ETL_DBG_SIGNAL_HEAP = 1u << 3;

The heap flags the system sets when a debugger is present (Windows).

function

DebuggerPresent

Ethereal::Platform#
bool DebuggerPresent( ETL_UINT32 * pSignalsOut = nullptr ) noexcept;

Whether there is a debugger signal in this process.

Read the file header before using this to decide anything. True is reliable, false means "no signal found". None of these probes detects a debugger that hides, and none of them protects anything.

pSignalsOut
Optional. Receives the combination of ETL_DBG_SINAL_* that fired. Useful to tell a common debugger (several signals) from something trying to hide (only one).
true when at least one signal fired.
Does not allocate. Thread safety: full.

processes.hpp

#include <ethereal/cpp/platform/processes.hpp>

The processes of the machine.

This walk goes to the system a lot, the opposite of EnumModulesSelf. The process list lives in the kernel and none of it is mapped in this process. What can be done is to go few times, and that is where the platforms really differ:

  • On Windows, NtQuerySystemInformation returns all processes (and the threads of each) in one buffer, in one call. The spec asks for it by name and forbids CreateToolhelp32Snapshot in the hot loop, since it copies the state of the whole system to answer the same question.
  • On Linux there is no equivalent: /proc is a directory, and each process costs opening, reading and closing at least one file, about three calls per process. The walk counts its calls, but LastSyscallCount (modules.hpp) only reports the module walks, so this count is not exposed yet. The spec budget for this function is two milliseconds on a typical desktop, not the hundred microseconds of the hot path. They are different problems.

Zero allocations still holds, and that shapes the signature. NtQuerySystemInformation needs a large buffer whose size is only known by asking. So the caller's arena serves both: the raw system data first, the converted text after it. That is why pNeeded can ask for hundreds of KiB here and a few dozen bytes in EnumModulesSelf. The two pass protocol (ask with an empty arena, get the total, reserve once, reuse forever) is what a scan loop wants.

A process can die in the middle of the walk. One that dies between being listed and being queried is not a defect: its entry comes out with what could be read and the walk goes on. The whole walk must not fail because of one process.

struct

SProcessInfo

Ethereal::Platform#
C++
struct   SProcessInfo   final
{
    /// @brief  'sizeof( SProcessInfo )'. Lets the structure grow without breaking compiled callers.
    ETL_UINT32        iStructSize = sizeof( SProcessInfo );

    /// @brief  Session the process belongs to. Zero when the platform has no sessions.
    ETL_UINT32        uSessionId = 0;

    /// @brief  Process identifier.
    ETL_UINT64        uPid = 0;

    /// @brief  Identifier of the parent. Zero when unknown.
    ETL_UINT64        uParentPid = 0;

    /// @brief  Creation time, in nanoseconds since the system origin.
    ///
    /// @details  Not calendar time, and the origin differs between platforms. It is
    ///            for telling processes apart: two processes with the same identifier
    ///            at different moments have different creation times, which prevents
    ///            mixing them up when the system reuses the number.
    ETL_UINT64        uCreateTimeNs = 0;

    /// @brief  Number of threads.
    ETL_UINT32        uThreadCount = 0;

    /// @brief  Length of the name, in bytes.
    ETL_UINT32        uNameLength = 0;

    /// @brief  Short name, in UTF-8, inside the caller's arena.
    const ETL_CHAR *    pName = nullptr;

    /// @brief  Image path, in UTF-8, or empty when it cannot be read.
    ///
    /// @details  Reading the path of another process needs privilege on almost every
    ///            platform. Without it this field is empty, uPathLength is zero and the
    ///            rest of the entry is still valid. Empty means "could not read", not
    ///            "has none". A caller that must tell them apart uses the
    ///            eAccessDenied of a direct query to the process.
    const ETL_CHAR *    pPath = nullptr;

    /// @brief  Length of the path, in bytes.
    ETL_UINT32        uPathLength = 0;

    /// @brief  Explicit padding. See section 7 of the conventions.
    ETL_UINT32        uPadding = 0;
};

One process of the machine.

alias

bool

Ethereal::Platform#
using FVisitProcess = bool ( * )( const SProcessInfo & Info, void * pUser );

Called for each process. Returning false stops the walk.

function

EnumProcesses

Ethereal::Platform#
EPlatformError EnumProcesses( FVisitProcess pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the processes of the machine.

pVisit
Called for each process. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Work and text arena. See the file header.
uArena
Size of the arena, in bytes.
pNeeded
Receives the bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied, eSystemError or eNotSupported.
Does not allocate. Thread safety: full.
function

EnumProcesses

Ethereal::Platform#
EPlatformError EnumProcesses( SProcessInfo * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

pCount is only valid when the walk actually ran, and that differs between platforms. On Linux the walk goes through /proc even with an empty arena (only the text stops fitting), so the count comes in the first call. On Windows it does not: the system query needs the work buffer before returning anything, and with an empty arena it only says how much space it wants. The count comes in the second call.

The protocol that works on both: ask with an empty arena, read pNeeded, reserve, call again, and only then read the count.

pOut
Array that receives the processes. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many processes exist, not how many fit.
pArena
Work and text arena.
uArena
Size of the arena, in bytes.
pNeeded
Receives the bytes the whole walk needs.
eOk, eBufferTooSmall, eAccessDenied, eSystemError or eNotSupported.
function

CurrentProcessId

Ethereal::Platform#
ETL_UINT64 CurrentProcessId() noexcept;

Identifier of this process.

function

CurrentParentProcessId

Ethereal::Platform#
ETL_UINT64 CurrentParentProcessId() noexcept;

Identifier of the process that created this one.

May return zero when the parent already died. That is the normal case of a process adopted by the system init, not a failure.

remote_memory.hpp

#include <ethereal/cpp/platform/remote_memory.hpp>

Reading and writing the memory of another process.

The batch exists because it changes the order of magnitude. The spec: "Batched multi-range read in a single call where the platform supports iovec, because that is a large win when sampling many addresses." A check that samples fifty scattered addresses should not pay fifty boundary crossings. On Linux process_vm_readv takes a vector of ranges and crosses once. On Windows there is no equivalent and the batch is a loop, but the signature is the same, so the caller is written once. The gain measured on the bench is in the module report.

Reading this process also goes through here, on purpose. With uPid zero the target is this process. A memcpy on an invalid address kills the process, and these functions return an error. A scan for what should not be there works with addresses that may no longer exist, and needs a read that fails instead of crashing.

A partial read is a result, not a failure. A range that starts in mapped memory and ends outside reads the start and stops. pReadOut says how much came out and the status says it was not all. In a scan, the start of the region is often what matters.

Permission is the normal case. Reading another process needs privilege on every serious platform. On Linux the YAMA ptrace_scope refuses by default even between processes of the same user, unless one is the parent of the other. So eAccessDenied is the first thing a caller must handle.

struct

SReadRange

Ethereal::Platform#
C++
struct   SReadRange   final
{
    /// @brief  'sizeof( SReadRange )'.
    ETL_UINT32        iStructSize = sizeof( SReadRange );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Where to read, in the address space of the target process.
    ETL_UINT64        uAddress = 0;

    /// @brief  Where to write, in the address space of this process.
    void *            pOut = nullptr;

    /// @brief  Bytes to request.
    ETL_UINT64        uSize = 0;

    /// @brief  Receives the bytes read. Zero when the range failed.
    ETL_UINT64        uReadOut = 0;
};

One range to read in a batch.

function

ReadRemoteMemory

Ethereal::Platform#
EPlatformError ReadRemoteMemory( const ETL_UINT64 uPid, const ETL_UINT64 uAddress, void * pOut, const ETL_UINT64 uSize, ETL_UINT64 * pReadOut ) noexcept;

Reads one range of the memory of a process.

uPid
Zero means this process.
uAddress
Where to read, in the target.
pOut
Where to write.
uSize
Bytes to read.
pReadOut
Receives the bytes read. Must not be null.
eOk when everything was read, eBufferTooSmall when only a part was read, eAccessDenied, eGone or eNotSupported.
function

ReadRemoteMemoryBatch

Ethereal::Platform#
EPlatformError ReadRemoteMemoryBatch( const ETL_UINT64 uPid, SReadRange * pRanges, const ETL_UINT64 uCount, ETL_UINT64 * pOkCount ) noexcept;

Reads several ranges at once.

A range that fails does not bring the others down. In a scan, half of the sampled addresses often point to memory that changed since the list was built, and giving up on the whole batch would make the function useless in its own use case.

uPid
Zero means this process.
pRanges
The ranges. Each receives its own uReadOut.
uCount
Number of ranges.
pOkCount
Receives the number of ranges read in full.
eOk when all ranges were read in full, eBufferTooSmall when some range was partial or failed.
function

WriteRemoteMemory

Ethereal::Platform#
EPlatformError WriteRemoteMemory( const ETL_UINT64 uPid, const ETL_UINT64 uAddress, const void * pIn, const ETL_UINT64 uSize, ETL_UINT64 * pWrittenOut ) noexcept;

Writes into the memory of a process.

It exists because the spec asks for it, and the module is still about facts: it injects nothing, hooks nothing and decides nothing. Whoever uses it already had the privilege to use the system call.

uPid
Zero means this process.
uAddress
Where to write, in the target.
pIn
What to write.
uSize
Bytes to write.
pWrittenOut
Receives the bytes written. Must not be null.
eOk, eBufferTooSmall when only a part was written, eAccessDenied, eSystemError or eNotSupported.
function

BatchIsAtomic

Ethereal::Platform#
bool BatchIsAtomic() noexcept;

Whether the batch crosses the boundary once on this platform.

True on Linux, where process_vm_readv takes a vector of ranges. False on Windows, where the batch is a loop. Useful to size the batch: where it is not atomic, there is no gain in packing a thousand addresses in one call.

threads.hpp

#include <ethereal/cpp/platform/threads.hpp>

The threads of a process.

On Windows the threads come with the processes. NtQuerySystemInformation( SystemProcessInformation ), the same query EnumProcesses uses, returns the thread array of each process right after it. Enumerating threads costs no new query, only reading more bytes of a buffer already at hand. On Linux it is the opposite: each thread is a directory in /proc/<pid>/task/, and each costs opening, reading and closing a file. So the spec budget (two milliseconds for processes and threads) means very different things on the two systems, and the walk here is per process instead of global: all threads of the machine on Linux would be thousands of files.

The asymmetry flips for a single process. Measured on the bench, for the threads of one process: Linux, 3 threads in 0.032 ms; Windows, 6 threads in 3.5 ms. A hundred times, and not an implementation defect: Windows has no per process query, the only way is to ask for the list of the whole system and find the process in it. Toolhelp, the alternative, also snapshots the whole machine and copies more. For a scan loop: on Windows, the threads of several processes should come from one process walk, not one call per process. On Linux the opposite is cheaper. Only measuring shows this.

The state is the least reliable field. A thread changes state between the system answering and the caller reading. The field is for statistics and diagnostics, not for decisions. The two platforms also disagree on what the states mean, so only the smallest set that means the same on both is offered.

enum

EThreadState

Ethereal::Platform#
C++
enum class   EThreadState : ETL_UINT32
{
    /// @brief  Unknown, or the system does not say.
    eUnknown = 0,

    /// @brief  Running on a processor.
    eRunning,

    /// @brief  Ready, waiting for a processor.
    eReady,

    /// @brief  Waiting for something other than a processor.
    eWaiting,

    /// @brief  Terminated, but still listed.
    eTerminated
};

What the thread was doing when it was looked at.

struct

SThreadInfo

Ethereal::Platform#
C++
struct   SThreadInfo   final
{
    /// @brief  'sizeof( SThreadInfo )'.
    ETL_UINT32        iStructSize = sizeof( SThreadInfo );

    /// @brief  The state, with the caveat in the file header.
    EThreadState    eState = EThreadState::eUnknown;

    /// @brief  Thread identifier.
    ETL_UINT64        uTid = 0;

    /// @brief  Process the thread belongs to.
    ETL_UINT64        uOwnerPid = 0;

    /// @brief  Where the thread started running. Zero when the system does not say.
    ///
    /// @details  The field that matters most in a check: a thread whose start address
    ///            falls outside every loaded module did not come from code mapped by a
    ///            loader. On Linux it is not available without privilege and is zero,
    ///            which means "could not find out", as everywhere in this module.
    ETL_UINT64        uStartAddress = 0;

    /// @brief  Processor time spent in user mode, in nanoseconds.
    ETL_UINT64        uUserTimeNs = 0;

    /// @brief  Processor time spent in kernel mode, in nanoseconds.
    ETL_UINT64        uKernelTimeNs = 0;

    /// @brief  Priority, on the system scale. Not comparable between systems.
    ETL_INT32        iPriority = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Top of the stack of this thread. Zero when the system does not say.
    ///
    /// @details  The stack grows down, so the base is the higher number. iStackBase is
    ///            the address right above the first usable byte, iStackLimit the lowest
    ///            committed one. Between them is what the thread can use without the
    ///            system committing more pages.
    ///
    ///           In a check: a return address outside this range did not come from the
    ///            stack of this thread, and a stack whose base falls in a private
    ///            executable region is a hand built thread.
    ///
    ///           Zero on Linux, meaning "could not find out". /proc gives the stack
    ///            limit only for the main thread, a number that would be right for one
    ///            entry and wrong for the others, which is worse than none.
    ETL_UINT64        iStackBase = 0;

    /// @brief  Committed bottom of the stack. Zero when the system does not say.
    ///
    /// @details  See iStackBase, which explains both.
    ETL_UINT64        iStackLimit = 0;
};

A thread.

alias

bool

Ethereal::Platform#
using FVisitThread = bool ( * )( const SThreadInfo & Info, void * pUser );

Called for each thread. Returning false stops the walk.

function

EnumThreads

Ethereal::Platform#
EPlatformError EnumThreads( const ETL_UINT64 uPid, FVisitThread pVisit, void * pUser, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

Walks the threads of a process.

uPid
Zero means this process.
pVisit
Called for each thread. Must not be null.
pUser
Passed back to the visitor untouched.
pArena
Work arena (Windows uses it for the system list).
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the walk needs.
eOk, eBufferTooSmall, eGone, eSystemError or eNotSupported.
function

EnumThreads

Ethereal::Platform#
EPlatformError EnumThreads( const ETL_UINT64 uPid, SThreadInfo * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pCount, ETL_CHAR * pArena, const ETL_UINT64 uArena, ETL_UINT64 * pNeeded ) noexcept;

The same walk, filling an array of the caller.

The spec asks for both forms: "enumeration APIs come in two forms: a callback form that visits entries with zero buffering, and a span form that fills a caller buffer. There is no form that returns a container." This one was missing, and without it the C layer had to send a function pointer across the boundary and back for each entry, which callers from C# or Rust should not have to write.

uPid
Zero means this process.
pOut
Where to write. May be null when uOut is zero.
uOut
Capacity of the array.
pCount
Receives how many threads exist, not how many fit.
pArena
Work arena.
uArena
Size of the arena, in bytes.
pNeeded
Receives the arena bytes the walk needs.
eOk, eBufferTooSmall, eGone, eSystemError or eNotSupported.
function

CurrentThreadId

Ethereal::Platform#
ETL_UINT64 CurrentThreadId() noexcept;

Identifier of this thread.

function

SetThreadName

Ethereal::Platform#
EPlatformError SetThreadName( const ETL_CHAR * pName, const ETL_UINT64 uLen ) noexcept;

Names this thread, for the debugger and the system.

The length limit belongs to the system, and it truncates silently. On Linux the name fits fifteen characters plus the terminator, and the kernel truncates without warning. Here a name that is too long is refused with eInvalidArgument, because a cut name passes for a name and a later search for it finds nothing.

pName
Text in UTF-8. Does not need a terminating zero.
uLen
Length, in bytes.
eOk, eInvalidArgument, eSystemError or eNotSupported.
function

GetThreadName

Ethereal::Platform#
EPlatformError GetThreadName( ETL_CHAR * pOut, const ETL_UINT64 uOut, ETL_UINT64 * pWritten ) noexcept;

Reads the name of this thread.

pOut
Where to write, with the terminator. At least THREAD_NAME_MAX bytes.
uOut
Size of pOut, in bytes.
pWritten
Receives the length written, without the terminator. May be null.
eOk, eInvalidArgument, eSystemError or eNotSupported.
const

THREAD_NAME_MAX

Ethereal::Platform#
constexpr ETL_UINT64 THREAD_NAME_MAX = 32u;

Bytes that fit any thread name, with the terminator.

function

SuspendThread

Ethereal::Platform#
EPlatformError SuspendThread( const ETL_UINT64 uTid, ETL_UINT32 * pPrevCount ) noexcept;

Suspends a thread. It cannot be the calling thread.

Suspending the calling thread is an instant deadlock: the call would never return to resume it. So asking for it returns eInvalidArgument.

Suspensions stack on Windows. Calling twice needs two resumes, and the system returns the previous count. Suspending in a loop and resuming once leaves the thread suspended forever.

uTid
The thread. Zero is refused on purpose.
pPrevCount
Receives the previous suspend count, when the system publishes it. May be null. Always zero on Linux, where the stop signal is not counted.
eOk, eInvalidArgument, eAccessDenied, eNotFound, eSystemError or eNotSupported.
function

ResumeThread

Ethereal::Platform#
EPlatformError ResumeThread( const ETL_UINT64 uTid, ETL_UINT32 * pPrevCount ) noexcept;

Resumes a thread suspended by SuspendThread.

uTid
The thread.
pPrevCount
Receives the previous suspend count. One means this call is the one that released it.
eOk, eInvalidArgument, eAccessDenied, eNotFound, eSystemError or eNotSupported.
struct

SThreadContext

Ethereal::Platform#
C++
struct   SThreadContext   final
{
    /// @brief  'sizeof( SThreadContext )'.
    ETL_UINT32        iStructSize = sizeof( SThreadContext );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Program counter. 'Rip' on x86-64, 'Pc' on AArch64.
    ETL_UINT64        uInstructionPointer = 0;

    /// @brief  Top of the stack. 'Rsp' / 'Sp'.
    ETL_UINT64        uStackPointer = 0;

    /// @brief  Frame base. 'Rbp' / 'Fp' (x29).
    ETL_UINT64        uFramePointer = 0;

    /// @brief  Processor flags. 'EFlags' / 'Cpsr'.
    ETL_UINT64        uFlags = 0;
};

The registers of a thread, the part common to x86-64 and AArch64.

Not the full context, on purpose. The Windows CONTEXT has the floating point registers, the debug registers and the extended state, and copying all that into a portable structure would invent a shape that matches neither system.

What is here is what a check uses: where the thread is executing and where its stack is. A program counter outside every loaded module is the same question SThreadInfo::uStartAddress answers for the start of the thread, answered for now.

function

CaptureThreadContext

Ethereal::Platform#
EPlatformError CaptureThreadContext( const ETL_UINT64 uTid, SThreadContext * pOut ) noexcept;

Reads the registers of a suspended thread.

The thread must be suspended, and this call does not suspend it. Reading the context of a running thread returns values that were no longer valid when the call returned, and Windows does not even prevent it: it returns something, and that something is noise. It does not suspend internally because callers usually read several things with the thread stopped, and suspending and resuming on each read would multiply the window in which the process is half frozen.

Windows only. On Linux, reading the registers of another thread needs ptrace, which needs being the tracer, and a process cannot trace itself. There is no path for the case this module serves, so it returns eNotSupported, and ECapability::eThreadContext says so before the call.

uTid
The thread. Zero is refused.
pOut
Receives the registers. Must not be null.
eOk, eInvalidArgument, eAccessDenied, eNotFound, eSystemError or eNotSupported.