ttypt/xy.h(3)libxylem

NAME

ttypt/xy.h - Modding and extensibility API.

SYNOPSIS

#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <ttypt/xy-pp.h>
#include <ttypt/stele.h>

Data Structures

struct xy_adapter_t

Adapter for dispatching hook calls to modules.

Macros

#define XY_MAX_RET_SIZE 4096

Maximum size for return types in hooks.

#define XY_INVALID ((unsigned) -1)

Invalid hook ID returned when lookup fails.

#define UNUSED __attribute__((unused))

Mark intentionally-unused symbols or parameters.

#define XY_OK 0

Success return code.

#define XY_ERR_NOTFOUND -1

Error: Module or hook not found.

#define XY_ERR_INVALID -2

Error: Invalid argument passed to function.

#define XY_ERR_TOOBIG -3

Error: Return type exceeds XY_MAX_RET_SIZE / no slot available.

#define XY_ERR_INIT -4

Error: Library initialization failed.

#define XY_ERR_EPERM -5

Error: Operation not permitted (deny, claim, unload veto, etc.).

#define XY_ERR_ABI -6

Error: Module was built against a different xy_ctx ABI.

#define XY_MODULE_API __attribute__((visibility('default')))

Export symbol from module (POSIX).

#define XY_DECL(ftype, fname, ...)

Declare a hook that can be called like a normal function.

#define XY_DEF(ftype, fname, ...)

Define the canonical adapter for a normal-function hook.

#define XY_IMPL(ftype, fname, ...)

Define a module listener implementation for a hook.

#define XY_LISTENER_TAG(ftype, fname, tag, ...)

Define a tagged module listener implementation for a hook.

#define XY_CALL(retp, fname, ...)

Call a mod hook by name within the current thread-local region.

#define XY_REGION_ROOT ((uint64_t)0)
#define XY_REGION_INVALID ((uint64_t)-1)

Context ABI tripwire
The host fills a module-local xy_ctx by writing sizeof(struct xy_ctx) bytes into it, using the size the host was compiled with. If the module was built against a different header its object may be smaller, and the tail of that write lands in whatever follows it in the module's BSS. This is invisible at the source level โ€” a stale module still loads, still returns XY_OK, and still has working function pointers for every field both versions share โ€” so the only symptom is corruption of an unrelated library, some distance away.

Two mechanisms prevent that, and both must be used:

1.
XY_CTX_SIZE is a hard _Static_assert on this struct. Adding or removing a field fails the build of everything that includes this header, host and module alike, until the constant is deliberately bumped. That makes a layout change impossible to ship silently.
2.
XY_CTX_ABI_VER is exchanged at load time. A module must export xy_ctx_abi() (xy-mod.h emits it automatically); if the descriptor does not match the host's exactly, the load is refused with XY_ERR_ABI. This catches the case (1) cannot: a module compiled earlier against an older header and still sitting on disk.

Note that (1) alone is not enough, because external/axil-* modules build against the system-installed header tree rather than this submodule, so a site make does not rebuild them.

#define XY_CTX_ABI_VER 3

ABI generation of xy_ctx. Bump on every layout change.

#define XY_CTX_SIZE 184

sizeof(struct xy_ctx) as asserted by this header.

#define XY_CTX_ABI_DESC (((uint64_t)(XY_CTX_ABI_VER) << 32) | (uint32_t)(XY_CTX_SIZE))

The value a module must export from xy_ctx_abi().

Typedefs

typedef void(* mod_cb_t) (void)

Module callback function type.

typedef int xy_deny_t(const char *what, xy_deny_type_t type)

Deny a hook or module within the caller's current region.

typedef int xy_claim_handler_fn_t(const char *module_path, uint8_t requested_bits, uint8_t *granted_bits, void *ud)

Claim handler type.

typedef int xy_require_claim_t(xy_claim_handler_fn_t *fn, void *ud)

Set or clear the claim gate on the caller's current region.

typedef int xy_region_each_fn_t(uint64_t child_id, uint8_t plen, void *ud)

Enumerate immediate child regions of the caller's current region.

typedef int xy_with_region_t(uint64_t region_id, uint8_t plen, xy_scope_fn_t *fn, void *ud)

Run fn with the caller's current region temporarily set to the region identified by (region_id, plen).

typedef uint64_t xy_current_region_t(void)

Return the id half of the caller's current region identity.

typedef uint8_t xy_current_region_plen_t(void)

Return the plen half of the caller's current region identity.

typedef int xy_region_exists_t(uint64_t region_id, uint8_t plen)

Test whether the region identified by (region_id, plen) exists and is addressable.

typedef int xy_claim_at_t(uint64_t id, uint8_t plen, xy_claim_handler_fn_t *fn, void *ud)

Create the region identified by (id, plen), or reuse it.

typedef uint64_t xy_region_at_t(uint64_t prefix_id, uint8_t plen, uint8_t *region_plen)

Find the deepest existing region whose prefix covers a point.

typedef int xy_call_self_t(void *retp, xy_adapter_t *adapter, void *args)

Dispatch to the caller's current region's own modules only.

typedef int xy_load_t(char *fname)

Load or reload a module into the caller's current region.

typedef int xy_unload_t(char *fname)

Unload a previously loaded module from the caller's current region.

typedef int xy_reload_t(char *fname)

Reload a module in place, preserving its dispatch position.

typedef void xy_shutdown_t(void)

Shutdown and unload all modules.

typedef int xy_errno_t(void)

Get last error code.

typedef const char * xy_strerror_t(int err)

Get human-readable error message.

Enumerations

enum xy_deny_type_t { XY_DENY_HOOK = 0, XY_DENY_MODULE = 1 }

Deny target (hook name or module path) selector.

Functions

struct __attribute__ ((packed)) xy_region_key

Region identity.

void xy_self_init_ctx (struct xy_ctx *ctx)

Register a module's xy context from a .init_array constructor.

uint64_t xy_ctx_abi (void)

Report this module's xy_ctx ABI generation and size.

int xy_load_mem (const xy_mem_mod_t *desc)

Load an in-memory module into the caller's current region.

int xy_register_mem_mod (const xy_mem_mod_t *desc)

Register a statically linked in-memory module descriptor for lazy resolution by xy_load().

Detailed Description

Modding and extensibility API.

Synopsis

XY_DEF(int, on_tick, int, dt);
on_tick(16);

Overview

libxylem provides a plugin/module system where:

Usage

1.
Host uses XY_DEF to define hook signatures
2.
Host loads modules via xy_load()
3.
Modules use XY_IMPL to implement hooks they provide
4.
Modules include xy-mod.h

Dependencies

Dependencies between modules are handled through the API:

Error Handling

Macro Definition Documentation

#define XY_CALL( retp, fname, ...)

Value:

    { \
    struct fname##_args args = { __VA_ARGS__ }; \
    xy_call(retp, &fname##_adapter, &args); \
}

Call a mod hook by name within the current thread-local region. This macro calls all modules that implement the named hook whose region is a descendant-or-equal of the caller's current region. The return value is from the last module that ran.

Parameters

retp Pointer to store return value
fname Hook function name
... Arguments to pass to the hook

Example:

int result;
XY_CALL(&result, on_tick, 16);

#define XY_CTX_ABI_DESC (((uint64_t)(XY_CTX_ABI_VER) << 32) | (uint32_t)(XY_CTX_SIZE))

The value a module must export from xy_ctx_abi(). Packs the ABI generation in the high 32 bits and the context size in the low 32, so one exported function carries the whole contract and the host can decode it for an actionable error message.

#define XY_DECL( ftype, fname, ...)

Value:

    typedef ftype fname##_t(XY_FA(__VA_ARGS__)); \
    _Pragma("GCC diagnostic push") \
    _Pragma("GCC diagnostic ignored \"-Wpedantic\"") \
    struct fname##_args { \
        XY_PG(__VA_ARGS__) \
    }; \
    _Pragma("GCC diagnostic pop") \
    static xy_adapter_t __xy_decl_##fname##_adapter = { \
        .name = XSTR(fname), \
        .arg_size = sizeof(struct fname##_args), \
        .ret_size = sizeof(ftype), \
        .hook_id = -1, \
    }; \
    static inline UNUSED \
    ftype fname(XY_FA(__VA_ARGS__)) { \
        ftype ret; \
        struct fname##_args args = { XY_DA(__VA_ARGS__) }; \
        __XY_DISPATCH(&ret, &__xy_decl_##fname##_adapter, &args); \
        return ret; \
    } \
    typedef int __xy_decl_##fname##_semicolon_eater_t

Declare a hook that can be called like a normal function. This is the preferred declaration form for call sites that should read as ordinary C. The generated inline function still routes through XY_CALL, so the current execution region is preserved.

Do not use this macro in the same translation unit that defines a listener for the same hook name with XY_IMPL; the listener should keep using XY_IMPL and dispatch recursively with XY_CALL when needed.

#define XY_DEF( ftype, fname, ...)

Define the canonical adapter for a normal-function hook. Use XY_DECL in shared headers; use XY_DEF in the one translation unit that emits the canonical adapter. XY_DEF is self-sufficient in definition TUs and also provides the ordinary call syntax there.

#define XY_ERR_ABI -6

Error: Module was built against a different xy_ctx ABI. Returned by xy_load() when the module's context object cannot be proven at least as large as the host's (see XY_CTX_ABI_VER and xy_ctx_abi()). This is deliberately a load-time refusal rather than a best-effort write: see the ABI note above struct xy_ctx for why the alternative is silent memory corruption.

#define XY_IMPL( ftype, fname, ...)

Define a module listener implementation for a hook. Use this in modules that implement hooks. The host dispatches to these listener functions when the matching hook is called.

Creates:

The hook is auto-registered when the module loads.

Parameters

ftype Return type (e.g., int, void)
fname Function name (e.g., on_tick)
... Argument types and names (e.g., int, dt)

Example:

XY_IMPL(int, on_tick, int, dt);
int on_tick(int dt) { return dt + 1; }

#define XY_LISTENER_TAG( ftype, fname, tag, ...)

Define a tagged module listener implementation for a hook. Emits static functions and adapters tagged with tag so that multiple listeners for the same hook can be compiled into the same library or WASM reactor without linker symbol collisions.

#define XY_MAX_RET_SIZE 4096

Maximum size for return types in hooks. Return types larger than this will cause a compile-time static assertion when using XY_DEF or XY_IMPL.

#define XY_REGION_INVALID ((uint64_t)-1)

Sentinel returned when region allocation fails.

#define XY_REGION_ROOT ((uint64_t)0)

Root region โ€” ancestor of all regions. Passing this to xy_call dispatches to every module regardless of its region.

Typedef Documentation

typedef void(* mod_cb_t) (void)

Module callback function type. Used for mod_auto_init(), xy_install()

typedef int xy_call_self_t(void *retp, xy_adapter_t *adapter, void *args)

Dispatch to the caller's current region's own modules only. The exact-region counterpart of xy_call(). xy_call() reaches the current region's whole subtree; this reaches only the modules loaded directly into the current region โ€” no descendant region, and no ancestor.

It exists so an ancestor walk gives each region one observable turn instead of re-running every level's entire subtree once per step. Deny checks and xy_last() predecessor semantics are identical to xy_call()'s: a listener still sees its predecessor's return value, and a deny from any ancestor still refuses the whole dispatch with XY_ERR_EPERM.

Parameters

retp Out-param for the last listener's return value.
adapter The hook adapter.
args Hook arguments.

Returns

XY_OK, XY_ERR_NOTFOUND if no listener in this exact region ran (an empty dispatch, which is not the same as a listener returning zero โ€” read xy_errno() to tell them apart), or another XY_ERR_*.

typedef int xy_claim_at_t(uint64_t id, uint8_t plen, xy_claim_handler_fn_t *fn, void *ud)

Create the region identified by (id, plen), or reuse it. The engine-facing creation primitive: it names the region outright instead of waiting for a module to claim bits, so a region can exist before any module is loaded into it (Phase 3's st_open) and be rebuilt at boot from persisted state (Phase 2's restore).

id is an opaque prefix value whose prefix lives in the HIGH bits above plen โ€” the same shape region_alloc_slot() produces for a claim-gated child. So 2<<48 at plen 16 is a canonical, fully aligned id; a value with any bit set below the prefix width is not, and is rejected. id is never inspected to infer a width: CP-3 established that four regions share id 0, so a "lowest set bit implies the width" shortcut is exactly the bug this API exists to avoid. Pass the width.

The new region is attached to the nearest existing ancestor โ€” the region of the largest width below plen that prefix-covers (id, plen), the root always qualifying. No intermediate ancestors are invented, so a multi-bit jump is legal and cheap: claiming (0,64) straight from the root creates one region, not four.

Rejections:

Note what that last rule does not say: a same-id child is legal. Claiming (0,16) under the root (0,0) widens the region, so it is accepted โ€” and it has to be, since (0,0) and (0,16) sharing an id is exactly what CP-3 introduced. The rejection is about width, never about id equalling the ancestor's.

An exact (id, plen) match is idempotent: it succeeds, becomes the caller's current region, and โ€” like the creation path โ€” installs fn as the region's claim handler when fn is non-NULL. A later claim therefore reconfigures an existing region rather than silently ignoring the handler.

Parameters

fn Claim handler to install on the region, or NULL for none.
ud User data for fn.

Returns

XY_OK on creation or reuse; negative XY_ERR_* on rejection. On success the region is the caller's current region, so a following xy_load() lands inside it.

typedef int xy_claim_handler_fn_t(const char *module_path, uint8_t requested_bits, uint8_t *granted_bits, void *ud)

Claim handler type.

Parameters

module_path Path of the child module making the request (read-only)
requested_bits Number of bits the child asked for
granted_bits Out-param: set to the approved width
ud User data from xy_require_claim()

Returns

XY_OK to approve (with *granted_bits set), XY_ERR_EPERM to reject.

typedef uint8_t xy_current_region_plen_t(void)

Return the plen half of the caller's current region identity. Reads the thread-local region entry directly โ€” no lookup, and no ambiguity, because the current region is already resolved. For any region other than the current one, use xy_region_exists() to test an exact (id, plen).

Returns

Prefix length in bits; 0 for the root region.

typedef uint64_t xy_current_region_t(void)

Return the id half of the caller's current region identity. This is the id only. It does not name a region uniquely; pair it with xy_current_region_plen() to obtain a full identity.

typedef int xy_deny_t(const char *what, xy_deny_type_t type)

Deny a hook or module within the caller's current region. The deny applies to sub-regions only (children-only semantics by default). A module's own region is never blocked by its own deny.

Parameters

what Hook name (XY_DENY_HOOK) or module path (XY_DENY_MODULE).
type XY_DENY_HOOK or XY_DENY_MODULE.

Returns

XY_OK or a negative XY_ERR_* code.

typedef int xy_errno_t(void)

Get last error code.

Returns

Last error code from failed API call

Most API functions set this on failure.

typedef int xy_load_t(char *fname)

Load or reload a module into the caller's current region.

Parameters

fname Path to .so (Linux) or .dll (Windows) file

Returns

XY_OK on success, negative error code on failure

On first load, calls xy_install(). Subsequent loads of the same path into the same region are no-ops.

typedef uint64_t xy_region_at_t(uint64_t prefix_id, uint8_t plen, uint8_t *region_plen)

Find the deepest existing region whose prefix covers a point. The engine's "which region is this point in?" primitive: given a prefix value, return the most specific region that contains it, so a caller walking the tree coarse-to-fine can tell an exact hit from an ancestor fallback.

A region (A, plen_A) covers (prefix_id, plen) when plen_A <= plen and masking prefix_id to plen_A yields A. The root covers every point, so the only way to miss is a plen that no region reaches.

Parameters

prefix_id The point to locate.
plen That point's prefix width in bits.
region_plen Out-param: the covering region's width. Set to 0 on every failure path, so it is always defined. May be NULL.

Returns

The covering region's id half, or XY_REGION_INVALID if none. The id alone does not name a region โ€” (0,0) and (0,16) share it โ€” so pass the returned width to xy_with_region() to dispatch there.

typedef int xy_region_each_fn_t(uint64_t child_id, uint8_t plen, void *ud)

Enumerate immediate child regions of the caller's current region. Calls fn(child_id, plen, ud) for each child in allocation order. child_id is an opaque uint64_t region identifier and plen is that child's prefix length in bits; together they are the child's identity.

Return XY_OK from fn to continue, any other value to stop. xy_region_each returns the last value returned by fn, or XY_OK if there were no children.

typedef int xy_region_exists_t(uint64_t region_id, uint8_t plen)

Test whether the region identified by (region_id, plen) exists and is addressable.

Returns

XY_OK if that exact region exists, XY_ERR_NOTFOUND otherwise. Both halves are required: an region_id that exists at a different width is a different region.

typedef int xy_reload_t(char *fname)

Reload a module in place, preserving its dispatch position. Equivalent to xy_unload() followed by xy_load() in the same region, but the reloaded module is re-inserted at its original position in the dispatch order rather than appended at the tail.

If xy_uninstall() vetoes the unload the reload is aborted.

Parameters

fname Path that was passed to xy_load() (without .so/.dll suffix)

Returns

XY_OK on success, negative XY_ERR_* on failure.

typedef int xy_require_claim_t(xy_claim_handler_fn_t *fn, void *ud)

Set or clear the claim gate on the caller's current region. When fn is non-NULL, the gate is opened: all subsequent xy_load() calls into this region require the module to export a XY_MODULE_API uint8_t xy_claim data symbol. If the symbol is absent, xy_load() returns XY_ERR_EPERM and xy_install() never runs. If the symbol is present, the host performs the claim on behalf of the module by invoking fn before running xy_install().

Modules loaded before this call in the same xy_install() context are unaffected โ€” they load flat into the current region as normal.

When fn is NULL, the gate is cleared: subsequent xy_load() calls no longer require an xy_claim symbol. A later non-NULL call re-enables the gate.

Parameters

fn Claim handler function, or NULL to clear the claim gate.
ud User data passed to fn (ignored when fn is NULL).

Returns

XY_OK or negative XY_ERR_* code.

typedef void xy_shutdown_t(void)

Shutdown and unload all modules. Calls dlclose() on all loaded module handles. After this, xy_load() can be called again.

typedef const char * xy_strerror_t(int err)

Get human-readable error message.

Parameters

err Error code (e.g., from xy_errno())

Returns

Static string describing the error

typedef int xy_unload_t(char *fname)

Unload a previously loaded module from the caller's current region. Decrements the module's reference count. When the count reaches zero:

Parameters

fname Path that was passed to xy_load() (without .so/.dll suffix)

Returns

XY_OK on success, XY_ERR_NOTFOUND if not loaded, XY_ERR_EPERM if xy_uninstall() vetoed the unload.

typedef int xy_with_region_t(uint64_t region_id, uint8_t plen, xy_scope_fn_t *fn, void *ud)

Run fn with the caller's current region temporarily set to the region identified by (region_id, plen). Nested hook calls inside fn inherit that region. The previous region is always restored, including when fn fails.

Returns

XY_ERR_NOTFOUND if no region with that exact (id, plen) exists โ€” an region_id that exists at some other width is a different region and is likewise not found.

Enumeration Type Documentation

enum xy_deny_type_t

Deny target (hook name or module path) selector.

Enumerator

XY_DENY_HOOK
what is a hook name
XY_DENY_MODULE
what is a module path

Function Documentation

struct __attribute__ ((packed) )

Region identity. A region is identified by the pair (id, plen) โ€” never by id alone. id is an opaque uint64_t prefix value and plen is that prefix's length in bits (0 for the root region). Two regions may legitimately share an id and differ only in plen โ€” e.g. the root (0,0) and a child granted its leftmost bits (0,16) โ€” so any API that must name a region unambiguously takes both halves.

This struct is packed, and that is load-bearing rather than cosmetic: it serves as a fixed-width corm key compared bytewise, so any padding would be uninitialised bytes that differ between the storing and the looking-up call and would silently make lookups miss. sizeof must be exactly 9.

uint64_t xy_ctx_abi (void )

Report this module's xy_ctx ABI generation and size. A module must export this symbol with exactly this signature, returning XY_CTX_ABI_DESC. xy-mod.h emits it automatically for C modules and xy_module!() does so for Rust modules; a hand-written module that only exports get_xy_ptr must add it by hand.

The host compares the returned descriptor against its own before writing anything into the module's context. A module built against a different header has an object of a different size, and the host's write would overrun it โ€” corrupting unrelated data in the module's BSS rather than failing. A module that does not export this symbol at all is refused the same way, because an unversioned module cannot be proven safe.

Only modules that actually have a context need this. A module that exports neither get_xy_ptr nor a xy_self_init_ctx call has nothing for the host to write into, so there is nothing to overrun and nothing to declare; bootstrap modules like the site's core are in that class and load unchanged.

Returns

XY_CTX_ABI_DESC as compiled into the calling module.

int xy_load_mem (const xy_mem_mod_t * desc)

Load an in-memory module into the caller's current region. On XY_OK, libxylem takes ownership of releasing the backing memory via desc->release(desc->ud) when the module is unloaded via xy_unload(desc->name) or xy_shutdown(). On any error, desc->release is NOT invoked.

int xy_register_mem_mod (const xy_mem_mod_t * desc)

Register a statically linked in-memory module descriptor for lazy resolution by xy_load(). When a host registers static modules with xy_register_mem_mod(), subsequent xy_load() calls matching desc->name (exact or logical basename) resolve via xy_load_mem(desc) without invoking dlopen(). Idempotent and preserved across xy_shutdown() so embedded hosts can restart cleanly.

void xy_self_init_ctx (struct xy_ctx * ctx)

Register a module's xy context from a .init_array constructor. Rust cdylibs call this from a .init_array constructor (generated by xy_module!()) to push their xy context pointer to the loader before mod_load_bind_xy runs. The loader uses it as a fallback when get_xy_ptr lookup fails or returns an unexpected result.

Parameters

ctx Pointer to the module-local XyCtx static.

Author

Generated automatically by Doxygen for libxylem from the source code.