Files
chandra/wasmhost/wt/wt_stub.c
Claude 77fcc4db1c
CI / test (push) Canceled after 12m58s
Screenshot editor: annotate, blur, pixelate, redact and crop before saving
Every screenshot now opens in an editor after KDE Spectacle's annotation mode:
Arrow, Line, Rectangle, Ellipse, Pen, Highlighter, Text, Number markers, Blur,
Pixelate, Redact and Crop, 8 colours, 3 sizes, undo/redo. Enter saves and
copies, Ctrl+C copies only, Esc discards.

- Drawn by the compositor (shot_editor.mbt), keyboard owned by it while up.
- Annotations are drawn into the picture's pixels at full size (annotate.mbt),
  so what is shown is what is saved. Blur = 6x6 block average + 3 box-blur
  passes; redact is opaque; both touch only their box (pixel tests).
- The picture goes to the renderer as <=2 MB strips: one 8 MB image-pixels
  call exhausts wasmtime's hostcall fuel and killed the wasm host.
- Frame callbacks are held while the overlay/editor freeze the screen, so apps
  behind stop drawing (0% CPU vs 52% with a full-screen animating app).
- wasmhost: error buffer 16 KB so trap causes aren't cut off; image-pixels
  limit 1024 -> 16384 a side (both hosts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hh3TaFJh7nhCxAjV4Q
2026-11-26 05:37:03 +00:00

459 lines
17 KiB
C

/* The wasmtime C API (component model) for the MoonBit host.
*
* One engine, store and linker. Host functions are registered by interface; every call from the
* component lands in one callback that encodes the arguments into bytes, calls the MoonBit
* dispatcher with them and decodes the bytes it returns into the results. Calling an export works
* the same way in reverse. MoonBit never sees a wasmtime value, only this encoding (see val.mbt):
*
* value = kind:u8 payload (kind is WASMTIME_COMPONENT_*)
* bool/s8/u8: 1 byte; s16/u16: 2; s32/u32/f32/char: 4; s64/u64/f64: 8 (little endian)
* string/enum: u32 length + UTF-8
* list/tuple: u32 n + n values
* record: u32 n + n (string name, value)
* variant: string case + u8 has-payload + [value]
* option: u8 is-some + [value]
* result: u8 is-ok + u8 has-payload + [value]
* flags: u32 n + n strings
* blob: u32 n + n bytes (kind 0x80: a list<u8>, both ways)
* message = u32 count + count values
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wasmtime.h>
#include "moonbit.h"
#define KIND_BLOB 0x80
typedef moonbit_bytes_t (*wt_dispatch_t)(int32_t id, moonbit_bytes_t args);
static wasm_engine_t *engine;
static wasmtime_store_t *store;
static wasmtime_context_t *ctx;
static wasmtime_component_linker_t *linker;
static wasmtime_component_t *component;
static wasmtime_component_instance_t instance;
static int have_instance;
static wt_dispatch_t dispatch;
static char last_error[16384]; /* wasmtime backtraces are long; the cause comes last */
static void set_error(const char *what, wasmtime_error_t *e) {
if (!e) {
snprintf(last_error, sizeof last_error, "%s", what);
return;
}
wasm_byte_vec_t m;
wasmtime_error_message(e, &m);
snprintf(last_error, sizeof last_error, "%s: %.*s", what, (int)m.size, m.data);
wasm_byte_vec_delete(&m);
wasmtime_error_delete(e);
}
/* ---- encoding ---- */
typedef struct { uint8_t *p; size_t len, cap; } Buf;
static void put(Buf *b, const void *src, size_t n) {
if (b->len + n > b->cap) {
size_t c = b->cap ? b->cap * 2 : 256;
while (c < b->len + n) c *= 2;
b->p = realloc(b->p, c);
b->cap = c;
}
memcpy(b->p + b->len, src, n);
b->len += n;
}
static void put_u8(Buf *b, uint8_t v) { put(b, &v, 1); }
static void put_u32(Buf *b, uint32_t v) { put(b, &v, 4); }
static void put_name(Buf *b, const wasm_name_t *s) {
put_u32(b, (uint32_t)s->size);
if (s->size) put(b, s->data, s->size);
}
static void enc(Buf *b, const wasmtime_component_val_t *v) {
put_u8(b, v->kind);
switch (v->kind) {
case WASMTIME_COMPONENT_BOOL: put_u8(b, v->of.boolean ? 1 : 0); break;
case WASMTIME_COMPONENT_S8: put(b, &v->of.s8, 1); break;
case WASMTIME_COMPONENT_U8: put(b, &v->of.u8, 1); break;
case WASMTIME_COMPONENT_S16: put(b, &v->of.s16, 2); break;
case WASMTIME_COMPONENT_U16: put(b, &v->of.u16, 2); break;
case WASMTIME_COMPONENT_S32: put(b, &v->of.s32, 4); break;
case WASMTIME_COMPONENT_U32: put(b, &v->of.u32, 4); break;
case WASMTIME_COMPONENT_S64: put(b, &v->of.s64, 8); break;
case WASMTIME_COMPONENT_U64: put(b, &v->of.u64, 8); break;
case WASMTIME_COMPONENT_F32: put(b, &v->of.f32, 4); break;
case WASMTIME_COMPONENT_F64: put(b, &v->of.f64, 8); break;
case WASMTIME_COMPONENT_CHAR: put(b, &v->of.character, 4); break;
case WASMTIME_COMPONENT_STRING: put_name(b, &v->of.string); break;
case WASMTIME_COMPONENT_ENUM: put_name(b, &v->of.enumeration); break;
case WASMTIME_COMPONENT_LIST:
if (v->of.list.size && v->of.list.data[0].kind == WASMTIME_COMPONENT_U8) {
b->p[b->len - 1] = KIND_BLOB;
put_u32(b, (uint32_t)v->of.list.size);
for (size_t i = 0; i < v->of.list.size; i++) put_u8(b, v->of.list.data[i].of.u8);
break;
}
put_u32(b, (uint32_t)v->of.list.size);
for (size_t i = 0; i < v->of.list.size; i++) enc(b, &v->of.list.data[i]);
break;
case WASMTIME_COMPONENT_TUPLE:
put_u32(b, (uint32_t)v->of.tuple.size);
for (size_t i = 0; i < v->of.tuple.size; i++) enc(b, &v->of.tuple.data[i]);
break;
case WASMTIME_COMPONENT_RECORD:
put_u32(b, (uint32_t)v->of.record.size);
for (size_t i = 0; i < v->of.record.size; i++) {
put_name(b, &v->of.record.data[i].name);
enc(b, &v->of.record.data[i].val);
}
break;
case WASMTIME_COMPONENT_VARIANT:
put_name(b, &v->of.variant.discriminant);
put_u8(b, v->of.variant.val ? 1 : 0);
if (v->of.variant.val) enc(b, v->of.variant.val);
break;
case WASMTIME_COMPONENT_OPTION:
put_u8(b, v->of.option ? 1 : 0);
if (v->of.option) enc(b, v->of.option);
break;
case WASMTIME_COMPONENT_RESULT:
put_u8(b, v->of.result.is_ok ? 1 : 0);
put_u8(b, v->of.result.val ? 1 : 0);
if (v->of.result.val) enc(b, v->of.result.val);
break;
case WASMTIME_COMPONENT_FLAGS:
put_u32(b, (uint32_t)v->of.flags.size);
for (size_t i = 0; i < v->of.flags.size; i++) put_name(b, &v->of.flags.data[i]);
break;
default:
break; /* resources and maps: our WIT has none */
}
}
static moonbit_bytes_t to_moonbit(const Buf *b) {
moonbit_bytes_t out = moonbit_make_bytes((int32_t)b->len, 0);
if (b->len) memcpy(out, b->p, b->len);
return out;
}
static moonbit_bytes_t enc_message(const wasmtime_component_val_t *vals, size_t n) {
Buf b = {0};
put_u32(&b, (uint32_t)n);
for (size_t i = 0; i < n; i++) enc(&b, &vals[i]);
moonbit_bytes_t out = to_moonbit(&b);
free(b.p);
return out;
}
/* ---- decoding ---- */
typedef struct { const uint8_t *p; size_t len, pos; int bad; } Rd;
static int take(Rd *r, void *dst, size_t n) {
if (r->bad || r->pos + n > r->len) { r->bad = 1; memset(dst, 0, n); return 0; }
memcpy(dst, r->p + r->pos, n);
r->pos += n;
return 1;
}
static uint8_t get_u8(Rd *r) { uint8_t v; take(r, &v, 1); return v; }
static uint32_t get_u32(Rd *r) { uint32_t v; take(r, &v, 4); return v; }
static void get_name(Rd *r, wasm_name_t *out) {
uint32_t n = get_u32(r);
if (r->bad || r->pos + n > r->len) { r->bad = 1; wasm_byte_vec_new_empty(out); return; }
wasm_byte_vec_new(out, n, (const wasm_byte_t *)(r->p + r->pos));
r->pos += n;
}
static void dec(Rd *r, wasmtime_component_val_t *v);
static wasmtime_component_val_t *dec_boxed(Rd *r) {
wasmtime_component_val_t tmp;
dec(r, &tmp);
return wasmtime_component_val_new(&tmp);
}
static void dec(Rd *r, wasmtime_component_val_t *v) {
memset(v, 0, sizeof *v);
uint8_t kind = get_u8(r);
if (r->bad) { v->kind = WASMTIME_COMPONENT_BOOL; return; }
v->kind = kind;
switch (kind) {
case WASMTIME_COMPONENT_BOOL: v->of.boolean = get_u8(r) != 0; break;
case WASMTIME_COMPONENT_S8: take(r, &v->of.s8, 1); break;
case WASMTIME_COMPONENT_U8: take(r, &v->of.u8, 1); break;
case WASMTIME_COMPONENT_S16: take(r, &v->of.s16, 2); break;
case WASMTIME_COMPONENT_U16: take(r, &v->of.u16, 2); break;
case WASMTIME_COMPONENT_S32: take(r, &v->of.s32, 4); break;
case WASMTIME_COMPONENT_U32: take(r, &v->of.u32, 4); break;
case WASMTIME_COMPONENT_S64: take(r, &v->of.s64, 8); break;
case WASMTIME_COMPONENT_U64: take(r, &v->of.u64, 8); break;
case WASMTIME_COMPONENT_F32: take(r, &v->of.f32, 4); break;
case WASMTIME_COMPONENT_F64: take(r, &v->of.f64, 8); break;
case WASMTIME_COMPONENT_CHAR: take(r, &v->of.character, 4); break;
case WASMTIME_COMPONENT_STRING: get_name(r, &v->of.string); break;
case WASMTIME_COMPONENT_ENUM: get_name(r, &v->of.enumeration); break;
case WASMTIME_COMPONENT_LIST:
case WASMTIME_COMPONENT_TUPLE: {
uint32_t n = get_u32(r);
if (r->bad || n > r->len) { r->bad = 1; n = 0; }
wasmtime_component_vallist_t *l = kind == WASMTIME_COMPONENT_LIST
? &v->of.list : (wasmtime_component_vallist_t *)&v->of.tuple;
wasmtime_component_vallist_new_uninit(l, n);
for (uint32_t i = 0; i < n; i++) dec(r, &l->data[i]);
break;
}
case KIND_BLOB: {
uint32_t n = get_u32(r);
if (r->bad || r->pos + n > r->len) { r->bad = 1; n = 0; }
v->kind = WASMTIME_COMPONENT_LIST;
wasmtime_component_vallist_new_uninit(&v->of.list, n);
for (uint32_t i = 0; i < n; i++) {
memset(&v->of.list.data[i], 0, sizeof v->of.list.data[i]);
v->of.list.data[i].kind = WASMTIME_COMPONENT_U8;
v->of.list.data[i].of.u8 = r->p[r->pos + i];
}
r->pos += n;
break;
}
case WASMTIME_COMPONENT_RECORD: {
uint32_t n = get_u32(r);
if (r->bad || n > r->len) { r->bad = 1; n = 0; }
wasmtime_component_valrecord_new_uninit(&v->of.record, n);
for (uint32_t i = 0; i < n; i++) {
get_name(r, &v->of.record.data[i].name);
dec(r, &v->of.record.data[i].val);
}
break;
}
case WASMTIME_COMPONENT_VARIANT:
get_name(r, &v->of.variant.discriminant);
v->of.variant.val = get_u8(r) ? dec_boxed(r) : NULL;
break;
case WASMTIME_COMPONENT_OPTION:
v->of.option = get_u8(r) ? dec_boxed(r) : NULL;
break;
case WASMTIME_COMPONENT_RESULT:
v->of.result.is_ok = get_u8(r) != 0;
v->of.result.val = get_u8(r) ? dec_boxed(r) : NULL;
break;
case WASMTIME_COMPONENT_FLAGS: {
uint32_t n = get_u32(r);
if (r->bad || n > r->len) { r->bad = 1; n = 0; }
wasmtime_component_valflags_new_uninit(&v->of.flags, n);
for (uint32_t i = 0; i < n; i++) get_name(r, &v->of.flags.data[i]);
break;
}
default:
r->bad = 1;
v->kind = WASMTIME_COMPONENT_BOOL;
break;
}
}
/* Decode a message into `out` (n slots). 0 on success. */
static int dec_message(moonbit_bytes_t bytes, wasmtime_component_val_t *out, size_t n) {
Rd r = { (const uint8_t *)bytes, (size_t)Moonbit_array_length(bytes), 0, 0 };
uint32_t count = get_u32(&r);
if (r.bad || count != n) {
for (size_t i = 0; i < n; i++) { memset(&out[i], 0, sizeof out[i]); out[i].kind = WASMTIME_COMPONENT_BOOL; }
return -1;
}
for (size_t i = 0; i < n; i++) dec(&r, &out[i]);
return r.bad ? -1 : 0;
}
/* ---- host functions ---- */
/* WASMHOST_PROFILE=1: time spent per host function (encode / MoonBit handler / decode), dumped to
* stderr every 5 s. */
#define MAX_FUNCS 512
static int profiling = -1;
static char *func_names[MAX_FUNCS];
static struct { uint64_t n, enc, call, dec, bytes; } prof[MAX_FUNCS];
static uint64_t prof_last;
static uint64_t now_ns(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec;
}
static void prof_dump(uint64_t t) {
fprintf(stderr, "--- host calls over %.1f s (ms: enc call dec)\n", (t - prof_last) / 1e9);
for (int i = 0; i < MAX_FUNCS; i++) {
if (!prof[i].n) continue;
fprintf(stderr, "%-44s %7llu %8.1f %8.1f %8.1f %llu kB\n", func_names[i] ? func_names[i] : "?",
(unsigned long long)prof[i].n, prof[i].enc / 1e6, prof[i].call / 1e6, prof[i].dec / 1e6,
(unsigned long long)(prof[i].bytes >> 10));
}
memset(prof, 0, sizeof prof);
prof_last = t;
}
static wasmtime_error_t *host_call(void *env, wasmtime_context_t *c, const wasmtime_component_func_type_t *ty,
wasmtime_component_val_t *args, size_t nargs,
wasmtime_component_val_t *results, size_t nresults) {
(void)c; (void)ty;
int32_t id = (int32_t)(intptr_t)env;
if (profiling < 0) { profiling = getenv("WASMHOST_PROFILE") != NULL; prof_last = now_ns(); }
uint64_t t0 = profiling ? now_ns() : 0;
moonbit_bytes_t in = enc_message(args, nargs);
uint64_t t1 = 0, inlen = profiling ? (uint64_t)Moonbit_array_length(in) : 0;
if (profiling) t1 = now_ns();
moonbit_bytes_t out = dispatch(id, in); /* takes `in` */
uint64_t t2 = profiling ? now_ns() : 0;
int bad = dec_message(out, results, nresults);
moonbit_decref(out);
if (profiling && id >= 0 && id < MAX_FUNCS) {
uint64_t t3 = now_ns();
prof[id].n++; prof[id].enc += t1 - t0; prof[id].call += t2 - t1; prof[id].dec += t3 - t2;
prof[id].bytes += inlen;
if (t3 - prof_last > 5000000000ull) prof_dump(t3);
}
if (bad) {
char msg[96];
snprintf(msg, sizeof msg, "host function %d returned a malformed result", id);
return wasmtime_error_new(msg);
}
return NULL;
}
void wt_set_dispatch(wt_dispatch_t f) { dispatch = f; }
moonbit_bytes_t wt_last_error(void) {
size_t n = strlen(last_error);
moonbit_bytes_t out = moonbit_make_bytes((int32_t)n, 0);
memcpy(out, last_error, n);
return out;
}
int32_t wt_init(void) {
if (engine) return 0;
wasm_config_t *cfg = wasm_config_new();
wasmtime_config_wasm_component_model_set(cfg, true);
engine = wasm_engine_new_with_config(cfg);
if (!engine) { set_error("cannot create the wasmtime engine", NULL); return -1; }
store = wasmtime_store_new(engine, NULL, NULL);
ctx = wasmtime_store_context(store);
linker = wasmtime_component_linker_new(engine);
return 0;
}
int32_t wt_load(moonbit_bytes_t path) {
char p[4096];
size_t n = (size_t)Moonbit_array_length(path);
if (n >= sizeof p) n = sizeof p - 1;
memcpy(p, path, n);
p[n] = 0;
FILE *f = fopen(p, "rb");
if (!f) { snprintf(last_error, sizeof last_error, "cannot open %s", p); return -1; }
fseek(f, 0, SEEK_END);
long len = ftell(f);
rewind(f);
uint8_t *data = malloc(len > 0 ? (size_t)len : 1);
size_t got = fread(data, 1, (size_t)len, f);
fclose(f);
wasmtime_error_t *e = wasmtime_component_new(engine, data, got, &component);
free(data);
if (e) { set_error("cannot compile the component", e); return -1; }
return 0;
}
/* Define the functions `names` (newline separated) of interface `iface` ("" for the root), with
* ids first_id, first_id + 1, ... in order. */
int32_t wt_define(moonbit_bytes_t iface, moonbit_bytes_t names, int32_t first_id) {
wasmtime_component_linker_instance_t *root = wasmtime_component_linker_root(linker);
wasmtime_component_linker_instance_t *li = root;
size_t ilen = (size_t)Moonbit_array_length(iface);
wasmtime_error_t *e = NULL;
if (ilen) {
e = wasmtime_component_linker_instance_add_instance(root, (const char *)iface, ilen, &li);
if (e) { set_error("cannot define the instance", e); wasmtime_component_linker_instance_delete(root); return -1; }
}
const char *s = (const char *)names;
size_t len = (size_t)Moonbit_array_length(names), start = 0;
int32_t id = first_id;
for (size_t i = 0; i <= len; i++) {
if (i == len || s[i] == '\n') {
if (i > start) {
e = wasmtime_component_linker_instance_add_func(li, s + start, i - start, host_call,
(void *)(intptr_t)id, NULL);
if (e) {
char what[160];
snprintf(what, sizeof what, "cannot define %.*s", (int)(i - start), s + start);
set_error(what, e);
break;
}
if (id >= 0 && id < MAX_FUNCS) {
size_t nl = i - start, il = ilen;
char *nm = malloc(il + nl + 2);
memcpy(nm, iface, il); nm[il] = '.'; memcpy(nm + il + 1, s + start, nl); nm[il + nl + 1] = 0;
func_names[id] = nm;
}
id++;
}
start = i + 1;
}
}
if (li != root) wasmtime_component_linker_instance_delete(li);
wasmtime_component_linker_instance_delete(root);
return e ? -1 : 0;
}
int32_t wt_instantiate(void) {
wasmtime_error_t *e = wasmtime_component_linker_instantiate(linker, ctx, component, &instance);
if (e) { set_error("cannot instantiate the component", e); return -1; }
have_instance = 1;
return 0;
}
/* Call export `name` of interface `iface` ("" for a root export) with the encoded `args`. The
* encoded results, or an empty byte string on failure (wt_last_error says why). */
moonbit_bytes_t wt_call(moonbit_bytes_t iface, moonbit_bytes_t name, moonbit_bytes_t args) {
moonbit_bytes_t fail = moonbit_make_bytes(0, 0);
if (!have_instance) { set_error("no instance", NULL); return fail; }
wasmtime_component_export_index_t *parent = NULL;
size_t ilen = (size_t)Moonbit_array_length(iface);
if (ilen) {
parent = wasmtime_component_instance_get_export_index(&instance, ctx, NULL, (const char *)iface, ilen);
if (!parent) { set_error("no such exported interface", NULL); return fail; }
}
wasmtime_component_export_index_t *idx = wasmtime_component_instance_get_export_index(
&instance, ctx, parent, (const char *)name, (size_t)Moonbit_array_length(name));
if (parent) wasmtime_component_export_index_delete(parent);
if (!idx) { set_error("no such export", NULL); return fail; }
wasmtime_component_func_t func;
int ok = wasmtime_component_instance_get_func(&instance, ctx, idx, &func);
wasmtime_component_export_index_delete(idx);
if (!ok) { set_error("the export is not a function", NULL); return fail; }
wasmtime_component_func_type_t *ty = wasmtime_component_func_type(&func, ctx);
size_t nparams = wasmtime_component_func_type_param_count(ty);
wasmtime_component_valtype_t rty;
size_t nresults = wasmtime_component_func_type_result(ty, &rty) ? 1 : 0;
if (nresults) wasmtime_component_valtype_delete(&rty);
wasmtime_component_func_type_delete(ty);
wasmtime_component_val_t *a = calloc(nparams ? nparams : 1, sizeof *a);
if (dec_message(args, a, nparams)) {
for (size_t i = 0; i < nparams; i++) wasmtime_component_val_delete(&a[i]);
free(a);
set_error("malformed arguments", NULL);
return fail;
}
wasmtime_component_val_t res[1];
memset(res, 0, sizeof res);
wasmtime_error_t *e = wasmtime_component_func_call(&func, ctx, a, nparams, res, nresults);
for (size_t i = 0; i < nparams; i++) wasmtime_component_val_delete(&a[i]);
free(a);
if (e) { set_error("call failed", e); return fail; }
moonbit_bytes_t out = enc_message(res, nresults);
for (size_t i = 0; i < nresults; i++) wasmtime_component_val_delete(&res[i]);
wasmtime_component_func_post_return(&func, ctx);
moonbit_decref(fail);
return out;
}