Files
chandra/compositor/wasm/wasm_stub.c
T
Claude 932fca627e
CI / test (push) Successful in 2m6s
Face unlock: a Howdy-style PAM module, shown in the password dialog and set up in Settings
- face/pam_chandra_face.so (`-auth sufficient`): runs `chandra-face compare` as root with a clean
  environment, forwards what it says as PAM_TEXT_INFO / PAM_ERROR_MSG, and maps its exit status
  to success / auth error / unavailable, so the password always still works. Skips remote
  sessions (PAM_RHOST, SSH_CONNECTION), a closed lid and users without faces; refuses a helper
  that isn't root's; kills one that hangs (timeout + 6 s).
- face/chandra-face (Python + OpenCV): YuNet finds the face, SFace embeds it, cosine similarity
  against the enrolled embeddings (threshold 0.42, two matching frames, dark IR warm-up frames
  skipped, optional require_ir). enroll / list / remove / clear / test / status / pam
  enable|disable / fetch-models (sha256-pinned opencv_zoo models). Embeddings only, in
  /var/lib/chandra-face/USER/faces.json (root, 0600); labels in faces.list (0644). Store, config
  and models must be root's and not writable by others. Root commands re-run through run0 (or
  pkexec), so polkit asks first. Settings in /etc/chandra/face.conf.
- `just install-face [--pam]`, `just uninstall-face [--purge]` (face/install.py; uninstall takes
  the module out of every PAM service first). `pam enable` inserts before the first auth or
  @include line (Debian's sudo has only @include common-auth), keeping a .bak.
- Password dialog: a face row ("Looking for your face…" with a sweeping ring, "Face
  recognized", or why not, "Type your password instead"); typing and Enter during the scan go in
  when PAM asks for the password. Howdy's pam_howdy.so messages are understood too.
- Settings > Session > Face unlock: "Use my face for passwords" (polkit-1 + sudo), the enrolled
  faces (Remove takes a second click), "Add a face…", and the tool's progress. New `face-unlock`
  capability: tables 24 (status) and 25 (faces), request 44, in the wasmer/wasmtime stub, the Rust
  host, the MoonBit wasmhost and chandra:host/plasmoids. compositor/shell/face.mbt runs the tool
  on a socket so the compositor never waits.
- Tests: face/test_face.py (fake camera of PGM frames + fake recognizer; --pam builds the module
  and runs it through pamtester), dialog states and message parsing (polkit_test), the dialog via
  a mock helper (auth_test, shots 14/15), Settings against a fake chandra-face (face_test).
  scripts/test.sh runs them (compositor/polkit was missing from its native list), CI installs
  libpam0g-dev + pamtester. Also regenerated two stale desktop-module bindings (doc comments).
- docs/face-unlock.md, including the limits of 2D face recognition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 01:19:29 +00:00

1002 lines
42 KiB
C

/* Wasm plasmoid host: runs the core module of a chandra plasmoid component
* (or a bare core module) with wasmer's C API. Canonical-ABI marshalling stays in
* MoonBit; this file instantiates, provides the host imports (theme, clock) and
* exposes raw calls plus guest-memory reads. */
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include <wasm.h>
#include "moonbit.h"
#define MAX_INST 2048
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC,
EX_CFG_ITEMS, EX_POST_CFG_ITEMS, EX_SET_CFG, EX_DESK_BACKDROP, EX_DESK_SCROLL, EX_DESK_TICK, EX_N };
static const char *ex_names[EX_N] = {
"chandra:desktop/plasmoid@0.1.0#info",
"chandra:desktop/plasmoid@0.1.0#render",
"chandra:desktop/plasmoid@0.1.0#on-event",
"chandra:desktop/plasmoid@0.1.0#popup",
"cabi_post_chandra:desktop/plasmoid@0.1.0#info",
"cabi_post_chandra:desktop/plasmoid@0.1.0#render",
"cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
"cabi_realloc",
/* optional: chandra:desktop/module-config (the module's own right-click settings) */
"chandra:desktop/module-config@0.1.0#config-items",
"cabi_post_chandra:desktop/module-config@0.1.0#config-items",
"chandra:desktop/module-config@0.1.0#set-config",
/* optional: chandra:desktop/desktop-module (a module that fills the desktop, wit/desktop.wit) */
"chandra:desktop/desktop-module@0.1.0#backdrop",
"chandra:desktop/desktop-module@0.1.0#on-scroll",
"chandra:desktop/desktop-module@0.1.0#tick",
};
typedef struct Inst {
int used;
wasm_module_t *module;
wasm_instance_t *instance;
wasm_memory_t *memory;
wasm_func_t *ex[EX_N];
uint8_t tokens[64];
int kind_n;
char imports[512]; /* newline-separated host interfaces this module imports (capabilities it uses) */
} Inst;
static wasm_engine_t *engine;
static wasm_store_t *store;
static Inst insts[MAX_INST];
/* Host imports a module can call. */
enum {
K_OTHER, K_TOKENS, K_CLOCK, K_APPS, K_LAUNCH, K_WINDOWS, K_FOCUS, K_LAYOUTS, K_LAYOUT_CUR, K_SET_LAYOUT,
K_INSPECT_IS_ON, K_INSPECT_SET, K_MOD_AVAILABLE, K_MOD_LOADED, K_MOD_LOAD, K_MOD_UNLOAD, K_MOD_MOVE, K_MOD_BROWSE,
K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID, K_LOGOUT, K_RELOAD, K_WALLPAPERS, K_WALLPAPER_CUR, K_SET_WALLPAPER,
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET,
K_APP_ICON,
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR,
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
K_BAT_READ,
K_NET_STATUS, K_NET_LIST, K_NET_SCAN, K_NET_CONNECT, K_NET_DISCONNECT, K_NET_FORGET, K_NET_SET_WIFI,
K_NET_SET_AIRPLANE,
K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL,
K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH,
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP,
K_FU_STATUS, K_FU_FACES, K_FU_ENROLL, K_FU_REMOVE, K_FU_SET_IN_USE, K_FU_REFRESH
};
typedef struct Env { Inst *inst; int kind; } Env;
/* ---- host data the shell publishes before calling a guest ----
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS,
T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES,
/* fixed numbers from here (wit/host/plasmoids.wit publish-table) */
T_DESKTOPS = 20, T_FACE_STATUS = 24, T_FACES = 25, T_N = 32 };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[24] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
4 screenshot state (bit 0 recording, bit 1 pointer in recordings),
5 screen-off minutes, 6 suspend minutes (0: never),
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left */
/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */
typedef struct { int kind; int32_t n; char *s; } Req;
#define MAX_REQ 64
static Req reqs[MAX_REQ];
static int req_head, req_tail;
static Req cur_req;
static void push_req(int kind, int32_t n, const char *s) {
if (req_tail - req_head >= MAX_REQ) return;
Req *r = &reqs[req_tail % MAX_REQ];
r->kind = kind;
r->n = n;
r->s = s ? strdup(s) : NULL;
req_tail++;
}
/* Host state a widget may read through its granted interfaces. The compositor refreshes
* these (mp_wasm_set_system / mp_wasm_set_windows) before drawing; widgets never touch
* /proc or the window manager themselves. */
static uint8_t g_system[64]; /* canonical-ABI bytes of system.snapshot */
static uint8_t *g_windows; /* count u32, then per window: id u64, focused u32, tlen u32, title u16[], alen u32, app u16[] */
static size_t g_windows_len;
static int64_t g_focus_req = -1; /* window id a widget asked to raise, until the compositor takes it */
static void mem_write(Inst *in, int32_t off, const void *src, size_t n) {
if (!in->memory || off < 0) return;
byte_t *base = wasm_memory_data(in->memory);
size_t size = wasm_memory_data_size(in->memory);
if ((size_t)off + n > size) return;
memcpy(base + off, src, n);
}
static int mem_read(Inst *in, int32_t off, void *dst, size_t n) {
if (!in->memory || off < 0) return 0;
size_t size = wasm_memory_data_size(in->memory);
if ((size_t)off + n > size) return 0;
memcpy(dst, wasm_memory_data(in->memory) + off, n);
return 1;
}
static void w32(Inst *in, int32_t off, int32_t v) { mem_write(in, off, &v, 4); }
/* Allocate in the guest through its cabi_realloc; -1 on failure. */
static int32_t guest_alloc(Inst *in, int32_t size, int32_t align) {
if (!in->ex[EX_REALLOC]) return -1;
if (size < 4) size = 4; /* the guest frees every lowered buffer, even empty ones */
wasm_val_t av[4] = { WASM_I32_VAL(0), WASM_I32_VAL(0), WASM_I32_VAL(align), WASM_I32_VAL(size) };
wasm_val_t rv[1] = { WASM_INIT_VAL };
wasm_val_vec_t a = { 4, av };
wasm_val_vec_t r = { 1, rv };
wasm_trap_t *tr = wasm_func_call(in->ex[EX_REALLOC], &a, &r);
if (tr) { wasm_trap_delete(tr); return -1; }
return rv[0].of.i32;
}
/* UTF-8 -> UTF-16LE string in guest memory; writes ptr/len (code units) at `at` and `at+4`. */
static void put_str(Inst *in, int32_t at, const uint8_t *u8, size_t n) {
size_t units = 0;
for (size_t i = 0; i < n;) {
uint8_t c = u8[i];
int len = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
units += len == 4 ? 2 : 1;
i += len;
}
int32_t ptr = guest_alloc(in, (int32_t)(units * 2), 2);
if (ptr < 0) { w32(in, at, 0); w32(in, at + 4, 0); return; }
uint16_t *buf = (uint16_t *)malloc(units * 2 + 2);
size_t k = 0;
for (size_t i = 0; i < n && k < units;) {
uint8_t c = u8[i];
uint32_t cp;
int len;
if (c < 0x80) { cp = c; len = 1; }
else if (c < 0xE0) { cp = c & 0x1F; len = 2; }
else if (c < 0xF0) { cp = c & 0x0F; len = 3; }
else { cp = c & 0x07; len = 4; }
for (int j = 1; j < len && i + j < n; j++) cp = (cp << 6) | (u8[i + j] & 0x3F);
i += len;
if (cp >= 0x10000) {
cp -= 0x10000;
buf[k++] = (uint16_t)(0xD800 + (cp >> 10));
if (k < units) buf[k++] = (uint16_t)(0xDC00 + (cp & 0x3FF));
} else {
buf[k++] = (uint16_t)cp;
}
}
mem_write(in, ptr, buf, units * 2);
free(buf);
w32(in, at, ptr);
w32(in, at + 4, (int32_t)units);
}
/* A guest UTF-16 string -> malloc'd UTF-8 (NUL-terminated). */
static char *guest_str(Inst *in, int32_t ptr, int32_t units) {
if (units < 0 || units > 4096) units = 0;
uint16_t *u = (uint16_t *)malloc((size_t)units * 2 + 2);
if (units > 0 && !mem_read(in, ptr, u, (size_t)units * 2)) units = 0;
char *out = (char *)malloc((size_t)units * 3 + 1);
size_t o = 0;
for (int i = 0; i < units; i++) {
uint32_t cp = u[i];
if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units) { cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); i++; }
if (cp < 0x80) out[o++] = (char)cp;
else if (cp < 0x800) { out[o++] = (char)(0xC0 | (cp >> 6)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else if (cp < 0x10000) { out[o++] = (char)(0xE0 | (cp >> 12)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else { out[o++] = (char)(0xF0 | (cp >> 18)); out[o++] = (char)(0x80 | ((cp >> 12) & 0x3F)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
}
out[o] = 0;
free(u);
return out;
}
static uint32_t rd_u32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }
/* Lower one row of table `t` (from byte `*pos`) as a record at guest address `off`: 'i' an i32,
* 's' a string, 'b' a bool (an i32 in the table, one byte in the record; bools go last). 0 when
* the table ends early. */
static int lower_row(Inst *in, Blob *b, size_t *pos, const char *spec, int32_t off) {
for (const char *c = spec; *c; c++) {
if (*pos + 4 > b->len) return 0;
uint32_t v = rd_u32(b->data + *pos);
*pos += 4;
if (*c == 'i') { w32(in, off, (int32_t)v); off += 4; }
else if (*c == 'b') { uint8_t one = v ? 1 : 0; mem_write(in, off, &one, 1); off += 1; }
else {
if (*pos + v > b->len) return 0;
put_str(in, off, b->data + *pos, v);
*pos += v;
off += 8;
}
}
return 1;
}
/* A record's size for `spec` ('s' 8, 'i' 4, 'b' 1), rounded up to its 4-byte alignment. */
static size_t record_size(const char *spec) {
size_t esz = 0;
for (const char *c = spec; *c; c++) esz += *c == 's' ? 8 : *c == 'b' ? 1 : 4;
return (esz + 3) & ~(size_t)3;
}
/* Lower row 0 of table `t` as a record at `retptr` (zeros when the table is empty). */
static void build_record(Inst *in, int t, const char *spec, int32_t retptr) {
Blob *b = &tables[t];
size_t pos = 4;
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
if (n == 0 || !lower_row(in, b, &pos, spec, retptr)) {
/* strings still need real (empty) allocations: the guest frees what it lifts */
int32_t off = retptr;
for (const char *c = spec; *c; c++) {
if (*c == 's') { put_str(in, off, (const uint8_t *)"", 0); off += 8; }
else if (*c == 'b') { uint8_t z = 0; mem_write(in, off, &z, 1); off += 1; }
else { w32(in, off, 0); off += 4; }
}
}
}
/* Lower table `t` (row layout `spec`, see lower_row) as a list<record> and write (ptr,len) at `retptr`. */
static void build_list(Inst *in, int t, const char *spec, int32_t retptr) {
Blob *b = &tables[t];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t esz = record_size(spec);
if (strchr(spec, 'b')) {
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
size_t pos = 4;
uint32_t r = 0;
while (r < n && lower_row(in, b, &pos, spec, base + (int32_t)(r * esz))) r++;
w32(in, retptr, base);
w32(in, retptr + 4, (int32_t)r);
return;
}
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
size_t pos = 4;
for (uint32_t r = 0; r < n; r++) {
int32_t off = base + (int32_t)(r * esz);
for (const char *c = spec; *c; c++) {
if (*c == 'i') {
if (pos + 4 > b->len) return;
w32(in, off, (int32_t)rd_u32(b->data + pos));
pos += 4;
off += 4;
} else {
if (pos + 4 > b->len) return;
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl > b->len) return;
put_str(in, off, b->data + pos, sl);
pos += sl;
off += 8;
}
}
}
w32(in, retptr, base);
w32(in, retptr + 4, (int32_t)n);
}
/* Does table `t` (first field a string) contain a row whose first string equals `id`? */
static int table_has_id(int t, const char *spec, const char *id) {
Blob *b = &tables[t];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t pos = 4;
size_t idl = strlen(id);
for (uint32_t r = 0; r < n; r++) {
for (const char *c = spec; *c; c++) {
if (pos + 4 > b->len) return 0;
if (*c == 'i') { pos += 4; continue; }
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl > b->len) return 0;
if (c == spec && sl == idl && memcmp(b->data + pos, id, sl) == 0) return 1;
pos += sl;
}
}
return 0;
}
/* The image handle table T_ICONS ("si": app id, handle) holds for `id`, or 0. */
static int32_t icon_for(const char *id) {
Blob *b = &tables[T_ICONS];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t pos = 4, idl = strlen(id);
for (uint32_t r = 0; r < n; r++) {
if (pos + 4 > b->len) return 0;
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl + 4 > b->len) return 0;
int hit = sl == idl && memcmp(b->data + pos, id, sl) == 0;
pos += sl;
int32_t h = (int32_t)rd_u32(b->data + pos);
pos += 4;
if (hit) return h;
}
return 0;
}
static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_vec_t *results) {
Env *e = (Env *)env;
Inst *in = e->inst;
int32_t a0 = args->size >= 1 ? args->data[0].of.i32 : 0;
int32_t a1 = args->size >= 2 ? args->data[1].of.i32 : 0;
int32_t a2 = args->size >= 3 ? args->data[2].of.i32 : 0;
switch (e->kind) {
case K_TOKENS:
if (args->size >= 1) {
uint8_t buf[64];
memcpy(buf, in->tokens, 64);
/* name: the guest lifts it as one of its own allocations, so give it a real (empty) one */
memset(buf, 0, 8);
int32_t p = guest_alloc(in, 0, 2);
if (p >= 0) memcpy(buf, &p, 4);
mem_write(in, a0, buf, 64);
}
break;
case K_CLOCK:
if (args->size >= 1) {
time_t t = time(NULL);
struct tm tmv;
localtime_r(&t, &tmv);
uint8_t buf[12];
memset(buf, 0, sizeof(buf));
int32_t year = tmv.tm_year + 1900;
memcpy(buf, &year, 4);
buf[4] = (uint8_t)(tmv.tm_mon + 1);
buf[5] = (uint8_t)tmv.tm_mday;
buf[6] = (uint8_t)tmv.tm_hour;
buf[7] = (uint8_t)tmv.tm_min;
buf[8] = (uint8_t)tmv.tm_sec;
buf[9] = (uint8_t)tmv.tm_wday;
mem_write(in, a0, buf, 12);
}
break;
case K_APPS: build_list(in, T_APPS, "sssss", a0); break; /* id name comment category glyph */
case K_WINDOWS: build_list(in, T_WINDOWS, "isii", a0); break;
case K_LAYOUTS: build_list(in, T_LAYOUTS, "s", a0); break;
case K_WALLPAPERS: build_list(in, T_WALLPAPERS, "s", a0); break;
case K_SESSION_SETTINGS: build_list(in, T_SESSION_SETTINGS, "s", a0); break;
case K_MOD_AVAILABLE: build_list(in, T_MODULES, "sssi", a0); break;
case K_MOD_LOADED: build_list(in, T_INSTANCES, "sss", a0); break;
case K_LAYOUT_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[0]);
break;
case K_WALLPAPER_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[2]);
break;
case K_SESSION_IS_ON:
if (results->size >= 1)
results->data[0] = (wasm_val_t)WASM_I32_VAL(a0 >= 0 && a0 < 32 ? (int32_t)(((uint32_t)host_ints[3] >> a0) & 1u) : 0);
break;
case K_INSPECT_IS_ON:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[1]);
break;
case K_SET_LAYOUT: push_req(3, a0, NULL); break;
case K_FOCUS: push_req(2, a0, NULL); break;
case K_LOGOUT: push_req(8, 0, NULL); break;
case K_RELOAD: push_req(8, 1, NULL); break; /* 8: session; n 0 log out, 1 reload */
case K_SET_WALLPAPER: push_req(9, a0, NULL); break;
case K_DESKTOPS: build_list(in, T_DESKTOPS, "s", a0); break;
case K_DESKTOP_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[20]);
break;
case K_SET_DESKTOP: push_req(40, a0, NULL); break;
/* Face unlock: status from table 24 (problem howdy message installed in-use busy), faces from
* table 25 (label added); request 44 is a face index to remove, or -1 refresh, -2 enroll,
* -3 / -4 stop / start using it. */
case K_FU_STATUS: build_record(in, T_FACE_STATUS, "sssbbb", a0); break;
case K_FU_FACES: build_list(in, T_FACES, "ss", a0); break;
case K_FU_ENROLL: push_req(44, -2, NULL); break;
case K_FU_REMOVE: if (a0 >= 0 && a0 < 1000) push_req(44, a0, NULL); break;
case K_FU_SET_IN_USE: push_req(44, a0 ? -4 : -3, NULL); break;
case K_FU_REFRESH: push_req(44, -1, NULL); break;
case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */
/* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */
case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break;
case K_SHOT_RECORD: if (a0 >= 0 && a0 <= 2) push_req(12, 10 + a0, NULL); break;
case K_SHOT_STOP: push_req(12, 20, NULL); break;
case K_SHOT_SET_PTR: push_req(12, a0 ? 31 : 30, NULL); break;
case K_PW_SCREEN:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[5]);
break;
case K_PW_SUSP:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[6]);
break;
case K_PW_SET_SCREEN: push_req(13, a0, NULL); break;
case K_PW_SET_SUSP: push_req(14, a0, NULL); break;
case K_PW_SUSPEND: push_req(15, 0, NULL); break; /* 15: power action n (0 suspend, 1 off, 2 restart) */
case K_PW_OFF: push_req(15, 1, NULL); break;
case K_PW_REBOOT: push_req(15, 2, NULL); break;
/* Network: status and the Wi-Fi list from tables 8/9; request 16 carries the action (n) and
* "ssid\x1fpassword" (see wit/host/plasmoids.wit network-request). */
case K_NET_STATUS: build_record(in, T_NET_STATUS, "iissbbbb", a0); break;
case K_NET_LIST: build_list(in, T_NET_NETWORKS, "sibbb", a0); break;
/* Shortcuts: the list from table 10 (name binding default conflict capturing); request 18 is
* action * 1000 + index (0 capture, 1 reset, 2 reset all, 3 cancel the capture). */
case K_SC_LIST: build_list(in, T_SHORTCUTS, "ssssb", a0); break;
case K_SC_CAPTURE: if (a0 >= 0 && a0 < 1000) push_req(18, a0, NULL); break;
case K_SC_RESET: if (a0 >= 0 && a0 < 1000) push_req(18, 1000 + a0, NULL); break;
case K_SC_RESET_ALL: push_req(18, 2000, NULL); break;
case K_SC_CANCEL: push_req(18, 3000, NULL); break;
/* Default apps: categories from table 11 (name current missing), choices from table 12 (category id name
* icon current); request 19 is category * 1000 + app, or -1 to scan again. */
case K_DA_CATS: build_list(in, T_APP_CATS, "sss", a0); break;
case K_DA_APPS: build_list(in, T_APP_CHOICES, "issib", a0); break;
case K_DA_SET: if (a0 >= 0 && a0 < 1000 && a1 >= 0 && a1 < 1000) push_req(19, a0 * 1000 + a1, NULL); break;
case K_DA_REFRESH: push_req(19, -1, NULL); break;
case K_NET_SCAN: push_req(16, 0, NULL); break;
case K_NET_DISCONNECT: push_req(16, 1, NULL); break;
case K_NET_SET_WIFI: push_req(16, a0 ? 3 : 2, NULL); break;
case K_NET_SET_AIRPLANE: push_req(16, a0 ? 5 : 4, NULL); break;
case K_NET_CONNECT:
case K_NET_FORGET: {
int32_t a3 = args->size >= 4 ? args->data[3].of.i32 : 0;
char *ssid = guest_str(in, a0, a1);
char *pw = e->kind == K_NET_CONNECT ? guest_str(in, a2, a3) : strdup("");
size_t ls = strlen(ssid), lp = strlen(pw);
char *both = (char *)malloc(ls + lp + 2);
memcpy(both, ssid, ls);
both[ls] = 0x1f;
memcpy(both + ls + 1, pw, lp + 1);
push_req(16, e->kind == K_NET_CONNECT ? 6 : 7, both);
memset(pw, 0, lp); /* don't leave the password lying around in freed memory */
memset(both, 0, ls + lp + 1);
free(ssid); free(pw); free(both);
break;
}
case K_SHOT_IS_REC:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[4] & 1);
break;
case K_SHOT_PTR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL((host_ints[4] >> 1) & 1);
break;
case K_INSPECT_SET: push_req(4, a0, NULL); break;
case K_MOD_BROWSE: push_req(7, 0, NULL); break;
case K_MOD_LOAD: { char *s = guest_str(in, a0, a1); push_req(5, 0, s); free(s); break; }
case K_MOD_UNLOAD: { char *s = guest_str(in, a0, a1); push_req(6, 0, s); free(s); break; }
/* move-instance(slot, delta): request 17, delta in n. */
case K_MOD_MOVE: { char *s = guest_str(in, a0, a1); push_req(17, a2, s); free(s); break; }
case K_LAUNCH: {
/* launch(id) -> result<_, string>; (ptr, len, retptr). Known catalog ids succeed; the shell spawns after the call. */
char *id = guest_str(in, a0, a1);
if (table_has_id(T_APPS, "sssss", id)) {
push_req(1, 0, id);
w32(in, a2, 0);
} else {
w32(in, a2, 1);
const char *msg = "unknown application";
put_str(in, a2 + 4, (const uint8_t *)msg, strlen(msg));
}
free(id);
break;
}
case K_APP_ICON: {
/* app-icon(app-id) -> u32; (ptr, len) */
char *id = guest_str(in, a0, a1);
int32_t h = id ? icon_for(id) : 0;
free(id);
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(h);
break;
}
case K_BAT_READ: {
/* battery.status: percent s32 @0, charge-state u8 @4, secs-left u32 @8 */
uint8_t st[12] = {0};
int32_t state = host_ints[8] >= 0 && host_ints[8] <= 4 ? host_ints[8] : 0;
memcpy(st, &host_ints[7], 4);
st[4] = (uint8_t)state;
memcpy(st + 8, &host_ints[9], 4);
if (args->size >= 1) mem_write(in, a0, st, 12);
break;
}
case K_SYSTEM_READ:
if (args->size >= 1) mem_write(in, a0, g_system, 64);
break;
case K_WIN_ALL: {
int32_t ret = a0;
uint32_t count = 0;
if (g_windows && g_windows_len >= 4) memcpy(&count, g_windows, 4);
if (count > 64) count = 64;
/* always a real allocation, even for an empty list: the guest frees it after lifting */
int32_t arr = guest_alloc(in, (int32_t)((count ? count : 1) * 32), 8);
size_t pos = 4;
uint32_t written = 0;
for (uint32_t i = 0; arr >= 0 && i < count; i++) {
uint64_t id; uint32_t focused, tlen, alen;
if (pos + 16 > g_windows_len) break;
memcpy(&id, g_windows + pos, 8); memcpy(&focused, g_windows + pos + 8, 4); memcpy(&tlen, g_windows + pos + 12, 4);
pos += 16;
if (tlen > 512 || pos + tlen * 2 + 4 > g_windows_len) break;
const uint8_t *title = g_windows + pos;
pos += tlen * 2;
memcpy(&alen, g_windows + pos, 4);
pos += 4;
if (alen > 512 || pos + alen * 2 > g_windows_len) break;
const uint8_t *app = g_windows + pos;
pos += alen * 2;
int32_t tp = tlen ? guest_alloc(in, (int32_t)(tlen * 2), 2) : 0;
int32_t ap = alen ? guest_alloc(in, (int32_t)(alen * 2), 2) : 0;
if (tlen && tp > 0) mem_write(in, tp, title, tlen * 2);
if (alen && ap > 0) mem_write(in, ap, app, alen * 2);
uint8_t rec[32];
memset(rec, 0, sizeof(rec));
int32_t tl = tp > 0 ? (int32_t)tlen : 0, al = ap > 0 ? (int32_t)alen : 0;
if (tp < 0) tp = 0;
if (ap < 0) ap = 0;
memcpy(rec, &id, 8); memcpy(rec + 8, &tp, 4); memcpy(rec + 12, &tl, 4);
memcpy(rec + 16, &ap, 4); memcpy(rec + 20, &al, 4); rec[24] = focused ? 1 : 0;
mem_write(in, arr + (int32_t)(i * 32), rec, 32);
written++;
}
int32_t out[2] = { arr >= 0 ? arr : 0, arr >= 0 ? (int32_t)written : 0 };
mem_write(in, ret, out, 8);
break;
}
case K_WIN_FOCUS_ID:
if (args->size >= 1) g_focus_req = args->data[0].of.i64;
break;
default: break;
}
return NULL;
}
static int leb(const uint8_t *p, size_t n, size_t *pos, uint32_t *out) {
uint32_t v = 0; int shift = 0;
while (*pos < n) {
uint8_t b = p[(*pos)++];
v |= (uint32_t)(b & 0x7f) << shift;
if (!(b & 0x80)) { *out = v; return 1; }
shift += 7;
if (shift > 28) return 0;
}
return 0;
}
static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len);
/* Components wrap their core modules in type-1 sections; try each until one yields a plasmoid. */
static int load_bytes(Inst *in, const uint8_t *d, size_t n) {
if (n < 8 || memcmp(d, "\0asm", 4) != 0) return -1;
if (d[4] == 1) return try_instantiate(in, d, n) ? 0 : -3;
size_t pos = 8;
while (pos < n) {
uint8_t id = d[pos++];
uint32_t size;
if (!leb(d, n, &pos, &size) || pos + size > n) return -1;
if (id == 1 && size >= 8 && memcmp(d + pos, "\0asm", 4) == 0) {
if (try_instantiate(in, d + pos, size)) return 0;
}
pos += size;
}
return -4;
}
/* "chandra:desktop/<iface>@<ver>" -> <iface> (copied, NUL-terminated); "" for anything else. */
static void iface_of(const wasm_name_t *m, char *out, size_t cap) {
const char *pre = "chandra:desktop/";
size_t pl = strlen(pre);
out[0] = 0;
if (m->size <= pl || memcmp(m->data, pre, pl) != 0) return;
size_t n = 0;
while (pl + n < m->size && m->data[pl + n] != '@' && n + 1 < cap) { out[n] = m->data[pl + n]; n++; }
out[n] = 0;
}
static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
char iface[64], fn[64];
iface_of(m, iface, sizeof(iface));
size_t fl = f->size < sizeof(fn) - 1 ? f->size : sizeof(fn) - 1;
memcpy(fn, f->data, fl);
fn[fl] = 0;
if (!strcmp(iface, "theme") && !strcmp(fn, "get-tokens")) return K_TOKENS;
if (!strcmp(iface, "clock") && !strcmp(fn, "now")) return K_CLOCK;
if (!strcmp(iface, "app-catalog") && !strcmp(fn, "list-apps")) return K_APPS;
if (!strcmp(iface, "app-launch") && !strcmp(fn, "launch")) return K_LAUNCH;
if (!strcmp(iface, "windows") && !strcmp(fn, "list-windows")) return K_WINDOWS;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus-window")) return K_FOCUS;
if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID;
if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ;
if (!strcmp(iface, "battery") && !strcmp(fn, "read")) return K_BAT_READ;
if (!strcmp(iface, "icons") && !strcmp(fn, "app-icon")) return K_APP_ICON;
if (!strcmp(iface, "session") && !strcmp(fn, "logout")) return K_LOGOUT;
if (!strcmp(iface, "session") && !strcmp(fn, "reload")) return K_RELOAD;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "wallpapers")) return K_WALLPAPERS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-wallpaper")) return K_WALLPAPER_CUR;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-wallpaper")) return K_SET_WALLPAPER;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "desktops")) return K_DESKTOPS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-desktop")) return K_DESKTOP_CUR;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-desktop")) return K_SET_DESKTOP;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "status")) return K_FU_STATUS;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "faces")) return K_FU_FACES;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "enroll")) return K_FU_ENROLL;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "remove")) return K_FU_REMOVE;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "set-in-use")) return K_FU_SET_IN_USE;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "refresh")) return K_FU_REFRESH;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "take")) return K_SHOT_TAKE;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "start-recording")) return K_SHOT_RECORD;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "stop-recording")) return K_SHOT_STOP;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "is-recording")) return K_SHOT_IS_REC;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "records-pointer")) return K_SHOT_PTR;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "set-records-pointer")) return K_SHOT_SET_PTR;
if (!strcmp(iface, "power") && !strcmp(fn, "screen-off-minutes")) return K_PW_SCREEN;
if (!strcmp(iface, "power") && !strcmp(fn, "set-screen-off-minutes")) return K_PW_SET_SCREEN;
if (!strcmp(iface, "power") && !strcmp(fn, "suspend-minutes")) return K_PW_SUSP;
if (!strcmp(iface, "power") && !strcmp(fn, "set-suspend-minutes")) return K_PW_SET_SUSP;
if (!strcmp(iface, "power") && !strcmp(fn, "suspend")) return K_PW_SUSPEND;
if (!strcmp(iface, "power") && !strcmp(fn, "power-off")) return K_PW_OFF;
if (!strcmp(iface, "power") && !strcmp(fn, "reboot")) return K_PW_REBOOT;
if (!strcmp(iface, "shortcuts") && !strcmp(fn, "shortcuts")) return K_SC_LIST;
if (!strcmp(iface, "shortcuts") && !strcmp(fn, "capture")) return K_SC_CAPTURE;
if (!strcmp(iface, "shortcuts") && !strcmp(fn, "cancel-capture")) return K_SC_CANCEL;
if (!strcmp(iface, "shortcuts") && !strcmp(fn, "reset")) return K_SC_RESET;
if (!strcmp(iface, "shortcuts") && !strcmp(fn, "reset-all")) return K_SC_RESET_ALL;
if (!strcmp(iface, "default-apps") && !strcmp(fn, "categories")) return K_DA_CATS;
if (!strcmp(iface, "default-apps") && !strcmp(fn, "apps")) return K_DA_APPS;
if (!strcmp(iface, "default-apps") && !strcmp(fn, "set-default")) return K_DA_SET;
if (!strcmp(iface, "default-apps") && !strcmp(fn, "refresh")) return K_DA_REFRESH;
if (!strcmp(iface, "network") && !strcmp(fn, "status")) return K_NET_STATUS;
if (!strcmp(iface, "network") && !strcmp(fn, "wifi-networks")) return K_NET_LIST;
if (!strcmp(iface, "network") && !strcmp(fn, "scan")) return K_NET_SCAN;
if (!strcmp(iface, "network") && !strcmp(fn, "connect")) return K_NET_CONNECT;
if (!strcmp(iface, "network") && !strcmp(fn, "disconnect")) return K_NET_DISCONNECT;
if (!strcmp(iface, "network") && !strcmp(fn, "forget")) return K_NET_FORGET;
if (!strcmp(iface, "network") && !strcmp(fn, "set-wifi-enabled")) return K_NET_SET_WIFI;
if (!strcmp(iface, "network") && !strcmp(fn, "set-airplane-mode")) return K_NET_SET_AIRPLANE;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
if (!strcmp(iface, "inspector") && !strcmp(fn, "is-on")) return K_INSPECT_IS_ON;
if (!strcmp(iface, "inspector") && !strcmp(fn, "set-on")) return K_INSPECT_SET;
if (!strcmp(iface, "modules") && !strcmp(fn, "available")) return K_MOD_AVAILABLE;
if (!strcmp(iface, "modules") && !strcmp(fn, "loaded")) return K_MOD_LOADED;
if (!strcmp(iface, "modules") && !strcmp(fn, "load-module")) return K_MOD_LOAD;
if (!strcmp(iface, "modules") && !strcmp(fn, "unload-instance")) return K_MOD_UNLOAD;
if (!strcmp(iface, "modules") && !strcmp(fn, "move-instance")) return K_MOD_MOVE;
if (!strcmp(iface, "modules") && !strcmp(fn, "browse")) return K_MOD_BROWSE;
return K_OTHER;
}
/* Remember which host interfaces a module imports (its capabilities). */
static void note_import(Inst *in, const wasm_name_t *m) {
char iface[64];
iface_of(m, iface, sizeof(iface));
if (!iface[0] || !strcmp(iface, "types")) return;
size_t have = strlen(in->imports);
/* already listed? */
for (const char *p = in->imports; *p;) {
const char *nl = strchr(p, '\n');
size_t l = nl ? (size_t)(nl - p) : strlen(p);
if (l == strlen(iface) && !memcmp(p, iface, l)) return;
p += l + (nl ? 1 : 0);
}
if (have + strlen(iface) + 2 < sizeof(in->imports)) {
memcpy(in->imports + have, iface, strlen(iface));
in->imports[have + strlen(iface)] = '\n';
in->imports[have + strlen(iface) + 1] = 0;
}
}
static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len) {
wasm_byte_vec_t bin;
wasm_byte_vec_new(&bin, len, (const wasm_byte_t *)bytes);
wasm_module_t *mod = wasm_module_new(store, &bin);
wasm_byte_vec_delete(&bin);
if (!mod) return 0;
wasm_exporttype_vec_t ets;
wasm_module_exports(mod, &ets);
int has_render = 0;
for (size_t i = 0; i < ets.size; i++) {
const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]);
if (nm->size == strlen(ex_names[EX_RENDER]) && memcmp(nm->data, ex_names[EX_RENDER], nm->size) == 0) has_render = 1;
}
if (!has_render) { wasm_exporttype_vec_delete(&ets); wasm_module_delete(mod); return 0; }
wasm_importtype_vec_t its;
wasm_module_imports(mod, &its);
wasm_extern_vec_t imports;
wasm_extern_vec_new_uninitialized(&imports, its.size);
for (size_t i = 0; i < its.size; i++) {
const wasm_name_t *m = wasm_importtype_module(its.data[i]);
const wasm_name_t *f = wasm_importtype_name(its.data[i]);
const wasm_externtype_t *et = wasm_importtype_type(its.data[i]);
Env *env = (Env *)calloc(1, sizeof(Env));
env->inst = in;
env->kind = classify_import(m, f);
note_import(in, m);
if (wasm_externtype_kind(et) == WASM_EXTERN_FUNC) {
wasm_func_t *fn = wasm_func_new_with_env(store, wasm_externtype_as_functype_const(et), host_import, env, NULL);
imports.data[i] = wasm_func_as_extern(fn);
} else {
/* tables/memories/globals are not expected from plasmoids */
wasm_extern_vec_delete(&imports);
wasm_importtype_vec_delete(&its);
wasm_exporttype_vec_delete(&ets);
wasm_module_delete(mod);
return 0;
}
}
wasm_trap_t *trap = NULL;
wasm_instance_t *inst = wasm_instance_new(store, mod, &imports, &trap);
wasm_extern_vec_delete(&imports);
wasm_importtype_vec_delete(&its);
if (!inst) {
if (trap) wasm_trap_delete(trap);
wasm_exporttype_vec_delete(&ets);
wasm_module_delete(mod);
return 0;
}
wasm_extern_vec_t exps;
wasm_instance_exports(inst, &exps);
for (size_t i = 0; i < ets.size && i < exps.size; i++) {
const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]);
wasm_extern_t *x = exps.data[i];
if (wasm_extern_kind(x) == WASM_EXTERN_MEMORY && nm->size == 6 && memcmp(nm->data, "memory", 6) == 0) {
in->memory = wasm_extern_as_memory(x);
} else if (wasm_extern_kind(x) == WASM_EXTERN_FUNC) {
for (int k = 0; k < EX_N; k++) {
if (nm->size == strlen(ex_names[k]) && memcmp(nm->data, ex_names[k], nm->size) == 0) in->ex[k] = wasm_extern_as_func(x);
}
}
}
wasm_exporttype_vec_delete(&ets);
in->module = mod;
in->instance = inst;
return in->memory && in->ex[EX_INFO] && in->ex[EX_RENDER];
}
/* Load a plasmoid from `path`; returns a handle >= 0 or a negative error. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_load(moonbit_bytes_t path_bytes, moonbit_bytes_t tokens) {
char path[1024];
int32_t plen = Moonbit_array_length(path_bytes);
size_t pn = (size_t)plen < sizeof(path) - 1 ? (size_t)plen : sizeof(path) - 1;
memcpy(path, path_bytes, pn);
path[pn] = '\0';
if (!engine) {
engine = wasm_engine_new();
store = wasm_store_new(engine);
if (!store) return -10;
}
int h = -1;
for (int i = 0; i < MAX_INST; i++) if (!insts[i].used) { h = i; break; }
if (h < 0) return -11;
FILE *f = fopen(path, "rb");
if (!f) return -2;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
if (sz <= 8) { fclose(f); return -1; }
uint8_t *buf = (uint8_t *)malloc((size_t)sz);
if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -2; }
fclose(f);
Inst *in = &insts[h];
memset(in, 0, sizeof(*in));
int32_t tn = Moonbit_array_length(tokens);
memcpy(in->tokens, tokens, tn < 64 ? (size_t)tn : 64);
int rc = load_bytes(in, buf, (size_t)sz);
free(buf);
if (rc != 0) { memset(in, 0, sizeof(*in)); return rc; }
in->used = 1;
return h;
}
MOONBIT_FFI_EXPORT
void mp_wasm_set_tokens(int32_t h, moonbit_bytes_t tokens) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return;
int32_t tn = Moonbit_array_length(tokens);
memcpy(insts[h].tokens, tokens, tn < 64 ? (size_t)tn : 64);
}
MOONBIT_FFI_EXPORT
void mp_wasm_unload(int32_t h) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return;
if (insts[h].instance) wasm_instance_delete(insts[h].instance);
if (insts[h].module) wasm_module_delete(insts[h].module);
memset(&insts[h], 0, sizeof(Inst));
}
/* Call export `which` (EX_*) with up to 4 i32 args; returns the i32 result (0 for none), -1 on trap/missing. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_call(int32_t h, int32_t which, int32_t a0, int32_t a1, int32_t a2, int32_t a3) {
if (h < 0 || h >= MAX_INST || !insts[h].used || which < 0 || which >= EX_N) return -1;
wasm_func_t *fn = insts[h].ex[which];
if (!fn) return -1;
size_t np = wasm_func_param_arity(fn);
size_t nr = wasm_func_result_arity(fn);
wasm_val_t av[4] = { WASM_I32_VAL(a0), WASM_I32_VAL(a1), WASM_I32_VAL(a2), WASM_I32_VAL(a3) };
wasm_val_t rv[1] = { WASM_INIT_VAL };
wasm_val_vec_t args = { np > 4 ? 4 : np, av };
wasm_val_vec_t res = { nr > 1 ? 1 : nr, rv };
wasm_trap_t *trap = wasm_func_call(fn, &args, &res);
if (trap) {
if (getenv("MP_WASM_DEBUG")) { wasm_message_t m; wasm_trap_message(trap, &m); fprintf(stderr, "wasm trap: %.*s\n", (int)m.size, m.data); wasm_byte_vec_delete(&m); }
wasm_trap_delete(trap);
return -1;
}
return nr > 0 ? rv[0].of.i32 : 0;
}
/* Copy `len` bytes of guest memory at `off` into `out`. Returns 0 on success. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_read(int32_t h, int32_t off, int32_t len, moonbit_bytes_t out) {
if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0) return -1;
size_t size = wasm_memory_data_size(insts[h].memory);
if ((size_t)off + (size_t)len > size || len > Moonbit_array_length(out)) return -1;
memcpy(out, wasm_memory_data(insts[h].memory) + off, (size_t)len);
return 0;
}
/* ---- native file picker: zenity on the host session, output read through a pipe ---- */
MOONBIT_FFI_EXPORT
int32_t mp_pick_start(void) {
int fds[2];
if (pipe(fds) != 0) return -1;
signal(SIGCHLD, SIG_IGN);
pid_t pid = fork();
if (pid < 0) { close(fds[0]); close(fds[1]); return -1; }
if (pid == 0) {
setsid();
dup2(fds[1], 1);
close(fds[0]);
close(fds[1]);
int dn = open("/dev/null", O_WRONLY);
if (dn >= 0) dup2(dn, 2);
execlp("zenity", "zenity", "--file-selection", "--title=Load widget (.wasm)",
"--file-filter=WebAssembly widgets | *.wasm", "--file-filter=All files | *", (char *)NULL);
_exit(127);
}
close(fds[1]);
fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL, 0) | O_NONBLOCK);
return fds[0];
}
/* Read from a pipe: bytes read, 0 at EOF, -1 when nothing is available yet. */
MOONBIT_FFI_EXPORT
int32_t mp_fd_read(int32_t fd, moonbit_bytes_t out) {
ssize_t n = read(fd, out, (size_t)Moonbit_array_length(out));
if (n < 0) return -1;
return (int32_t)n;
}
MOONBIT_FFI_EXPORT
void mp_fd_close(int32_t fd) { close(fd); }
/* ---- host state a widget can read, and the one action it can ask for ---- */
/* Replace the 64-byte system.snapshot the guest's system.read returns. */
MOONBIT_FFI_EXPORT
void mp_wasm_set_system(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
memset(g_system, 0, sizeof(g_system));
memcpy(g_system, b, n < 64 ? (size_t)n : 64);
}
/* Replace the window list blob (see g_windows) served by windows.all. */
MOONBIT_FFI_EXPORT
void mp_wasm_set_windows(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
free(g_windows);
g_windows = (uint8_t *)malloc(n > 0 ? (size_t)n : 1);
g_windows_len = g_windows ? (size_t)n : 0;
if (g_windows) memcpy(g_windows, b, (size_t)n);
}
/* Window id a widget asked to focus since the last call, or -1. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_take_focus(void) {
int64_t id = g_focus_req;
g_focus_req = -1;
return id < 0 || id > 0x7fffffff ? -1 : (int32_t)id;
}
/* ---- host data + requests (see the tables/Req definitions above) ---- */
MOONBIT_FFI_EXPORT
void mp_host_set_table(int32_t which, moonbit_bytes_t data) {
if (which < 0 || which >= T_N) return;
int32_t n = Moonbit_array_length(data);
free(tables[which].data);
tables[which].data = (uint8_t *)malloc((size_t)n + 1);
memcpy(tables[which].data, data, (size_t)n);
tables[which].len = (size_t)n;
}
MOONBIT_FFI_EXPORT
void mp_host_set_int(int32_t which, int32_t v) {
if (which >= 0 && which < 24) host_ints[which] = v; /* 20: the desktop (wallpaper.current-desktop) */
}
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
MOONBIT_FFI_EXPORT
int32_t mp_host_req_pop(void) {
if (cur_req.s) memset(cur_req.s, 0, strlen(cur_req.s)); /* may hold a Wi-Fi password */
free(cur_req.s);
memset(&cur_req, 0, sizeof(cur_req));
if (req_head >= req_tail) return 0;
cur_req = reqs[req_head % MAX_REQ];
req_head++;
return cur_req.kind;
}
MOONBIT_FFI_EXPORT
int32_t mp_host_req_int(void) { return cur_req.n; }
MOONBIT_FFI_EXPORT
int32_t mp_host_req_str(moonbit_bytes_t out) {
if (!cur_req.s) return 0;
int32_t cap = Moonbit_array_length(out);
int32_t n = (int32_t)strlen(cur_req.s);
if (n > cap) n = cap;
memcpy(out, cur_req.s, (size_t)n);
return n;
}
/* Write `len` bytes into guest memory at `off`. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_write(int32_t h, int32_t off, moonbit_bytes_t src, int32_t len) {
if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0 || len > Moonbit_array_length(src)) return -1;
size_t size = wasm_memory_data_size(insts[h].memory);
if ((size_t)off + (size_t)len > size) return -1;
memcpy(wasm_memory_data(insts[h].memory) + off, src, (size_t)len);
return 0;
}
/* Newline-separated host interfaces the module imports; returns the byte count copied into `out`. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_imports(int32_t h, moonbit_bytes_t out) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return 0;
int32_t n = (int32_t)strlen(insts[h].imports);
int32_t cap = Moonbit_array_length(out);
if (n > cap) n = cap;
memcpy(out, insts[h].imports, (size_t)n);
return n;
}
/* Names of "*.wasm" files in `dir`, newline-separated, sorted. */
static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_list_wasm(moonbit_bytes_t dir_bytes) {
char dir[1024];
int32_t dl = Moonbit_array_length(dir_bytes);
size_t dn = (size_t)dl < sizeof(dir) - 1 ? (size_t)dl : sizeof(dir) - 1;
memcpy(dir, dir_bytes, dn);
dir[dn] = 0;
DIR *d = opendir(dir);
if (!d) return moonbit_make_bytes_raw(0);
char **names = NULL;
size_t count = 0, cap = 0;
struct dirent *e;
while ((e = readdir(d)) != NULL) {
size_t n = strlen(e->d_name);
if (n < 6 || strcmp(e->d_name + n - 5, ".wasm") != 0) continue;
if (count == cap) { cap = cap ? cap * 2 : 16; names = (char **)realloc(names, cap * sizeof(char *)); }
names[count++] = strdup(e->d_name);
}
closedir(d);
if (count > 1) qsort(names, count, sizeof(char *), cmp_str);
size_t len = 0;
for (size_t i = 0; i < count; i++) len += strlen(names[i]) + 1;
moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len);
size_t o = 0;
for (size_t i = 0; i < count; i++) {
size_t n = strlen(names[i]);
memcpy((char *)out + o, names[i], n);
o += n;
((char *)out)[o++] = '\n';
free(names[i]);
}
free(names);
return out;
}