LEVIATHAN vd52e79c4 · d52e79c486

Declarations

Callbacks, threads and tasks in foreign calls

Pass a Leviathan function to C with ffi::callback; where foreign calls run, when a callback may await, and the marks @mayCallback, @shallow and @reentrant.

since 0.1.0-alpha.1linuxwindowswasm

Description

A foreign function whose parameter has a function type, such as C's qsort comparator, takes a C function pointer. ffi::callback(f) turns a Leviathan function into one: it returns an ffi::Callback, which is what you pass for that parameter (its fn field is the raw address, for C functions that take a void*). The function's parameter and result types, which must be known where callback is called, select the C signature; each must be a C type, and the result may be void.

Sorting C memory with a Leviathan comparator

uses ffi;
use ffi;
use io::console;

@extern("c")
void qsort(Block base, int nmemb, int size, (Ptr, Ptr) => int32 compar);

void main() {
    Block data = Block(12);
    data.setInt32(0, 30);
    data.setInt32(4, 10);
    data.setInt32(8, 20);
    Callback cmp = ffi::callback::<(Ptr, Ptr) => int32>((Ptr a, Ptr b) => {
        int x = ffi::view(a, 4).int32At(0);
        int y = ffi::view(b, 4).int32At(0);
        return x < y ? -1 : (x > y ? 1 : 0);
    });
    qsort(data, 3, 4, cmp);
    console.writeln(data.int32At(0));
    console.writeln(data.int32At(4));
    console.writeln(data.int32At(8));
    cmp.close();
}
main();
10
20
30

The Callback you pass must have the C signature of the parameter it is passed for. Ptr and Ptr? count as the same C type (each side's own declaration decides whether it sees NULL as a null Ptr or as None); string and string? do not. When ffi::callback is written directly as the argument of a foreign call with a lambda, the lambda takes its types from that parameter, exactly as a lambda passed to an ordinary function-typed parameter does, so qsort(data, 3, 4, ffi::callback((Ptr a, Ptr b) => 0)) returns an int32. Elsewhere the lambda's own types decide, and an integer literal result is an int: name the signature with ffi::callback::<(Ptr, Ptr) => int32>(...), as the example above does, write the lambda's return type, which is its C return type (ffi::callback(int32 (Ptr a, Ptr b) => 0)), or convert the result with toInt32(). When the compiler can see where a Callback came from, that is ffi::callback(f) written in the call or a local variable initialized with it and never reassigned, a different signature is a compile error: callback signature mismatch for parameter 4 of 'qsort': expected (Ptr, Ptr) => int32, got (Ptr, Ptr) => int; write ffi::callback::<(Ptr, Ptr) => int32>(…) or convert the result with .toInt32(). Otherwise the call itself checks, before C runs, and throws FfiException with the same text up to the ;. A raw Ptr (such as a callback's fn) is passed without a check.

A callback occupies one of a fixed number of slots for its C signature until it is closed: 16 by default, more when a foreign function naming that signature says slots: n. close() frees the slot and the Leviathan function it holds; C must not call the pointer afterwards. ffi::Callback is not IDisposable (nor is ffi::Library): it is a raw-memory handle whose close() needs the native permission like the rest of the FFI surface, so it is not used with using — call close() yourself. Claiming a slot when all are live throws FfiException (callback slots exhausted for (Ptr, Ptr) => int32 (16)).

Inside a callback the code is ordinary Leviathan; a lambda that calls a method of its object writes this.method() explicitly. A throw does not unwind through C: the callback returns zero (or NULL, or nothing) to C, and the exception is raised again in Leviathan when the foreign call returns.

Where a foreign call runs

A foreign function that can call back into Leviathan, because it has a callback parameter or is marked @mayCallback, is callback-capable; every other one is a leaf. A leaf runs on the thread's own, large stack. A callback-capable function runs on the calling task's stack, after a check that at least 1 MiB of that stack is left (otherwise it throws FfiException saying how much remains; the LANG_TASK_STACK environment variable raises the task stack). Programs that call C get 8 MiB task stacks. @shallow puts a small, frequently called leaf such as strlen on the task stack with no stack switch and no check, which is cheaper and is safe only when the function really uses little stack.

Waiting inside a callback

A callback may await when the foreign function that invoked it is callback-capable: the task is suspended with the C frames still on its stack, and the rest of the program runs meanwhile. A callback invoked from inside a leaf function cannot wait, and an await there throws FfiException. The reason this matters is that some libraries store a callback in one call and invoke it from another: curl_easy_setopt stores the write function, curl_easy_perform calls it. Mark such a function @mayCallback so its callbacks may wait.

A library that calls back from a later call

uses ffi;
use ffi;
use io::console;

@extern("ev", "ev_set_handler")
void setHandler((int32) => void handler);

@extern("ev", "ev_run")
@mayCallback
int32 runLoop();

void main() {
    Callback h = ffi::callback((int32 code) => {
        console.writeln("event " + code.toString());
    });
    setHandler(h);
    runLoop();
    h.close();
}

To hand a result from a callback that may not wait to code that can, resolve a Promise from the callback and await it elsewhere.

Another task entering a library

While one task's callback is suspended inside library L, a different task calling a function of L would run L's code a second time on top of the half-finished first call, which most C libraries do not expect. Leviathan detects this and throws FfiException naming both functions and the waiting task, instead of running the second call. A callback calling back into its own library from the same task is ordinary C re-entry and is allowed. When a library does tolerate the interleaving, say so: mark the library reentrant = true in its [[native]] table, or mark the individual functions @reentrant. The C library and the maths library are treated as reentrant.

What no rule catches

  • Thread-local state shared between libraries, such as the C locale, is not tracked.
  • Re-entry by the same task follows C's rules.
  • A C function that needs more stack than is left can still overflow it, as in C; the headroom check makes this rare for callback-capable functions, and @shallow skips it.
  • @mayCallback, @shallow and @reentrant are claims the compiler cannot check. A missing @mayCallback shows up the first time a callback from that function waits; a wrong @reentrant or @shallow is undefined behaviour, as in C.

Rules

  1. ffi::callback(f) needs a function value whose type is known where it is called: a lambda with typed parameters (and, if written, a return type, which is its C return type), a method reference, or a typed function variable. Otherwise: ffi::callback needs a statically typed function value. Its parameters may be scalars, Ptr, Ptr?, string and string?; its result a scalar, Ptr, Ptr? or void. ffi::callback::<F>(f) names the C signature explicitly. C passing NULL for a string parameter does not run the callback: C gets zero, and the foreign call throws RuntimeException when it returns (callback (string) => int32: parameter 1 received NULL for a string); a string? parameter receives None.
  2. A function-typed parameter of a foreign function must have such a signature (callback parameter must be a function type with marshalable parameters ('name' param <n>)); it takes an ffi::Callback or a raw Ptr, never a Leviathan function directly. A Callback of a different C signature (different parameter or result types; Ptr and Ptr? count as one) is rejected: callback signature mismatch for parameter <n> of 'name': expected <signature>, got <signature> — a compile error when the argument is ffi::callback(f) or a never-reassigned local initialized with it (with a hint when only integer widths differ), otherwise an FfiException thrown by the call before C runs. A raw Ptr is not checked. Among overloaded foreign functions, a Callback whose signature the compiler can see selects the overload whose parameter has that signature.
  3. ffi::callback(<lambda>) written directly as a foreign-call argument is typed by that parameter's function type, like ffi::callback::<F>(...).
  4. The number of live callbacks of one signature is bounded by the largest slots among the foreign functions that name it (16 when none does).
  5. A callback runs on the thread that created it; a C library calling it from another thread aborts the process. ffi::Callback and ffi::Library do not cross spawn or a Channel; a Ptr does.
  6. @mayCallback marks a foreign function that may invoke a callback registered earlier. @shallow marks a leaf that uses little stack; it is an error on a callback-capable function (@shallow is meaningless on a callback-capable extern ('name')). @reentrant marks a function that tolerates another task's entry into its library while a callback from it is suspended. Each takes an optional bool (default true) and applies only to an @extern declaration (@mayCallback/@shallow/@reentrant apply to @extern declarations only).
  7. An await inside a callback invoked by a leaf foreign function throws FfiException; so does a second task entering a library while a callback from one of its non-reentrant callback-capable functions is suspended, and a callback-capable call with less than 1 MiB of task stack left.

Examples

A callback that must not wait can still hand work to code that can: it resolves a Promise, and a task awaits it. The shape is the same with or without C in between; here an ordinary function stands in for the callback.

Handing a result out of a callback

use io::console;

Promise<int> ready = Promise();

void onEvent(int code) {
    ready.resolve(code * 2);
}

void main() {
    onEvent(21);
    int value = await ready;
    console.writeln("got " + value.toString());
}
main();
got 42

The manifest line that declares a whole library reentrant:

[[native]]
name      = "sqlite3"
pkg       = "sqlite3"
reentrant = true

Notes

  • A callback slot is the only resource ffi::callback takes; closing a callback twice does nothing.
  • Callbacks need no userdata convention: every slot is its own C function.

See also

  • Foreign functions (@extern, @export) — Declare a C function with @extern and call it like any other function; which types cross to C and how, errors, variadic functions, exports and the build permission.
  • callback — Makes a Leviathan function callable from C.
  • Callback — A Leviathan function made callable from C, returned by ffi::callback.
  • Tasks — suspension and interleaving — What a task is, what runs while one is suspended, and in what order suspended tasks resume.
  • Threads, workers and message passing — Run work in parallel with std::spawn; values cross between threads by copy, and Channel is the way to talk to a running worker.