Skip to main content

Crate cscript_ffi

Crate cscript_ffi 

Source
Expand description

Loads a user-supplied, precompiled shared library (.so/.dylib/.dll) exposing a small C ABI – two required functions, cscript_start and cscript_output, plus the optional ones documented below (cscript_free, cscript_clone, the continuous-state xc contract, the discrete cscript_update, cscript_arity and cscript_next_sample_hit) – and calls into it once per block instance per transient step — a dynamically- loaded, stateful escape hatch for block behavior no existing continuous-blocks block covers, the same role a code-generation/scripting slot plays in other block-diagram simulation tools’ own extensibility mechanisms, or an ngspice XSPICE codemodel .cm plugin (see an internal gotcha note on ngspice XSPICE codemodels needing MFBINIT set in the environment, for that already-used pattern).

This crate is the one place in this workspace where calling into arbitrary native code is deliberately allowed. Loading a shared library and calling into it is unsafe by construction: the code runs in-process with this program’s own privileges, can corrupt memory, crash the process, or do anything a normal native program can do. That is an accepted, bounded risk of this specific opt-in feature (a user explicitly names a .so file in their own netlist), not something this crate tries to sandbox away — no different in kind from the XSPICE codemodel pattern already used elsewhere in this same project.

§The C-side contract

A block’s shared library must export:

// Called once, when this block instance is created. Return an opaque instance-state
// pointer (typically malloc'd), or NULL if this block instance carries no state at all.
void *cscript_start(void);

// Called once per resolved transient step. `state` is whatever cscript_start() returned
// for this instance (NULL if none); `in`/`in_len` is this step's input vector, in the
// netlist's own declared order; `dt` is this step's size (seconds) -- needed for any block
// that integrates over time, e.g. `state->integral += error * dt`, the same explicit-Euler
// update every other stateful block in this project already uses; `out`/`out_len` is the
// output vector to fill.
void cscript_output(void *state, const double *in, int in_len, double dt, double *out, int out_len);

// Optional. Called once when this block instance is dropped. Free anything
// cscript_start() allocated. If the symbol is absent, `state` is simply leaked -- harmless
// for a short-lived CLI run, but real cleanup is provided for any longer-lived host.
void cscript_free(void *state);

// Optional. Return a deep copy of `state` (independent memory: mutating the copy through
// future cscript_output() calls must never affect the original, and vice versa). Only
// needed to use this block under general-simulator's adaptive step-size control, which retries a
// rejected trial step from an independent copy of every block's state -- see "Adaptive
// step-size control and instance cloning" below.
void *cscript_clone(void *state);

§The optional continuous-state (xc) contract

A block declaring xc_count > 0 in its netlist line owns a continuous-state vector the solver itself numerically integrates (RK4, one independent integration per block, the same convention [continuous_blocks::StateSpace::rk4_step] uses for every other dynamic block in this workspace) – as opposed to the plain void *state blob above, which is never touched by anything but the block’s own C code. This is a pure vector-field evaluation the solver calls, not something the block’s own cscript_output hand-integrates itself (a block that wants to manage its own state by hand, e.g. a hand-rolled dv/dt Euler estimate, remains exactly as correct as before this contract existed – this new contract is specifically for state the solver should own instead).

Such a block exports two more functions instead of cscript_output (never both – CScriptRegistry::instantiate_xc requires exactly these two, CScriptRegistry::instantiate requires plain cscript_output; a library is meant to implement one contract or the other):

// Pure vector-field evaluation: dxc/dt = f(t, u, xc, xd). Must not
// mutate `state`, `in`, or `xc` -- called up to four times per accepted step (RK4's own
// k1..k4 stages), including from now-discarded trial steps under adaptive stepping (see
// "Adaptive step-size control and instance cloning" below -- the same "a rejected trial's
// mutation never survives" guarantee applies here, so this restriction is about correctness
// of a single RK4 step's own math, not about adaptive-step safety).
void cscript_derivative(void *state, const double *in, int in_len,
                        const double *xc, int xc_len, double *xc_dot, int xc_dot_len);

// Used instead of cscript_output. Identical role, with read access to this step's own
// already-RK4-integrated xc (the *new*, post-step continuous state -- matching every other
// dynamic block's own "step state, then compute output from the new state" convention). May
// still mutate `state` for its own xd/bookkeeping purposes, exactly like plain
// cscript_output.
void cscript_output_xc(void *state, const double *in, int in_len, double dt,
                       const double *xc, int xc_len, double *out, int out_len);

xc itself lives in dae-runtime’s own BlockState, not inside the opaque void *state blob – the one place this contract breaks the “everything is opaque to Rust” rule, and deliberately so: the solver’s own RK4 stepper needs to do ordinary vector arithmetic on it between stages, which an opaque C-managed blob could never allow. cscript_start/ cscript_free/cscript_clone are unaffected either way – xc’s own initial value is always the zero vector (matching every other dynamic block’s own “starts at rest” convention), and cloning it is a plain Vec<f64> clone, needing no C-side involvement at all.

§The optional discrete-state update function

cscript_output/cscript_output_xc are permitted to mutate state themselves (documented above) – fine for the common case, but it conflates two different things: computing this step’s output from the block’s current state, and committing that state forward to the next step. Some block-diagram tools’ own code-block feature keeps these deliberately separate (an output function that’s expected to be side-effect-free, plus a dedicated update function that’s the only place discrete state actually advances) – cscript now offers the same split, as an entirely optional third function:

// Optional. Called once per resolved (or per-sample-period, under ts=) step, immediately
// after cscript_output/cscript_output_xc for that same call -- the dedicated place to
// commit `state`'s own discrete bookkeeping forward to the next step, instead of doing it
// inside the output function itself. `xc` is this step's own already-integrated continuous
// state (`xc_len == 0` for a block with `xc_count == 0`, exactly like every other xc-aware
// parameter in this contract). If this symbol is absent, a cscript block is expected to
// keep updating `state` directly inside cscript_output/cscript_output_xc, exactly as before
// this function existed -- nothing about the existing contract changes if you never add
// this.
void cscript_update(void *state, const double *in, int in_len, double dt,
                     const double *xc, int xc_len);

§The optional block-controlled sample time

A cscript block’s own ts=/freq= fixes a period at netlist-parse time — the right choice for a controller running at a genuinely fixed rate. Some blocks instead know their own next execution time only at runtime (a modulator whose next switching instant depends on a live computation, an event-driven controller that only needs to re-run when something crosses a threshold). ts=variable in the netlist selects this mode, and requires the library to export one more function (checked once, up front, the same “checked once, up front” discipline cscript_clone’s own adaptive-stepping requirement already uses):

// Required when this block declares ts=variable (never called otherwise). Called
// immediately after cscript_output/cscript_output_xc on every step this block actually
// ran. Returns the number of seconds, *relative to this call*, until this block should
// next be executed -- not an absolute time, consistent with every other cscript function
// never seeing absolute time either. Must return a value > 0; dae-runtime holds this
// block's last output constant (zero-order hold) for that many seconds, then calls
// cscript_output/cscript_output_xc again and asks for the next interval once more.
double cscript_next_sample_hit(void *state, const double *in, int in_len,
                                const double *xc, int xc_len);

Unlike the discrete-state update function above, this one is genuinely required once opted into via ts=variable — a missing symbol is a load-time error (CScriptError::MissingSymbol), not a silent no-op, since there would otherwise be no way to ever know when to run the block at all.

§The optional checkpoint state contract

dae-runtime’s checkpoint/resume writes every block’s state to a file and reads it back later, possibly in another process. The opaque void *state is the one thing it cannot reach on its own — only the author’s own C code knows the layout — so a library opts in by exporting all three of:

// How many bytes cscript_state_write() will produce for this state. Called with the same
// `state` pointer cscript_start()/cscript_clone()/cscript_state_read() returned (NULL for a
// block that keeps no state -- return 0 in that case).
size_t cscript_state_size(const void *state);

// Serialize `state` into `out`, which has exactly cscript_state_size(state) bytes of room.
// Never called when that size is 0. Write every value the block needs to continue
// *bit-identically*: a memcpy of a plain-old-data struct is the usual implementation; a
// struct holding pointers must serialize what they point at, not the addresses.
void cscript_state_write(const void *state, uint8_t *out);

// The inverse: build a fresh, independently owned state object from `len` bytes written
// by cscript_state_write() (possibly by another process), and return it. The instance's
// previous state is released through cscript_free() (if exported) once this returns.
void *cscript_state_read(const uint8_t *in, size_t len);

The three are all-or-nothing: exporting none keeps today’s behaviour (a run that asks for a checkpoint is refused at the first snapshot, naming the block; a run that does not is unaffected), and exporting only some is a load-time CScriptError::MissingSymbol naming the absent one — a library half-way through adopting the contract would otherwise look exactly like one that never started. CScriptInstance::supports_state_io is the up-front check, CScriptInstance::state_bytes/CScriptInstance::restore_state the two halves. xc needs nothing from this contract: it is a plain Vec<f64> on the Rust side.

§Adaptive step-size control and instance cloning

general-simulator’s adaptive step-size control retries a rejected trial step from scratch: every block’s state is cloned before the trial, the trial runs against the clone, and if rejected the clone is discarded and a fresh one is taken for the next, smaller attempt – never mutating the real, confirmed state until a trial is actually accepted. That is exactly correct for plain Rust block state (a Vec<f64> clone is a real, independent copy), but a CScriptInstance’s state is an opaque pointer this crate never reads through, so it cannot generically deep-copy it – only the user’s own C code knows its own layout. Clone for CScriptInstance is implemented in terms of cscript_clone for exactly this reason, and panics if the library didn’t export it. In practice this should never fire: check CScriptInstance::supports_clone once, up front, and refuse adaptive step-size control for a netlist containing a cscript block whose library doesn’t support it, the same way dae-runtime already does before entering its own adaptive loop.

Everything else in the user’s .c file — includes, #defines, typedefs, file-scope static helper functions and variables the user wants visible to all three of the functions above for one translation unit — needs no special support from this crate: plain C file scope already provides exactly that. The user compiles their own .c file into a shared library themselves (e.g. cc -shared -fPIC -o my_block.so my_block.c); this crate never invokes a compiler.

§The optional arity declaration

in_len/out_len are whatever the netlist declared for this block. If the .c file was written for a different number, nothing here notices: the block indexes a buffer sized by the netlist against the size it expected, which is an out-of-bounds read or write, not a failed run. A wrong answer at best, memory corruption at worst, and in neither case a message naming the block.

A library can close that by saying what it was built for:

// Optional. Write the counts this block expects and return 0. Return non-zero to decline,
// which is treated exactly like not exporting the symbol at all.
int cscript_arity(int *in_len, int *out_len) {
    *in_len = 2;
    *out_len = 1;
    return 0;
}

When present, dae-runtime compares it against the netlist before the first step and refuses a disagreement with DaeError::CScriptArityMismatch, naming the block and both counts. This crate only resolves and calls the symbol — see CScriptInstance::declared_arity — because nothing here knows what a netlist is.

A negative value means “not declaring this side”, so a block that genuinely takes any number of inputs can still pin its output count:

int cscript_arity(int *in_len, int *out_len) {
    *in_len = -1;   // any number
    *out_len = 1;
    return 0;
}

The symbol is optional on purpose. Every library written before it existed keeps loading and running unchanged, with the old “documented, not enforced” behaviour — the check is something a library opts into, not a new requirement.

§Multi-instance state

Two block instances naming the same lib= path share one loaded image (dlopen on most platforms de-duplicates repeat loads of the same path — see CScriptLibrary::load), but each instance gets its own cscript_start() call and its own returned state pointer, so per-instance state (e.g. an integrator’s accumulator) is never accidentally shared between two uses of the same block in one netlist. CScriptRegistry caches loaded libraries by path for exactly this reason: cheap repeat instantiation, without repeat dlopen.

Structs§

CScriptInstance
One block instance’s own state, from one call to cscript_start() on a shared CScriptLibrary. Drop calls cscript_free if the library exported one.
CScriptLibrary
One loaded shared library’s three FFI entry points. Kept alive for as long as any CScriptInstance built from it exists (each instance holds an Arc to this) — the Library must outlive every raw function pointer taken from it.
CScriptRegistry
Caches loaded libraries by path, so several block instances naming the same lib= file share one dlopen’d image while each still gets its own CScriptInstance (own state pointer) — see the module doc comment, “Multi-instance state.”
DeclaredArity
What a library says about its own input and output counts.

Enums§

CScriptError