MoonBit host for the compositor component on prebuilt libwasmtime (sys, font, raster)
CI / test (push) Failing after 17s

wasmhost/ runs build/compositor.wasm with wasmtime linked as the upstream C API
library (fetched by setup-toolchain.sh) instead of compiling it: a cold build is
about 4 s against about 2 min for host-wasm. sys and font reuse the native
compositor's packages; the rasteriser is a port of host-wasm/src/raster.rs with the
pixel work in C, SVG through nanosvg. Panel modules, --drm and --window come next;
host-wasm stays the working host until then.

wit: sys.append-file. The C API moves list<u8> as one dynamic value per byte and
wasmtime caps what one call may copy, so the component writes files over 1 MiB as
write-file plus appends (host-wasm implements it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
This commit is contained in:
Claude committed 2026-11-25 19:42:20 +00:00
1 parent 2636373a4f
commit 2f4ce827c3
26 files changed
+7592 -2

No files matched your search

+1
View File
@@ -12,3 +12,4 @@ host-wasm/target/
# moon rewrites these for whichever target was built last, so they differ run to run. A few
# (app, gfx, renderer, scene) were committed early and stay tracked; the rest are not.
compositor/*/pkg.generated.mbti
wasmhost/*/pkg.generated.mbti
+17 -1
View File
@@ -154,7 +154,23 @@ pub fn read_file_bytes(path : String) -> Bytes {
///|
pub fn write_file_bytes(path : String, data : Bytes) -> Int {
@hostsys.write_file(path, to_fixed(data))
// At most 1 MiB per call (see append-file in wit/host/sys.wit).
let chunk = 1 << 20
if data.length() <= chunk {
return @hostsys.write_file(path, to_fixed(data))
}
if @hostsys.write_file(path, to_fixed(data[0:chunk].to_owned())) != 0 {
return -1
}
let mut at = chunk
while at < data.length() {
let end = if at + chunk < data.length() { at + chunk } else { data.length() }
if @hostsys.append_file(path, to_fixed(data[at:end].to_owned())) != 0 {
return -1
}
at = end
}
0
}
///|
+9
View File
@@ -698,6 +698,15 @@ impl Host for State {
}
}
fn append_file(&mut self, path: String, data: Vec<u8>) -> i32 {
use std::io::Write;
let f = std::fs::OpenOptions::new().append(true).create(true).open(path);
match f.and_then(|mut f| f.write_all(&data)) {
Ok(()) => 0,
Err(_) => -1,
}
}
fn read_proc(&mut self, path: String) -> Vec<u8> {
// /proc and /sys files report size 0: read to EOF, capped at 64 KiB.
let Ok(f) = std::fs::File::open(path) else { return Vec::new() };
+3
View File
@@ -48,6 +48,9 @@ fn wasmImportReadFile(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/sys@0.1.0"
///|
fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "write-file"
///|
fn wasmImportAppendFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "append-file"
///|
fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/sys@0.1.0" "read-proc"
@@ -80,6 +80,11 @@ fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportAppendFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
@@ -2,6 +2,8 @@
package "chandra/desktop/interface/chandra/host/sys"
// Values
pub fn append_file(String, FixedArray[Byte]) -> Int32
pub fn close_fd(Int32) -> Unit
pub fn getenv(String) -> String
@@ -50,6 +52,8 @@ pub fn unix_listen(String) -> Int32
pub fn unlink(String) -> Unit
pub fn wait_readable(FixedArray[Int32], Int32) -> Int32
pub fn wall_time_field(Int32) -> Int32
pub fn write_file(String, FixedArray[Byte]) -> Int32
+15
View File
@@ -183,6 +183,21 @@ pub fn write_file(path : String, data : FixedArray[Byte]) -> Int {
mbt_ffi_free(ptr0)
return ret
}
///|
/// Append `data` to the file at `path` (created if missing): 0, or -1 on error.
pub fn append_file(path : String, data : FixedArray[Byte]) -> Int {
let ptr = mbt_ffi_str2ptr(path)
let ptr0 = mbt_ffi_bytes2ptr(data)
let result : Int = wasmImportAppendFile(ptr, path.length(), ptr0, data.length());
let ret = result
mbt_ffi_free(ptr)
mbt_ffi_free(ptr0)
return ret
}
///|
/// Contents of a small /proc or /sys file ("" when unreadable).
+5
View File
@@ -146,3 +146,8 @@ compositor-wasm:
host-wasm:
cd host-wasm && cargo build --release
# Build the MoonBit host for the compositor component (build/wasmhost): links the prebuilt wasmtime
# C API instead of compiling wasmtime. Work in progress: it will replace host-wasm.
wasmhost:
scripts/build-wasmhost.sh
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Build the MoonBit host for the compositor component: build/wasmhost.
# It links the prebuilt wasmtime C API (scripts/setup-toolchain.sh puts it in .tools/wasmtime-c-api)
# instead of compiling wasmtime, so a build takes seconds. Statically linked: nothing to install.
# scripts/build-wasmhost.sh
# build/wasmhost build/compositor.wasm --socket PATH [--window | --drm | --gfx-out PNG]
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH"
CAPI="$ROOT/.tools/wasmtime-c-api"
[ -f "$CAPI/lib/libwasmtime.a" ] || { echo "error: $CAPI missing; run scripts/setup-toolchain.sh" >&2; exit 1; }
command -v moon >/dev/null || { echo "error: moon not found" >&2; exit 1; }
export C_INCLUDE_PATH="$CAPI/include${C_INCLUDE_PATH:+:$C_INCLUDE_PATH}"
export LIBRARY_PATH="$CAPI/lib${LIBRARY_PATH:+:$LIBRARY_PATH}"
moon build --target native --release --warn-list -a wasmhost/bin
mkdir -p build
cp _build/native/release/build/wasmhost/bin/bin.exe build/wasmhost
echo "build/wasmhost $(stat -c %s build/wasmhost) bytes"
+11 -1
View File
@@ -30,5 +30,15 @@ if ! have wasmtime "$WASMTIME_VERSION"; then
curl -fsSL "https://github.com/bytecodealliance/wasmtime/releases/download/v$WASMTIME_VERSION/wasmtime-v$WASMTIME_VERSION-x86_64-linux.tar.xz" | tar xJ -C "$tmp"
cp "$tmp"/wasmtime-*/wasmtime "$BIN/"
fi
# The wasmtime C API (libwasmtime + headers) for the MoonBit host (wasmhost/), linked instead of
# compiling wasmtime from source: .tools/wasmtime-c-api/{include,lib}.
CAPI="$ROOT/.tools/wasmtime-c-api"
if [ "$(cat "$CAPI/VERSION" 2>/dev/null)" != "$WASMTIME_VERSION" ]; then
echo ">> wasmtime C API $WASMTIME_VERSION"
curl -fsSL "https://github.com/bytecodealliance/wasmtime/releases/download/v$WASMTIME_VERSION/wasmtime-v$WASMTIME_VERSION-x86_64-linux-c-api.tar.xz" | tar xJ -C "$tmp"
rm -rf "$CAPI"; mkdir -p "$CAPI"
cp -r "$tmp"/wasmtime-*-c-api/include "$tmp"/wasmtime-*-c-api/lib "$CAPI/"
echo "$WASMTIME_VERSION" > "$CAPI/VERSION"
fi
echo "installed into $BIN:"
"$BIN/wasm-tools" --version; "$BIN/wit-bindgen" --version; "$BIN/wasmtime" --version
"$BIN/wasm-tools" --version; "$BIN/wit-bindgen" --version; "$BIN/wasmtime" --version; echo "wasmtime C API $(cat "$CAPI/VERSION") in $CAPI"
+18
View File
@@ -0,0 +1,18 @@
Copyright (c) 2013-14 Mikko Mononen memon@inside.org
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
+3278
View File
File diff suppressed because it is too large. Load diff
+1472
View File
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
# wasmhost
The MoonBit host for the compositor component (`build/compositor.wasm`), replacing the Rust
`host-wasm/`. It links wasmtime as the prebuilt C API library (`libwasmtime.a` from the upstream
`wasmtime-v$WASMTIME_VERSION-x86_64-linux-c-api` release, fetched by `scripts/setup-toolchain.sh`
into `.tools/wasmtime-c-api`) instead of compiling wasmtime, so a cold build takes about 4 s
instead of about 2 minutes.
```
scripts/build-wasmhost.sh # or: just wasmhost -> build/wasmhost
build/wasmhost build/compositor.wasm --socket PATH --gfx-out frame.png
```
- `wt/`: the wasmtime C API (`wt_stub.c`) and the value encoding host calls cross as (`val.mbt`).
wasmtime's C API has no bindgen: every call goes through one callback with dynamic values, so
each import is a small handler from values to values. A `list<u8>` crosses as one dynamic value
per byte and wasmtime caps how much one call may copy (about 2.7 MB of `list<u8>`), so large
files are written as `write-file` plus `append-file` chunks.
- `bin/`: the interfaces of `wit/host`. Most of it is the native compositor's own packages:
`sys` is compositor/sys, glyphs come from compositor/font (stb_truetype). The rasteriser
(`raster.mbt`, pixel work in `raster_stub.c`) is a port of `host-wasm/src/raster.rs`; SVG icons
use nanosvg (`third_party/nanosvg`) where the Rust host used resvg.
Status: sys, font and raster work (`--gfx-out` frames match the Rust host's). Panel modules
(plasmoids), the login-session display (`--drm`) and the nested window are still to come.
`WASMHOST_TRACE=1` logs every host call.
+37
View File
@@ -0,0 +1,37 @@
/* Small pieces of the MoonBit host that need C. */
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "moonbit.h"
/* A line on stderr (the compositor's log). */
void wh_eprint(moonbit_bytes_t s) {
fwrite(s, 1, (size_t)Moonbit_array_length(s), stderr);
fputc('\n', stderr);
fflush(stderr);
}
/* No zombies from launched apps. */
void wh_ignore_sigchld(void) { signal(SIGCHLD, SIG_IGN); }
void wh_exit(int32_t code) {
fflush(stdout);
fflush(stderr);
exit(code);
}
/* Append `data` to the file at `path` (created if missing): 0, or -1 on error. */
int32_t wh_append_file(moonbit_bytes_t path, moonbit_bytes_t data) {
char p[4096];
size_t n = (size_t)Moonbit_array_length(path);
if (n >= sizeof p) return -1;
memcpy(p, path, n);
p[n] = 0;
FILE *f = fopen(p, "ab");
if (!f) return -1;
size_t len = (size_t)Moonbit_array_length(data);
int ok = fwrite(data, 1, len, f) == len;
return fclose(f) == 0 && ok ? 0 : -1;
}
+109
View File
@@ -0,0 +1,109 @@
///| The MoonBit host for the compositor component (build/compositor.wasm).
///
/// It runs the component with wasmtime, linked as the prebuilt C API library, and implements the
/// interfaces the component imports (wit/host): sys, font, raster, display and plasmoids. Most of
/// it is the native compositor's own packages (compositor/sys, font, kms, wasm, renderer), so the
/// native and wasm builds share one implementation of each.
///
/// wasmhost build/compositor.wasm --socket PATH [--window | --drm | --gfx-out PNG [--serve]]
///|
#borrow(s)
extern "C" fn c_eprint(s : Bytes) = "wh_eprint"
///|
extern "C" fn c_ignore_sigchld() = "wh_ignore_sigchld"
///|
extern "C" fn c_exit(code : Int) = "wh_exit"
///|
fn exit(code : Int) -> Unit {
c_exit(code)
}
///|
fn eprint(s : String) -> Unit {
c_eprint(@utf8.encode(s))
}
///| Every host function, by interface, in registration order (its id is its index).
let handlers : Array[(Array[@wt.Val]) -> Array[@wt.Val]] = []
///| "interface.function" of each handler, for WASMHOST_TRACE.
let handler_names : Array[String] = []
///|
fn register(
iface : String,
funcs : Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])],
) -> Unit {
let first = handlers.length()
for f in funcs {
handlers.push(f.1)
handler_names.push(iface + "." + f.0)
}
match @wt.define_funcs(iface, funcs.map(f => f.0), first) {
Ok(_) => ()
Err(e) => {
eprint("error: " + e)
exit(1)
}
}
}
///|
fn main {
let argv = @env.args()
let args : Array[String] = if argv.length() > 1 {
argv[1:].to_array()
} else {
[]
}
// First argument may be the component path; otherwise use the default build location.
let path = if args.length() > 0 && args[0].has_suffix(".wasm") {
args.remove(0)
} else {
"build/compositor.wasm"
}
if args.length() > 0 && args[0] == "--" {
args.remove(0) |> ignore
}
c_ignore_sigchld()
match @wt.load(path) {
Ok(_) => ()
Err(e) => {
eprint(
"error: cannot load \{path}: \{e}\n build it with `just compositor-wasm`",
)
exit(1)
}
}
if @sys.getenv("WASMHOST_TRACE") != "" {
@wt.set_handler(fn(id, a) {
eprint("> " + handler_names[id] + " " + a.length().to_string())
handlers[id](a)
})
} else {
@wt.set_handler(fn(id, a) { handlers[id](a) })
}
register("chandra:host/sys@0.1.0", sys_funcs())
register("chandra:host/font@0.1.0", font_funcs())
register("chandra:host/raster@0.1.0", raster_funcs())
register("chandra:host/display@0.1.0", display_funcs())
register("chandra:host/plasmoids@0.1.0", plasmoid_funcs())
match @wt.instantiate() {
Ok(_) => ()
Err(e) => {
eprint("error: " + e)
exit(1)
}
}
match @wt.call("", "run", [@wt.Val::strings(args)]) {
Ok(r) => exit(if r.length() > 0 { r[0].to_int() } else { 0 })
Err(e) => {
eprint("error: " + e)
exit(1)
}
}
}
+25
View File
@@ -0,0 +1,25 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/env" @env,
"moonbitlang/core/encoding/utf8" @utf8,
"moonbitlang/core/cmp" @cmp,
"chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/font" @font,
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/wasmhost/wt" @wt,
}
supported_targets = "-all+native"
pkgtype(kind: "executable")
// libwasmtime comes prebuilt (scripts/setup-toolchain.sh); scripts/build-wasmhost.sh puts it on
// the compiler's and linker's search paths. Linked statically: the binary needs nothing at runtime.
options(
"native-stub": [ "host_stub.c", "raster_stub.c" ],
link: {
"native": {
"cc-link-flags": "-l:libwasmtime.a -lpthread -ldl -lm",
},
},
)
+774
View File
@@ -0,0 +1,774 @@
///| `chandra:host/raster` and `chandra:host/font`: the compositor sends draw operations and window
/// surface ids; the pixels live here (raster_stub.c) and never cross the component boundary.
/// What to draw where (layers, the wallpaper cache, damage) is decided here, as in
/// host-wasm/src/raster.rs.
///|
extern "C" fn rs_resize(w : Int, h : Int) -> Int = "rs_resize"
///|
extern "C" fn rs_clear() = "rs_clear"
///|
extern "C" fn rs_set_clip(on : Int, x : Int, y : Int, w : Int, h : Int) = "rs_set_clip"
///|
extern "C" fn rs_fill_rect(
x : Int,
y : Int,
w : Int,
h : Int,
r : Int,
g : Int,
b : Int,
a : Int,
radius : Int,
) = "rs_fill_rect"
///|
extern "C" fn rs_stroke_rect(
x : Int,
y : Int,
w : Int,
h : Int,
r : Int,
g : Int,
b : Int,
a : Int,
width : Int,
radius : Int,
) = "rs_stroke_rect"
///|
extern "C" fn rs_line(
x0 : Int,
y0 : Int,
x1 : Int,
y1 : Int,
r : Int,
g : Int,
b : Int,
a : Int,
width : Int,
) = "rs_line"
///|
extern "C" fn rs_circle(
cx : Int,
cy : Int,
radius : Int,
r : Int,
g : Int,
b : Int,
a : Int,
filled : Int,
) = "rs_circle"
///| compositor/font's shim (stb_truetype); 0 on success.
#borrow(path)
extern "C" fn mp_font_load(slot : Int, path : Bytes) -> Int = "mp_font_load"
///|
extern "C" fn rs_font_loaded(slot : Int) = "rs_font_loaded"
///| Load the TTF file at `path` into `slot` (0..3).
fn font_load(slot : Int, path : String) -> Bool {
if slot < 0 || slot >= 4 {
return false
}
if mp_font_load(slot, @utf8.encode(path)) != 0 {
return false
}
rs_font_loaded(slot)
true
}
///|
extern "C" fn rs_font_has(slot : Int) -> Int = "rs_font_has"
///|
#borrow(info)
extern "C" fn rs_glyph_info(
slot : Int,
cp : Int,
size : Int,
info : FixedArray[Int],
) = "rs_glyph_info"
///|
#borrow(out)
extern "C" fn rs_glyph_coverage(
slot : Int,
cp : Int,
size : Int,
out : FixedArray[Byte],
) = "rs_glyph_coverage"
///|
extern "C" fn rs_draw_glyph(
slot : Int,
cp : Int,
size : Int,
pen : Int,
baseline : Int,
r : Int,
g : Int,
b : Int,
a : Int,
embolden : Int,
) = "rs_draw_glyph"
///|
#borrow(rgba)
extern "C" fn rs_image_put(
reuse : Int,
w : Int,
h : Int,
rgba : FixedArray[Byte],
) -> Int = "rs_image_put"
///|
#borrow(data)
extern "C" fn rs_image_svg(data : Bytes) -> Int = "rs_image_svg"
///|
extern "C" fn rs_draw_image(handle : Int, x : Int, y : Int, w : Int, h : Int) = "rs_draw_image"
///|
extern "C" fn rs_capture(
fd : Int,
offset : Int,
stride : Int,
w : Int,
h : Int,
format : Int,
) -> UInt = "rs_capture"
///|
extern "C" fn rs_release(id : UInt) = "rs_release"
///|
extern "C" fn rs_thumbnail(id : UInt, w : Int, h : Int, reuse : Int) -> Int = "rs_thumbnail"
///|
extern "C" fn rs_blit_surface(id : UInt, x : Int, y : Int, w : Int, h : Int) -> Int = "rs_blit_surface"
///|
extern "C" fn rs_save_backdrop() = "rs_save_backdrop"
///|
extern "C" fn rs_has_backdrop() -> Int = "rs_has_backdrop"
///|
extern "C" fn rs_copy_backdrop() = "rs_copy_backdrop"
///|
extern "C" fn rs_width() -> Int = "rs_width"
///|
extern "C" fn rs_height() -> Int = "rs_height"
///|
#borrow(out)
extern "C" fn rs_read_frame(out : FixedArray[Byte]) = "rs_read_frame"
///|
extern "C" fn rs_export_memfd() -> Int = "rs_export_memfd"
// ---------------------------------------------------------------- geometry
///|
struct R {
x : Int
y : Int
w : Int
h : Int
} derive(Eq, Show)
///|
fn R::empty(self : R) -> Bool {
self.w <= 0 || self.h <= 0
}
///|
fn rect_of(v : @wt.Val) -> R {
{
x: v.field("x").to_int(),
y: v.field("y").to_int(),
w: v.field("w").to_int(),
h: v.field("h").to_int(),
}
}
///| The overlap of two clips (None: no clip).
fn intersect(a : R?, b : R?) -> R? {
match (a, b) {
(None, k) | (k, None) => k
(Some(a), Some(b)) => {
let x0 = @cmp.maximum(a.x, b.x)
let y0 = @cmp.maximum(a.y, b.y)
let x1 = @cmp.minimum(a.x + a.w, b.x + b.w)
let y1 = @cmp.minimum(a.y + a.h, b.y + b.h)
Some({
x: x0,
y: y0,
w: @cmp.maximum(x1 - x0, 0),
h: @cmp.maximum(y1 - y0, 0),
})
}
}
}
///| The bounding box of two rectangles (an empty one counts for nothing).
fn union(a : R, b : R) -> R {
if a.empty() {
return b
}
if b.empty() {
return a
}
let x0 = @cmp.minimum(a.x, b.x)
let y0 = @cmp.minimum(a.y, b.y)
let x1 = @cmp.maximum(a.x + a.w, b.x + b.w)
let y1 = @cmp.maximum(a.y + a.h, b.y + b.h)
{ x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
}
///|
fn set_clip(k : R?) -> Unit {
match k {
Some(r) => rs_set_clip(1, r.x, r.y, r.w, r.h)
None => rs_set_clip(0, 0, 0, 0, 0)
}
}
// ---------------------------------------------------------------- text
///| The font slot for (bold, mono), and whether its glyphs must be emboldened (a face with no
/// bold instance gets drawn a pixel wider). Slots: 0 mono, 1 mono bold, 2 sans. None when no
/// face is loaded at all.
fn pick_face(bold : Bool, mono : Bool) -> (Int, Bool)? {
let has_mono = rs_font_has(0) != 0
let has_sans = rs_font_has(2) != 0
if !has_mono && !has_sans {
return None
}
let has_bold = has_mono && rs_font_has(1) != 0
Some(
if mono && has_mono {
if bold && has_bold {
(1, false)
} else {
(0, bold)
}
} else if has_sans {
(2, bold)
} else {
(0, bold)
},
)
}
///|
let glyph_info : FixedArray[Int] = FixedArray::make(5, 0)
///| Advance of `cp` in `slot`.
fn advance(slot : Int, cp : Int, size : Int) -> Int {
rs_glyph_info(slot, cp, size, glyph_info)
glyph_info[4]
}
///|
fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit {
let text = l.field("text").to_string()
let col = l.field("color")
let ca = col.field("a").to_int()
if text == "" || ca == 0 {
return
}
let size = @cmp.maximum(l.field("size").to_int(), 0)
let bold = l.field("bold").to_bool()
let mono = l.field("mono").to_bool()
let (slot, embolden) = match pick_face(bold, mono) {
Some(f) => f
None => return // no face loaded: nothing to draw with
}
let extra = if embolden { 1 } else { 0 }
let cps : Array[Int] = []
let mut total_w = 0
for ch in text {
let cp = ch.to_int()
cps.push(cp)
total_w += advance(slot, cp, size) + extra
}
let x = l.field("x").to_int() + ox
let start_x = match l.field("align").to_int() {
1 => x - total_w / 2
2 => x - total_w
_ => x
}
// `y` is the vertical centre of the text; centre the capital height ('H') on it.
let (cap_slot, _) = match pick_face(false, mono) {
Some(f) => f
None => return
}
rs_glyph_info(cap_slot, 72, size, glyph_info)
let baseline = l.field("y").to_int() + oy + -glyph_info[3] / 2
let r = col.field("r").to_int()
let g = col.field("g").to_int()
let b = col.field("b").to_int()
let mut pen = start_x
for cp in cps {
rs_draw_glyph(slot, cp, size, pen, baseline, r, g, b, ca, extra)
pen += advance(slot, cp, size) + extra
}
}
// ---------------------------------------------------------------- ops
///|
fn rgba(c : @wt.Val) -> (Int, Int, Int, Int) {
(
c.field("r").to_int(),
c.field("g").to_int(),
c.field("b").to_int(),
c.field("a").to_int(),
)
}
///| Draw `ops` offset by (ox, oy). `base` limits everything (the frame's damaged area); a
/// push-clip op replaces the clip within it.
fn draw_ops(ops : Array[@wt.Val], ox : Int, oy : Int, base : R?) -> Unit {
let stack : Array[R] = []
set_clip(base)
for op in ops {
guard op is Variant(name, payload)
match (name, payload) {
("fill-rect", Some(f)) => {
let a = rect_of(f.field("area"))
let (r, g, b, al) = rgba(f.field("color"))
rs_fill_rect(
a.x + ox,
a.y + oy,
a.w,
a.h,
r,
g,
b,
al,
f.field("radius").to_int(),
)
}
("stroke-rect", Some(s)) => {
let a = rect_of(s.field("area"))
let (r, g, b, al) = rgba(s.field("color"))
rs_stroke_rect(
a.x + ox,
a.y + oy,
a.w,
a.h,
r,
g,
b,
al,
s.field("width").to_int(),
s.field("radius").to_int(),
)
}
("draw-line", Some(s)) => {
let (r, g, b, al) = rgba(s.field("color"))
rs_line(
s.field("x0").to_int() + ox,
s.field("y0").to_int() + oy,
s.field("x1").to_int() + ox,
s.field("y1").to_int() + oy,
r,
g,
b,
al,
s.field("width").to_int(),
)
}
("draw-circle", Some(d)) => {
let (r, g, b, al) = rgba(d.field("color"))
rs_circle(
d.field("cx").to_int() + ox,
d.field("cy").to_int() + oy,
d.field("radius").to_int(),
r,
g,
b,
al,
if d.field("filled").to_bool() {
1
} else {
0
},
)
}
("draw-text", Some(l)) => draw_text(l, ox, oy)
("push-clip", Some(k)) => {
let k = rect_of(k)
stack.push({ x: k.x + ox, y: k.y + oy, w: k.w, h: k.h })
set_clip(intersect(Some(stack[stack.length() - 1]), base))
}
("pop-clip", _) => {
stack.pop() |> ignore
set_clip(
if stack.length() > 0 {
intersect(Some(stack[stack.length() - 1]), base)
} else {
base
},
)
}
("draw-image", Some(p)) => {
let a = rect_of(p.field("area"))
rs_draw_image(p.field("image").to_int(), a.x + ox, a.y + oy, a.w, a.h)
}
_ => ()
}
}
}
// ---------------------------------------------------------------- frames
///| A frame as the compositor sent it (the parts compared to find what changed).
struct Frame {
width : Int
height : Int
wallpaper : @wt.Val? // Some(ops) when sent with this frame
background : @wt.Val
windows : Array[@wt.Val]
panel : @wt.Val
popups : @wt.Val
}
///| The last frame drawn, and the wallpaper ops the cached backdrop was drawn from.
let prev_frame : Ref[Frame?] = Ref(None)
///|
let backdrop_ops : Ref[@wt.Val?] = Ref(None)
///| Room around a window for its drop shadow (4 px right, 6 px down) and a little slack.
const SHADOW_PAD : Int = 8
///| What a window covers on screen: its decoration and drop shadow, or just itself when fullscreen.
fn window_footprint(win : @wt.Val) -> R {
let g = rect_of(win.field("geometry"))
if win.field("fullscreen").to_bool() {
return g
}
let it = win.field("inset-top").to_int()
let ir = win.field("inset-right").to_int()
let ib = win.field("inset-bottom").to_int()
let il = win.field("inset-left").to_int()
{
x: g.x - il - SHADOW_PAD,
y: g.y - it - SHADOW_PAD,
w: g.w + il + ir + 2 * SHADOW_PAD,
h: g.h + it + ib + 2 * SHADOW_PAD,
}
}
///| The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must
/// be redrawn. Only window changes are narrowed down: any change to the wallpaper, desktop card,
/// panel or the set of windows redraws everything.
fn damage(prev : Frame, f : Frame) -> R? {
if prev.width != f.width ||
prev.height != f.height ||
prev.windows.length() != f.windows.length() {
return None
}
if f.background != prev.background || f.panel != prev.panel {
return None
}
if f.wallpaper is Some(ops) && prev.wallpaper != Some(ops) {
return None
}
let mut d : R = { x: 0, y: 0, w: 0, h: 0 }
for i, a in prev.windows {
let b = f.windows[i]
if a == b {
continue
}
d = union(d, union(window_footprint(a), window_footprint(b)))
}
if prev.popups != f.popups {
for p in prev.popups.to_list() {
d = union(d, rect_of(p.field("area")))
}
for p in f.popups.to_list() {
d = union(d, rect_of(p.field("area")))
}
}
Some(d)
}
///| Remember `f` as the last frame. Its wallpaper ops are kept from the frame that sent them, so
/// a later frame that resends the same wallpaper still compares equal.
fn keep_prev(f : Frame) -> Unit {
let wallpaper = match f.wallpaper {
Some(_) => f.wallpaper
None =>
match prev_frame.val {
Some(p) => p.wallpaper
None => None
}
}
prev_frame.val = Some({ ..f, wallpaper, })
}
///| Pixels redrawn by the last submit (for --profile).
let last_drawn : Ref[Int] = Ref(0)
///| Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top,
/// panel, then client popups. The same layering as the software renderer's `render_scene`. Only
/// the part that differs from the last frame is redrawn.
fn submit(v : @wt.Val) -> Unit {
let f : Frame = {
width: @cmp.maximum(v.field("width").to_int(), 1),
height: @cmp.maximum(v.field("height").to_int(), 1),
wallpaper: v.field("wallpaper").to_option(),
background: v.field("background"),
windows: v.field("windows").to_list(),
panel: v.field("panel"),
popups: v.field("popups"),
}
let w = f.width
let h = f.height
let resized = rs_resize(w, h) != 0
// The frame starts from the cached backdrop (which covers every pixel), so the buffer is only
// cleared when there is none.
let backdrop_ready = rs_has_backdrop() != 0 &&
(match (f.wallpaper, backdrop_ops.val) {
(None, Some(_)) => true
(Some(ops), Some(o)) => o == ops
_ => false
})
let clip : R? = match prev_frame.val {
Some(prev) if !resized && backdrop_ready =>
match damage(prev, f) {
Some(d) =>
match intersect(Some(d), Some({ x: 0, y: 0, w, h })) {
Some(k) if !k.empty() => Some(k)
_ => {
// Nothing on screen changed (a window off screen, say).
last_drawn.val = 0
keep_prev(f)
return
}
}
None => None
}
_ => None
}
if !resized && !backdrop_ready {
rs_clear()
}
last_drawn.val = match clip {
Some(k) => k.w * k.h
None => w * h
}
// 1. Wallpaper: drawn once, copied back while unchanged (only the damaged part).
match f.wallpaper {
Some(ops) =>
if backdrop_ready {
set_clip(clip)
rs_copy_backdrop()
} else {
draw_ops(ops.to_list(), 0, 0, None)
rs_save_backdrop()
backdrop_ops.val = Some(ops)
}
None =>
if rs_has_backdrop() != 0 {
set_clip(clip)
rs_copy_backdrop()
}
}
draw_ops(f.background.to_list(), 0, 0, clip)
// 2. Windows, bottom to top.
for win in f.windows {
let g = rect_of(win.field("geometry"))
if clip is Some(_) {
match intersect(Some(window_footprint(win)), clip) {
Some(r) if !r.empty() => ()
_ => continue
}
}
if !win.field("fullscreen").to_bool() {
let it = win.field("inset-top").to_int()
let ir = win.field("inset-right").to_int()
let ib = win.field("inset-bottom").to_int()
let il = win.field("inset-left").to_int()
let outer_x = g.x - il
let outer_y = g.y - it
let outer_w = g.w + il + ir
let outer_h = g.h + it + ib
// Subtle drop shadow: only the strips that stick out from under the window (and the part
// under the translucent title bar) are blended.
let strips : Array[R] = [
{ x: outer_x + outer_w, y: outer_y, w: 4, h: outer_h + 6 },
{ x: outer_x, y: outer_y + outer_h, w: outer_w + 4, h: 6 },
{ x: outer_x, y: outer_y, w: outer_w, h: it + 2 },
]
for s in strips {
match intersect(Some(s), clip) {
Some(k) if !k.empty() => {
set_clip(Some(k))
rs_fill_rect(outer_x + 4, outer_y + 6, outer_w, outer_h, 0, 0, 0, 80, 8)
}
_ => ()
}
}
draw_ops(win.field("deco").to_list(), outer_x, outer_y, clip)
}
set_clip(clip)
if rs_blit_surface(win.field("surface").to_uint(), g.x, g.y, g.w, g.h) == 0 {
rs_fill_rect(g.x, g.y, g.w, g.h, 0x1e, 0x29, 0x3b, 0xff, 0)
}
}
// 3. Panel (and its popups, menus and notices), then 4. client popups above everything.
draw_ops(f.panel.to_list(), 0, 0, clip)
set_clip(clip)
for p in f.popups.to_list() {
let a = rect_of(p.field("area"))
rs_blit_surface(p.field("surface").to_uint(), a.x, a.y, a.w, a.h) |> ignore
}
keep_prev(f)
}
// ---------------------------------------------------------------- images
///| Image handles by path (0: it failed, don't try again).
let image_paths : Map[String, Int] = {}
///| Biggest image side accepted from a file.
const MAX_IMAGE : Int = 1024
///| Load the PNG or SVG at `path` (an app icon); the same path gives the same handle. 0 on failure.
fn load_image(path : String) -> Int {
match image_paths.get(path) {
Some(h) => return h
None => ()
}
let b = @sys.read_file_bytes(path)
let h = if b.length() > 8 && b[0] == b'\x89' && b[1] == b'P' && b[2] == b'N' {
match @renderer.decode_png(b) {
Some(p) if p.width <= MAX_IMAGE && p.height <= MAX_IMAGE =>
rs_image_put(0, p.width, p.height, p.data)
_ => 0
}
} else if path.has_suffix(".svg") && b.length() > 0 {
rs_image_svg(b)
} else {
0
}
image_paths.set(path, h)
h
}
///|
fn is_path_image(h : Int) -> Bool {
for _, v in image_paths {
if v == h {
return true
}
}
false
}
// ---------------------------------------------------------------- the interfaces
///|
fn font_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
[
(
"load",
a => boolean(font_load(a[0].to_int(), a[1].to_string())),
),
(
"rasterise",
a => {
let (slot, cp, size) = (a[0].to_int(), a[1].to_int(), a[2].to_int())
let info = FixedArray::make(5, 0)
rs_glyph_info(slot, cp, size, info)
let cov = FixedArray::make(info[0] * info[1], b'\x00')
if cov.length() > 0 {
rs_glyph_coverage(slot, cp, size, cov)
}
[
Record([
("width", S32(info[0])),
("height", S32(info[1])),
("xoff", S32(info[2])),
("yoff", S32(info[3])),
("advance", S32(info[4])),
("coverage", @wt.Val::bytes(Bytes::from_fixedarray(cov))),
]),
]
},
),
]
}
///|
fn raster_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
[
(
"capture",
a => [
U32(
rs_capture(
a[0].to_int(),
a[1].to_int(),
a[2].to_int(),
a[3].to_int(),
a[4].to_int(),
a[5].to_int(),
),
),
],
),
(
"release",
a => {
rs_release(a[0].to_uint())
none
},
),
("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]),
(
"thumbnail",
a => {
let reuse = a[3].to_int()
let reuse = if is_path_image(reuse) { 0 } else { reuse }
[
U32(
rs_thumbnail(a[0].to_uint(), a[1].to_int(), a[2].to_int(), reuse).reinterpret_as_uint(),
),
]
},
),
(
"submit",
a => {
submit(a[0])
none
},
),
(
"read-frame",
_ => {
let out = FixedArray::make(rs_width() * rs_height() * 4, b'\x00')
rs_read_frame(out)
[@wt.Val::bytes(Bytes::from_fixedarray(out))]
},
),
("export-memfd", _ => s32(rs_export_memfd())),
]
}
+600
View File
@@ -0,0 +1,600 @@
/* The host's rasteriser (chandra:host/raster), pixel work in C.
*
* A port of host-wasm/src/raster.rs, itself a port of compositor/renderer, so a frame comes out
* pixel for pixel the same. raster.mbt decides what to draw (layers, damage, the wallpaper cache);
* this file owns the framebuffer, the captured client surfaces, the images and the glyph cache,
* and draws one primitive per call, inside the current clip.
*
* Glyphs come from stb_truetype through compositor/font's shim (mp_font_*); SVG icons from
* nanosvg (third_party/nanosvg). */
#define _GNU_SOURCE
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "moonbit.h"
#define NANOSVG_IMPLEMENTATION
#define NANOSVGRAST_IMPLEMENTATION
#include "../../third_party/nanosvg/nanosvg.h"
#include "../../third_party/nanosvg/nanosvgrast.h"
/* compositor/font/font_stub.c */
int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes);
void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info);
void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf);
/* ------------------------------------------------------------------ canvas */
static int32_t fb_w, fb_h;
static uint8_t *fb; /* RGBA8888 */
static int clip_on;
static int32_t clip_x, clip_y, clip_w, clip_h;
static inline int clamp_u8(int v) { return v < 0 ? 0 : v > 255 ? 255 : v; }
static inline int imin(int a, int b) { return a < b ? a : b; }
static inline int imax(int a, int b) { return a > b ? a : b; }
/* Resize the framebuffer (zeroed). 1 when the size changed. */
int32_t rs_resize(int32_t w, int32_t h) {
if (w < 1) w = 1;
if (h < 1) h = 1;
if (fb && w == fb_w && h == fb_h) return 0;
free(fb);
fb = calloc((size_t)w * h, 4);
fb_w = w;
fb_h = h;
return 1;
}
void rs_clear(void) { if (fb) memset(fb, 0, (size_t)fb_w * fb_h * 4); }
void rs_set_clip(int32_t on, int32_t x, int32_t y, int32_t w, int32_t h) {
clip_on = on;
clip_x = x; clip_y = y; clip_w = w; clip_h = h;
}
static inline void blend_pixel(int x, int y, int r, int g, int b, int a) {
if (x < 0 || y < 0 || x >= fb_w || y >= fb_h || a <= 0) return;
if (clip_on && (x < clip_x || y < clip_y || x >= clip_x + clip_w || y >= clip_y + clip_h)) return;
uint8_t *d = fb + ((size_t)y * fb_w + x) * 4;
if (a >= 255) {
d[0] = (uint8_t)r; d[1] = (uint8_t)g; d[2] = (uint8_t)b; d[3] = 0xff;
return;
}
int inv = 255 - a;
d[0] = (uint8_t)((r * a + d[0] * inv + 127) / 255);
d[1] = (uint8_t)((g * a + d[1] * inv + 127) / 255);
d[2] = (uint8_t)((b * a + d[2] * inv + 127) / 255);
d[3] = (uint8_t)clamp_u8(a + (d[3] * inv + 127) / 255);
}
/* Blend a colour over pixels [xa, xb) of row y; the span is already clipped. */
static void blend_span(int y, int xa, int xb, int r, int g, int b, int a) {
if (xa >= xb || a <= 0) return;
uint8_t *p = fb + ((size_t)y * fb_w + xa) * 4, *end = fb + ((size_t)y * fb_w + xb) * 4;
if (a >= 255) {
for (; p < end; p += 4) { p[0] = (uint8_t)r; p[1] = (uint8_t)g; p[2] = (uint8_t)b; p[3] = 0xff; }
return;
}
int inv = 255 - a, ra = r * a + 127, ga = g * a + 127, ba = b * a + 127;
for (; p < end; p += 4) {
p[0] = (uint8_t)((ra + p[0] * inv) / 255);
p[1] = (uint8_t)((ga + p[1] * inv) / 255);
p[2] = (uint8_t)((ba + p[2] * inv) / 255);
p[3] = (uint8_t)clamp_u8(a + (p[3] * inv + 127) / 255);
}
}
static int in_rounded_rect(int px, int py, int rx, int ry, int rw, int rh, int rad) {
if (px < rx || py < ry || px >= rx + rw || py >= ry + rh) return 0;
if (rad <= 0) return 1;
int r = imin(rad, imin(rw, rh) / 2);
if (r <= 0) return 1;
int x_left = rx + r, x_right = rx + rw - r - 1, y_top = ry + r, y_bot = ry + rh - r - 1;
#define CORNER(dx, dy) ((dx) * (dx) + (dy) * (dy) <= r * r)
if (px < x_left && py < y_top) return CORNER(x_left - px, y_top - py);
if (px > x_right && py < y_top) return CORNER(px - x_right, y_top - py);
if (px < x_left && py > y_bot) return CORNER(x_left - px, py - y_bot);
if (px > x_right && py > y_bot) return CORNER(px - x_right, py - y_bot);
#undef CORNER
return 1;
}
/* The part of the rect on the canvas and inside the clip. 0 when empty. */
static int visible(int x, int y, int w, int h, int *x0, int *y0, int *x1, int *y1) {
*x0 = imax(x, 0); *y0 = imax(y, 0);
*x1 = imin(x + w, fb_w); *y1 = imin(y + h, fb_h);
if (clip_on) {
*x0 = imax(*x0, clip_x); *y0 = imax(*y0, clip_y);
*x1 = imin(*x1, clip_x + clip_w); *y1 = imin(*y1, clip_y + clip_h);
}
return *x0 < *x1 && *y0 < *y1;
}
void rs_fill_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t radius) {
if (!fb || w <= 0 || h <= 0 || ca == 0) return;
int x0, y0, x1, y1;
if (!visible(x, y, w, h, &x0, &y0, &x1, &y1)) return;
if (radius <= 0) {
for (int yy = y0; yy < y1; yy++) blend_span(yy, x0, x1, cr, cg, cb, ca);
return;
}
int r = imin(radius, imin(w, h) / 2);
int x_left = x + r, x_right = x + w - r - 1, y_top = y + r, y_bot = y + h - r - 1;
for (int yy = y0; yy < y1; yy++) {
if (yy >= y_top && yy <= y_bot) { blend_span(yy, x0, x1, cr, cg, cb, ca); continue; }
int xx = x0;
while (xx < x1 && xx < x_left) {
if (in_rounded_rect(xx, yy, x, y, w, h, radius)) blend_span(yy, xx, xx + 1, cr, cg, cb, ca);
xx++;
}
int mid_a = imax(x_left, x0), mid_b = imin(x_right + 1, x1);
blend_span(yy, mid_a, mid_b, cr, cg, cb, ca);
xx = imax(imax(x_right + 1, x0), mid_a);
while (xx < x1) {
if (in_rounded_rect(xx, yy, x, y, w, h, radius)) blend_span(yy, xx, xx + 1, cr, cg, cb, ca);
xx++;
}
}
}
void rs_stroke_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t width, int32_t radius) {
if (!fb || w <= 0 || h <= 0 || width <= 0 || ca == 0) return;
int x0 = imax(x, 0), y0 = imax(y, 0), x1 = imin(x + w, fb_w), y1 = imin(y + h, fb_h);
int inner_x = x + width, inner_y = y + width, inner_w = w - width * 2, inner_h = h - width * 2;
int inner_r = radius > width ? radius - width : 0;
int cx0 = clip_on ? clip_x : 0, cx1 = clip_on ? clip_x + clip_w : fb_w;
int cy0 = clip_on ? clip_y : 0, cy1 = clip_on ? clip_y + clip_h : fb_h;
int mid_a = inner_y + inner_r, mid_b = inner_y + inner_h - inner_r;
for (int yy = y0; yy < y1; yy++) {
if (inner_w > 0 && inner_h > 0 && yy >= mid_a && yy < mid_b) {
if (yy >= cy0 && yy < cy1) {
int l0 = imax(x0, cx0), l1 = imin(imin(inner_x, x1), cx1);
blend_span(yy, l0, l1, cr, cg, cb, ca);
int r0 = imax(imax(inner_x + inner_w, x0), cx0);
blend_span(yy, r0, imin(x1, cx1), cr, cg, cb, ca);
}
continue;
}
for (int xx = x0; xx < x1; xx++) {
int in_outer = in_rounded_rect(xx, yy, x, y, w, h, radius);
int in_inner = inner_w > 0 && inner_h > 0 && in_rounded_rect(xx, yy, inner_x, inner_y, inner_w, inner_h, inner_r);
if (in_outer && !in_inner) blend_pixel(xx, yy, cr, cg, cb, ca);
}
}
}
void rs_line(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t width) {
if (!fb) return;
int half = width <= 1 ? 0 : width / 2;
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = dx + dy;
for (;;) {
for (int oy = -half; oy <= half; oy++)
for (int ox = -half; ox <= half; ox++) blend_pixel(x0 + ox, y0 + oy, cr, cg, cb, ca);
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; }
if (e2 <= dx) { err += dx; y0 += sy; }
}
}
void rs_circle(int32_t cx, int32_t cy, int32_t radius, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t filled) {
if (!fb || radius <= 0) return;
double rad = radius;
for (int dy = -radius - 1; dy <= radius + 1; dy++) {
for (int dx = -radius - 1; dx <= radius + 1; dx++) {
double dist = sqrt((double)(dx * dx + dy * dy));
double outer = rad + 0.5 - dist;
double cov = outer > 1.0 ? 1.0 : outer;
if (!filled) {
double inner = dist - (rad - 1.0 - 0.5);
double ic = inner > 1.0 ? 1.0 : inner;
if (ic < cov) cov = ic;
}
if (cov > 0.02) blend_pixel(cx + dx, cy + dy, cr, cg, cb, (int)round(ca * cov));
}
}
}
/* ------------------------------------------------------------------ glyphs */
typedef struct Glyph {
int32_t slot, cp, size;
int32_t w, h, xoff, yoff, advance;
uint8_t *coverage;
struct Glyph *next;
} Glyph;
#define GLYPH_BUCKETS 4096
static Glyph *glyphs[GLYPH_BUCKETS];
static int font_loaded[4];
static Glyph *glyph(int32_t slot, int32_t cp, int32_t size) {
uint32_t hsh = ((uint32_t)slot * 2654435761u) ^ ((uint32_t)cp * 40503u) ^ ((uint32_t)size * 977u);
Glyph **b = &glyphs[hsh % GLYPH_BUCKETS];
for (Glyph *g = *b; g; g = g->next)
if (g->slot == slot && g->cp == cp && g->size == size) return g;
Glyph *g = calloc(1, sizeof *g);
g->slot = slot; g->cp = cp; g->size = size;
int32_t info[5] = {0};
if (slot >= 0 && slot < 4 && font_loaded[slot]) mp_font_metrics(slot, cp, size, info);
g->w = info[0]; g->h = info[1]; g->xoff = info[2]; g->yoff = info[3]; g->advance = info[4];
if (g->w > 0 && g->h > 0) {
/* The shim checks the buffer's MoonBit length: hand it a real MoonBit byte string. */
moonbit_bytes_t buf = moonbit_make_bytes(g->w * g->h, 0);
mp_font_bitmap(slot, cp, size, g->w, g->h, buf);
g->coverage = malloc((size_t)g->w * g->h);
memcpy(g->coverage, buf, (size_t)g->w * g->h);
moonbit_decref(buf);
} else {
g->w = g->h = 0;
}
g->next = *b;
*b = g;
return g;
}
static void drop_glyphs(int32_t slot) {
for (int i = 0; i < GLYPH_BUCKETS; i++) {
Glyph **p = &glyphs[i];
while (*p) {
Glyph *g = *p;
if (g->slot == slot) { *p = g->next; free(g->coverage); free(g); }
else p = &g->next;
}
}
}
/* Slot `slot` now holds a newly loaded face (raster.mbt loads it with mp_font_load, which also
* links compositor/font's shim in). */
void rs_font_loaded(int32_t slot) {
if (slot < 0 || slot >= 4) return;
font_loaded[slot] = 1;
drop_glyphs(slot);
}
int32_t rs_font_has(int32_t slot) { return slot >= 0 && slot < 4 && font_loaded[slot]; }
/* Metrics into info: width, height, xoff, yoff, advance. */
void rs_glyph_info(int32_t slot, int32_t cp, int32_t size, int32_t *info) {
Glyph *g = glyph(slot, cp, size);
info[0] = g->w; info[1] = g->h; info[2] = g->xoff; info[3] = g->yoff; info[4] = g->advance;
}
/* The coverage bitmap (w * h bytes) into `out`. */
void rs_glyph_coverage(int32_t slot, int32_t cp, int32_t size, moonbit_bytes_t out) {
Glyph *g = glyph(slot, cp, size);
size_t n = (size_t)g->w * g->h, cap = (size_t)Moonbit_array_length(out);
if (g->coverage && n <= cap) memcpy(out, g->coverage, n);
}
void rs_draw_glyph(int32_t slot, int32_t cp, int32_t size, int32_t pen, int32_t baseline, int32_t cr, int32_t cg,
int32_t cb, int32_t ca, int32_t embolden) {
if (!fb) return;
Glyph *g = glyph(slot, cp, size);
for (int row = 0; row < g->h; row++) {
for (int col = 0; col < g->w; col++) {
int cov = g->coverage[row * g->w + col];
if (cov > 0) {
int px = pen + g->xoff + col, py = baseline + g->yoff + row;
blend_pixel(px, py, cr, cg, cb, ca * cov / 255);
if (embolden) blend_pixel(px + 1, py, cr, cg, cb, ca * cov / 255);
}
}
}
}
/* ------------------------------------------------------------------ images */
#define MAX_IMAGE 1024
typedef struct Sized { int32_t w, h; uint8_t *rgba; struct Sized *next; } Sized;
typedef struct {
int used;
int32_t w, h;
uint8_t *rgba; /* pixels, or NULL for an SVG */
NSVGimage *svg;
Sized *sized; /* the image at the sizes it was drawn at */
} Image;
static Image *images;
static int32_t n_images, cap_images;
/* Scale RGBA src (sw x sh) to w x h: average of the covered source pixels (alpha weighted), the
* nearest one when enlarging. Same as the software renderer. */
static uint8_t *scale_rgba(const uint8_t *src, int sw, int sh, int w, int h) {
uint8_t *out = calloc((size_t)w * h, 4);
for (int y = 0; y < h; y++) {
int y0 = y * sh / h, y1 = imax((y + 1) * sh / h, y0 + 1);
for (int x = 0; x < w; x++) {
int x0 = x * sw / w, x1 = imax((x + 1) * sw / w, x0 + 1);
int64_t r = 0, g = 0, b = 0, a = 0, n = 0;
for (int sy = y0; sy < y1; sy++) {
for (int sx = x0; sx < x1; sx++) {
const uint8_t *p = src + ((size_t)sy * sw + sx) * 4;
int64_t pa = p[3];
r += p[0] * pa; g += p[1] * pa; b += p[2] * pa; a += pa; n++;
}
}
if (a > 0) {
uint8_t *o = out + ((size_t)y * w + x) * 4;
o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n);
}
}
}
return out;
}
static void image_reset(Image *im) {
free(im->rgba);
if (im->svg) nsvgDelete(im->svg);
for (Sized *s = im->sized; s;) { Sized *n = s->next; free(s->rgba); free(s); s = n; }
memset(im, 0, sizeof *im);
}
static int32_t image_slot(int32_t reuse) {
if (reuse > 0 && reuse <= n_images) {
image_reset(&images[reuse - 1]);
images[reuse - 1].used = 1;
return reuse;
}
if (n_images == cap_images) {
cap_images = cap_images ? cap_images * 2 : 64;
images = realloc(images, sizeof(Image) * (size_t)cap_images);
}
memset(&images[n_images], 0, sizeof(Image));
images[n_images].used = 1;
return ++n_images;
}
/* Store w x h RGBA pixels as an image: overwrite `reuse` when it is an earlier handle, else add one. */
int32_t rs_image_put(int32_t reuse, int32_t w, int32_t h, moonbit_bytes_t rgba) {
if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0;
if ((size_t)Moonbit_array_length(rgba) < (size_t)w * h * 4) return 0;
int32_t id = image_slot(reuse);
Image *im = &images[id - 1];
im->w = w; im->h = h;
im->rgba = malloc((size_t)w * h * 4);
memcpy(im->rgba, rgba, (size_t)w * h * 4);
return id;
}
/* An SVG document (its bytes) as an image, rendered sharp at each size it is drawn at. 0 when it
* doesn't parse. */
int32_t rs_image_svg(moonbit_bytes_t data) {
size_t n = (size_t)Moonbit_array_length(data);
char *text = malloc(n + 1);
memcpy(text, data, n);
text[n] = 0;
NSVGimage *svg = nsvgParse(text, "px", 96.0f);
free(text);
if (!svg) return 0;
if (svg->width <= 0 || svg->height <= 0 || !svg->shapes) { nsvgDelete(svg); return 0; }
int32_t id = image_slot(0);
images[id - 1].svg = svg;
return id;
}
static uint8_t *render_svg(NSVGimage *svg, int w, int h) {
static NSVGrasterizer *rast;
if (!rast) rast = nsvgCreateRasterizer();
uint8_t *out = calloc((size_t)w * h, 4);
float k = fminf((float)w / svg->width, (float)h / svg->height);
float dx = ((float)w - svg->width * k) / 2.0f, dy = ((float)h - svg->height * k) / 2.0f;
nsvgRasterize(rast, svg, dx, dy, k, out, w, h, w * 4); /* straight (not premultiplied) RGBA */
return out;
}
static const uint8_t *image_sized(int32_t handle, int w, int h) {
if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return NULL;
if (handle <= 0 || handle > n_images || !images[handle - 1].used) return NULL;
Image *im = &images[handle - 1];
if (im->rgba && im->w == w && im->h == h) return im->rgba;
for (Sized *s = im->sized; s; s = s->next)
if (s->w == w && s->h == h) return s->rgba;
uint8_t *px = im->svg ? render_svg(im->svg, w, h) : im->rgba ? scale_rgba(im->rgba, im->w, im->h, w, h) : NULL;
if (!px) return NULL;
Sized *s = malloc(sizeof *s);
s->w = w; s->h = h; s->rgba = px; s->next = im->sized;
im->sized = s;
return px;
}
void rs_draw_image(int32_t handle, int32_t x0, int32_t y0, int32_t w, int32_t h) {
if (!fb) return;
const uint8_t *px = image_sized(handle, w, h);
if (!px) return;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
const uint8_t *p = px + ((size_t)y * w + x) * 4;
blend_pixel(x0 + x, y0 + y, p[0], p[1], p[2], p[3]);
}
}
/* ------------------------------------------------------------------ surfaces */
typedef struct Surface {
uint32_t id;
int32_t w, h;
uint8_t *rgba;
int opaque; /* every pixel has alpha 255: blits copy rows */
struct Surface *next;
} Surface;
#define SURF_BUCKETS 256
static Surface *surfaces[SURF_BUCKETS];
static uint32_t next_surface;
static Surface *surface(uint32_t id) {
for (Surface *s = surfaces[id % SURF_BUCKETS]; s; s = s->next)
if (s->id == id) return s;
return NULL;
}
/* Copy a client buffer (stride * height bytes at `offset` of the file behind fd, little-endian
* B, G, R, A/X) into a surface. 0 on failure. */
uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32_t h, int32_t format) {
if (fd < 0 || offset < 0 || stride <= 0 || w <= 0 || h <= 0 || stride < w * 4) return 0;
int64_t len = (int64_t)stride * h, end = offset + len;
struct stat st;
if (fstat(fd, &st) < 0 || st.st_size < end) return 0;
/* Mapping a large pool only reserves address space; just the pages copied are touched. */
uint8_t *p = mmap(NULL, (size_t)end, PROT_READ, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) return 0;
const uint8_t *src = p + offset;
uint8_t *rgba = malloc((size_t)w * h * 4);
int opaque = 1, xrgb = format == 1;
for (int y = 0; y < h; y++) {
const uint8_t *s = src + (size_t)y * stride;
uint8_t *d = rgba + (size_t)y * w * 4;
for (int x = 0; x < w; x++, s += 4, d += 4) {
d[0] = s[2]; d[1] = s[1]; d[2] = s[0];
d[3] = xrgb ? 0xff : s[3];
opaque &= d[3] == 0xff;
}
}
munmap(p, (size_t)end);
do { next_surface++; } while (next_surface == 0 || surface(next_surface));
Surface *sf = malloc(sizeof *sf);
sf->id = next_surface; sf->w = w; sf->h = h; sf->rgba = rgba; sf->opaque = opaque;
sf->next = surfaces[sf->id % SURF_BUCKETS];
surfaces[sf->id % SURF_BUCKETS] = sf;
return sf->id;
}
void rs_release(uint32_t id) {
Surface **p = &surfaces[id % SURF_BUCKETS];
while (*p) {
if ((*p)->id == id) { Surface *s = *p; *p = s->next; free(s->rgba); free(s); return; }
p = &(*p)->next;
}
}
int32_t rs_surface_count(void) {
int n = 0;
for (int i = 0; i < SURF_BUCKETS; i++) for (Surface *s = surfaces[i]; s; s = s->next) n++;
return n;
}
/* A w x h scaled copy of surface `id` as an image (see rs_image_put for `reuse`). */
int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) {
if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0;
Surface *s = surface(id);
if (!s) return 0;
uint8_t *px = scale_rgba(s->rgba, s->w, s->h, w, h);
int32_t img = image_slot(reuse);
images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px;
return img;
}
/* Draw surface `id` into (x, y, w, h). While a client catches up with a resize its buffer is
* smaller than the window: the buffer's bottom-right colour is extended over the rest.
* 0 when there is no such surface. */
int32_t rs_blit_surface(uint32_t id, int32_t dx, int32_t dy, int32_t dw, int32_t dh) {
Surface *s = surface(id);
if (!s) return 0;
if (!fb || s->w <= 0 || s->h <= 0 || dw <= 0 || dh <= 0) return 1;
if (s->w < dw || s->h < dh) {
const uint8_t *o = s->rgba + ((size_t)(s->h - 1) * s->w + (s->w - 1)) * 4;
rs_fill_rect(dx, dy, dw, dh, o[0], o[1], o[2], o[3], 0);
}
int copy_w = imin(s->w, dw), copy_h = imin(s->h, dh);
int c0 = imax(-dx, 0), c1 = imin(copy_w, fb_w - dx);
int r0 = imax(-dy, 0), r1 = imin(copy_h, fb_h - dy);
if (clip_on) {
c0 = imax(c0, clip_x - dx); c1 = imin(c1, clip_x + clip_w - dx);
r0 = imax(r0, clip_y - dy); r1 = imin(r1, clip_y + clip_h - dy);
}
if (c0 >= c1 || r0 >= r1) return 1;
for (int row = r0; row < r1; row++) {
const uint8_t *src = s->rgba + ((size_t)row * s->w + c0) * 4;
uint8_t *dst = fb + ((size_t)(dy + row) * fb_w + dx + c0) * 4;
size_t n = (size_t)(c1 - c0) * 4;
if (s->opaque) { memcpy(dst, src, n); continue; }
for (size_t i = 0; i < n; i += 4) {
int a = src[i + 3];
if (a >= 255) memcpy(dst + i, src + i, 4);
else if (a > 0) {
/* wl_shm ARGB8888 is premultiplied: the colour already carries its alpha. */
int inv = 255 - a;
dst[i] = (uint8_t)clamp_u8(src[i] + (dst[i] * inv + 127) / 255);
dst[i + 1] = (uint8_t)clamp_u8(src[i + 1] + (dst[i + 1] * inv + 127) / 255);
dst[i + 2] = (uint8_t)clamp_u8(src[i + 2] + (dst[i + 2] * inv + 127) / 255);
dst[i + 3] = (uint8_t)clamp_u8(a + (dst[i + 3] * inv + 127) / 255);
}
}
}
return 1;
}
/* ------------------------------------------------------------------ backdrop and output */
static uint8_t *backdrop;
static int32_t backdrop_w, backdrop_h;
/* Keep the framebuffer as the backdrop (wallpaper and desktop card). */
void rs_save_backdrop(void) {
free(backdrop);
backdrop = malloc((size_t)fb_w * fb_h * 4);
memcpy(backdrop, fb, (size_t)fb_w * fb_h * 4);
backdrop_w = fb_w;
backdrop_h = fb_h;
}
/* 1 when a backdrop of the framebuffer's size is kept. */
int32_t rs_has_backdrop(void) { return backdrop && backdrop_w == fb_w && backdrop_h == fb_h; }
/* Copy the backdrop back into the clip (or everywhere). */
void rs_copy_backdrop(void) {
if (!rs_has_backdrop()) return;
if (!clip_on) { memcpy(fb, backdrop, (size_t)fb_w * fb_h * 4); return; }
int x0 = imax(clip_x, 0), x1 = imin(clip_x + clip_w, fb_w);
int y0 = imax(clip_y, 0), y1 = imin(clip_y + clip_h, fb_h);
if (x0 >= x1) return;
for (int y = y0; y < y1; y++) {
size_t a = ((size_t)y * fb_w + x0) * 4;
memcpy(fb + a, backdrop + a, (size_t)(x1 - x0) * 4);
}
}
int32_t rs_width(void) { return fb_w; }
int32_t rs_height(void) { return fb_h; }
uint8_t *rs_pixels(void) { return fb; }
/* The framebuffer as RGBA8888 into `out` (w * h * 4 bytes). */
void rs_read_frame(moonbit_bytes_t out) {
size_t n = (size_t)fb_w * fb_h * 4;
if (fb && (size_t)Moonbit_array_length(out) >= n) memcpy(out, fb, n);
}
/* A new memfd holding the framebuffer as little-endian ARGB8888 (B, G, R, 255). -1 on failure. */
int32_t rs_export_memfd(void) {
if (!fb) return -1;
size_t n = (size_t)fb_w * fb_h * 4;
uint8_t *data = malloc(n);
for (size_t i = 0; i < n; i += 4) {
data[i] = fb[i + 2]; data[i + 1] = fb[i + 1]; data[i + 2] = fb[i]; data[i + 3] = 0xff;
}
int fd = memfd_create("chandra-frame", MFD_CLOEXEC);
if (fd < 0) { free(data); return -1; }
size_t done = 0;
while (done < n) {
ssize_t w = write(fd, data + done, n - done);
if (w <= 0) { close(fd); free(data); return -1; }
done += (size_t)w;
}
free(data);
return fd;
}
+48
View File
@@ -0,0 +1,48 @@
///| Interfaces not served yet (filled in stage by stage).
///|
fn display_wait_fds() -> Array[Int] {
[]
}
///|
fn display_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
[
("open", _ => [Option(None)]),
("poll", _ => [Bool(false)]),
("frame-ready", _ => [Bool(false)]),
("present", _ => none),
("present-frame", _ => none),
("set-cursor-shape", _ => none),
("take-input", _ => [List([])]),
("close", _ => none),
]
}
///|
fn plasmoid_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
[
("load", _ => [Result(false, Some(Str("not yet")))]),
("unload", _ => none),
("set-tokens", _ => none),
("render", _ => [List([])]),
("popup", _ => [Option(None)]),
("on-event", _ => [Bool(false)]),
("config-items", _ => [List([])]),
("set-config", _ => [Bool(false)]),
("publish-table", _ => none),
("publish-state", _ => none),
("publish-wallpaper", _ => none),
("publish-session-settings", _ => none),
("publish-screenshot", _ => none),
("publish-system", _ => none),
("publish-windows", _ => none),
("next-request", _ => [Option(None)]),
("take-focus-request", _ => [Option(None)]),
("list-wasm-files", _ => [List([])]),
("picker-start", _ => [Bool(false)]),
("picker-poll", _ => [Variant("cancelled", None)]),
]
}
+211
View File
@@ -0,0 +1,211 @@
///| `chandra:host/sys`: the OS surface, over compositor/sys's native implementation (the same
/// C shim the native compositor uses).
///|
#borrow(path, data)
extern "C" fn c_append_file(path : Bytes, data : Bytes) -> Int = "wh_append_file"
///| Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`.
let extra_fds : Map[Int, Array[Int]] = {}
///|
fn drop_extra_fds(sock : Int) -> Unit {
match extra_fds.get(sock) {
Some(left) => {
for f in left {
@sys.close_fd(f)
}
extra_fds.remove(sock)
}
None => ()
}
}
///|
fn s32(v : Int) -> Array[@wt.Val] {
[S32(v)]
}
///|
fn boolean(b : Bool) -> Array[@wt.Val] {
[Bool(b)]
}
///|
let none : Array[@wt.Val] = []
///|
fn sys_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
[
("unix-listen", a => s32(@sys.unix_listen(a[0].to_string()))),
("unix-accept", a => s32(@sys.unix_accept(a[0].to_int()))),
("unix-connect", a => s32(@sys.unix_connect(a[0].to_string()))),
(
"close-fd",
a => {
let fd = a[0].to_int()
if fd >= 0 {
// A closed client socket's number is reused by the next one: drop what it left.
drop_extra_fds(fd)
@sys.close_fd(fd)
}
none
},
),
(
"unlink",
a => {
@sys.unlink(a[0].to_string())
none
},
),
("poll-read", a => s32(@sys.poll_read(a[0].to_int(), a[1].to_int()))),
(
"wait-readable",
a => {
let fds = a[0].to_list().map(v => v.to_int())
for f in display_wait_fds() {
fds.push(f)
}
s32(@sys.wait_readable(fds, a[1].to_int()))
},
),
(
"recvmsg",
a => {
let fd = a[0].to_int()
// Fds from the previous read nobody took would leak: close them.
drop_extra_fds(fd)
let max_len = a[1].to_int()
let received = fn(count : Int, got : Int, data : Bytes) -> Array[@wt.Val] {
[
Record([
("count", S32(count)),
("fd", S32(got)),
("data", @wt.Val::bytes(data)),
]),
]
}
if max_len <= 0 {
return received(0, -1, b"")
}
let buf = FixedArray::make(max_len, b'\x00')
let (n, fds) = @sys.recvmsg_fds(fd, buf, max_len)
if n < 0 {
for f in fds {
@sys.close_fd(f)
}
return received(n, -1, b"")
}
let got = if fds.length() > 0 { fds[0] } else { -1 }
if fds.length() > 1 {
extra_fds.set(fd, fds[1:].to_array())
}
received(n, got, Bytes::from_fixedarray(buf, len=n))
},
),
(
"take-fd",
a => {
let sock = a[0].to_int()
match extra_fds.get(sock) {
Some(q) if q.length() > 0 => {
let f = q.remove(0)
if q.length() == 0 {
extra_fds.remove(sock)
}
s32(f)
}
_ => s32(-1)
}
},
),
(
"sendmsg",
a => {
let data = a[1].to_bytes()
if data.length() == 0 {
return s32(0)
}
s32(@sys.sendmsg_fd(a[0].to_int(), data, a[2].to_int()))
},
),
("memfd-create", a => s32(@sys.memfd_create(a[0].to_string(), a[1].to_int()))),
(
"pwrite",
a => {
let fd = a[0].to_int()
let data = a[1].to_bytes()
let off = a[2].to_int()
s32(
if off < 0 {
@sys.write_nonblock(fd, data)
} else {
@sys.pwrite_bytes(fd, data, off)
},
)
},
),
(
"mmap-read",
a => [@wt.Val::bytes(@sys.mmap_read(a[0].to_int(), a[1].to_int()))],
),
(
"mmap-read-at",
a => {
let (fd, off, len) = (a[0].to_int(), a[1].to_int(), a[2].to_int())
if fd < 0 || off < 0 || len <= 0 {
return [@wt.Val::bytes(b"")]
}
[@wt.Val::bytes(@sys.mmap_read_at(fd, off, len))]
},
),
(
"read-file",
a => [@wt.Val::bytes(@sys.read_file_bytes(a[0].to_string()))],
),
(
"write-file",
a => s32(@sys.write_file_bytes(a[0].to_string(), a[1].to_bytes())),
),
(
"append-file",
a => s32(c_append_file(@utf8.encode(a[0].to_string()), a[1].to_bytes())),
),
(
"read-proc",
a => [@wt.Val::bytes(@sys.read_proc_bytes(a[0].to_string()))],
),
("mkdir-p", a => boolean(@sys.mkdir_p(a[0].to_string()))),
(
"list-desktop-files",
a => [@wt.Val::strings(@sys.list_desktop_files(a[0].to_string()))],
),
(
"sleep-ms",
a => {
let ms = a[0].to_int()
if ms > 0 {
@sys.sleep_ms(ms)
}
none
},
),
("monotonic-ms", _ => [U64(@sys.monotonic_ms())]),
(
"log",
a => {
eprint(a[0].to_string())
none
},
),
("getpid", _ => s32(@sys.getpid())),
("wall-time-field", a => s32(@sys.wall_time_field(a[0].to_int()))),
("getenv", a => [Str(@sys.getenv(a[0].to_string()))]),
("has-exe", a => boolean(@sys.has_exe(a[0].to_string()))),
(
"spawn",
a => boolean(@sys.spawn(a[0].to_string(), a[1].to_string())),
),
]
}
+13
View File
@@ -0,0 +1,13 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/buffer" @buffer,
"moonbitlang/core/encoding/utf8" @utf8,
}
supported_targets = "-all+native"
// The wasmtime C API comes prebuilt from setup-toolchain.sh (.tools/wasmtime-c-api); build with
// scripts/build-wasmhost.sh, which points the C compiler and linker at it.
options(
"native-stub": [ "wt_stub.c" ],
)
+365
View File
@@ -0,0 +1,365 @@
///| A component-model value as it crosses to and from wasmtime (encoding in wt_stub.c).
pub(all) enum Val {
Bool(Bool)
S8(Int)
U8(Int)
S16(Int)
U16(Int)
S32(Int)
U32(UInt)
S64(Int64)
U64(UInt64)
F32(Float)
F64(Double)
Char(Char)
Str(String)
List(Array[Val])
Record(Array[(String, Val)])
Tuple(Array[Val])
Variant(String, Val?)
Enum(String)
Option(Val?)
Result(Bool, Val?)
Flags(Array[String])
/// A `list<u8>` (encoded as one blob rather than a value per byte).
Blob(Bytes)
} derive(Show, Eq)
///| A list of u8 (`list<u8>`) from bytes.
pub fn Val::bytes(b : Bytes) -> Val {
Blob(b)
}
///| A `list<string>`.
pub fn Val::strings(a : Array[String]) -> Val {
List(a.map(Str(_)))
}
///| Record field `name` (records are looked up by name, not position).
pub fn Val::field(self : Val, name : String) -> Val {
match self {
Record(fs) => {
for f in fs {
if f.0 == name {
return f.1
}
}
abort("record has no field \{name}")
}
_ => abort("not a record: field \{name}")
}
}
///|
pub fn Val::to_int(self : Val) -> Int {
match self {
S8(v) | U8(v) | S16(v) | U16(v) | S32(v) => v
U32(v) => v.reinterpret_as_int()
S64(v) => v.to_int()
U64(v) => v.to_int()
Bool(b) => if b { 1 } else { 0 }
Char(c) => c.to_int()
_ => abort("not an integer: \{self}")
}
}
///|
pub fn Val::to_uint(self : Val) -> UInt {
match self {
U32(v) => v
_ => self.to_int().reinterpret_as_uint()
}
}
///|
pub fn Val::to_bool(self : Val) -> Bool {
match self {
Bool(b) => b
_ => self.to_int() != 0
}
}
///|
pub fn Val::to_double(self : Val) -> Double {
match self {
F64(d) => d
F32(f) => f.to_double()
_ => self.to_int().to_double()
}
}
///|
pub fn Val::to_string(self : Val) -> String {
match self {
Str(s) | Enum(s) => s
_ => abort("not a string: \{self}")
}
}
///|
pub fn Val::to_list(self : Val) -> Array[Val] {
match self {
List(a) | Tuple(a) => a
_ => abort("not a list: \{self}")
}
}
///| A `list<u8>` as bytes.
pub fn Val::to_bytes(self : Val) -> Bytes {
if self is Blob(b) {
return b
}
let a = self.to_list()
let out = FixedArray::make(a.length(), b'\x00')
for i, v in a {
out[i] = v.to_int().to_byte()
}
Bytes::from_fixedarray(out)
}
///|
pub fn Val::to_option(self : Val) -> Val? {
match self {
Option(o) => o
_ => abort("not an option: \{self}")
}
}
// ---- encoding ----
///|
fn put_u32(buf : @buffer.Buffer, v : Int) -> Unit {
buf.write_int_le(v)
}
///|
fn put_str(buf : @buffer.Buffer, s : String) -> Unit {
let b = @utf8.encode(s)
put_u32(buf, b.length())
buf.write_bytes(b)
}
///|
fn kind(v : Val) -> Byte {
match v {
Bool(_) => 0
S8(_) => 1
U8(_) => 2
S16(_) => 3
U16(_) => 4
S32(_) => 5
U32(_) => 6
S64(_) => 7
U64(_) => 8
F32(_) => 9
F64(_) => 10
Char(_) => 11
Str(_) => 12
List(_) => 13
Record(_) => 14
Tuple(_) => 15
Variant(_, _) => 16
Enum(_) => 17
Option(_) => 18
Result(_, _) => 19
Flags(_) => 20
Blob(_) => 0x80
}
}
///|
fn enc(buf : @buffer.Buffer, v : Val) -> Unit {
buf.write_byte(kind(v))
match v {
Bool(b) => buf.write_byte(if b { b'\x01' } else { b'\x00' })
S8(x) | U8(x) => buf.write_byte(x.to_byte())
S16(x) | U16(x) => {
buf.write_byte(x.to_byte())
buf.write_byte((x >> 8).to_byte())
}
S32(x) => buf.write_int_le(x)
U32(x) => buf.write_uint_le(x)
S64(x) => buf.write_int64_le(x)
U64(x) => buf.write_uint64_le(x)
F32(x) => buf.write_float_le(x)
F64(x) => buf.write_double_le(x)
Char(c) => buf.write_int_le(c.to_int())
Str(s) | Enum(s) => put_str(buf, s)
List(a) | Tuple(a) => {
put_u32(buf, a.length())
for x in a {
enc(buf, x)
}
}
Record(fs) => {
put_u32(buf, fs.length())
for f in fs {
put_str(buf, f.0)
enc(buf, f.1)
}
}
Variant(name, p) => {
put_str(buf, name)
match p {
Some(x) => {
buf.write_byte(b'\x01')
enc(buf, x)
}
None => buf.write_byte(b'\x00')
}
}
Option(p) =>
match p {
Some(x) => {
buf.write_byte(b'\x01')
enc(buf, x)
}
None => buf.write_byte(b'\x00')
}
Result(ok, p) => {
buf.write_byte(if ok { b'\x01' } else { b'\x00' })
match p {
Some(x) => {
buf.write_byte(b'\x01')
enc(buf, x)
}
None => buf.write_byte(b'\x00')
}
}
Flags(names) => {
put_u32(buf, names.length())
for n in names {
put_str(buf, n)
}
}
Blob(b) => {
put_u32(buf, b.length())
buf.write_bytes(b)
}
}
}
///| Encode a message (a list of values: arguments or results).
pub fn encode(vals : Array[Val]) -> Bytes {
let buf = @buffer.new(size_hint=64)
put_u32(buf, vals.length())
for v in vals {
enc(buf, v)
}
buf.to_bytes()
}
// ---- decoding ----
///|
struct Reader {
b : Bytes
mut pos : Int
}
///|
fn Reader::u8(self : Reader) -> Int {
let v = self.b[self.pos].to_int()
self.pos += 1
v
}
///|
fn Reader::u32(self : Reader) -> UInt {
let p = self.pos
let v = self.b[p].to_uint() |
(self.b[p + 1].to_uint() << 8) |
(self.b[p + 2].to_uint() << 16) |
(self.b[p + 3].to_uint() << 24)
self.pos += 4
v
}
///|
fn Reader::u64(self : Reader) -> UInt64 {
let lo = self.u32().to_uint64()
let hi = self.u32().to_uint64()
lo | (hi << 32)
}
///|
fn Reader::str(self : Reader) -> String {
let n = self.u32().reinterpret_as_int()
let s = @utf8.decode_lossy(self.b[self.pos:self.pos + n])
self.pos += n
s
}
///|
fn Reader::val(self : Reader) -> Val {
match self.u8() {
0 => Bool(self.u8() != 0)
1 => {
let x = self.u8()
S8(if x >= 128 { x - 256 } else { x })
}
2 => U8(self.u8())
3 => {
let x = self.u8() | (self.u8() << 8)
S16(if x >= 32768 { x - 65536 } else { x })
}
4 => U16(self.u8() | (self.u8() << 8))
5 => S32(self.u32().reinterpret_as_int())
6 => U32(self.u32())
7 => S64(self.u64().reinterpret_as_int64())
8 => U64(self.u64())
9 => F32(Float::reinterpret_from_uint(self.u32()))
10 => F64(self.u64().reinterpret_as_double())
11 => Char(Int::unsafe_to_char(self.u32().reinterpret_as_int()))
12 => Str(self.str())
13 | 15 as k => {
let n = self.u32().reinterpret_as_int()
let a = Array::new(capacity=n)
for _ in 0..<n {
a.push(self.val())
}
if k == 13 {
List(a)
} else {
Tuple(a)
}
}
14 => {
let n = self.u32().reinterpret_as_int()
let a = Array::new(capacity=n)
for _ in 0..<n {
let name = self.str()
a.push((name, self.val()))
}
Record(a)
}
16 => {
let name = self.str()
Variant(name, if self.u8() != 0 { Some(self.val()) } else { None })
}
17 => Enum(self.str())
18 => Option(if self.u8() != 0 { Some(self.val()) } else { None })
19 => {
let ok = self.u8() != 0
Result(ok, if self.u8() != 0 { Some(self.val()) } else { None })
}
20 => {
let n = self.u32().reinterpret_as_int()
Flags(Array::makei(n, _ => self.str()))
}
0x80 => {
let n = self.u32().reinterpret_as_int()
let b = self.b[self.pos:self.pos + n].to_owned()
self.pos += n
Blob(b)
}
k => abort("unknown value kind \{k}")
}
}
///| Decode a message.
pub fn decode(b : Bytes) -> Array[Val] {
let r = { b, pos: 0 }
let n = r.u32().reinterpret_as_int()
Array::makei(n, _ => r.val())
}
+109
View File
@@ -0,0 +1,109 @@
///| Running a component with wasmtime (its C API, linked as a prebuilt library; see wt_stub.c).
///
/// The host registers its functions by interface with `define`, each under an id; calls from the
/// component reach the one handler given to `set_handler` as (id, arguments).
///|
extern "C" fn c_set_dispatch(f : FuncRef[(Int, Bytes) -> Bytes]) = "wt_set_dispatch"
///|
extern "C" fn c_last_error() -> Bytes = "wt_last_error"
///|
extern "C" fn c_init() -> Int = "wt_init"
///|
#borrow(path)
extern "C" fn c_load(path : Bytes) -> Int = "wt_load"
///|
#borrow(iface, names)
extern "C" fn c_define(iface : Bytes, names : Bytes, first_id : Int) -> Int = "wt_define"
///|
extern "C" fn c_instantiate() -> Int = "wt_instantiate"
///|
#borrow(iface, name, args)
extern "C" fn c_call(iface : Bytes, name : Bytes, args : Bytes) -> Bytes = "wt_call"
///| What a host function returns: its results (zero or one value).
let handler : Ref[(Int, Array[Val]) -> Array[Val]] = Ref(fn(id, _) {
abort("no handler for host function \{id}")
})
///|
fn dispatch(id : Int, args : Bytes) -> Bytes {
encode((handler.val)(id, decode(args)))
}
///|
fn last_error() -> String {
@utf8.decode_lossy(c_last_error())
}
///|
fn cstr(s : String) -> Bytes {
@utf8.encode(s)
}
///| Create the engine and load the component at `path`.
pub fn load(path : String) -> Result[Unit, String] {
if c_init() != 0 {
return Err(last_error())
}
c_set_dispatch(fn(id, args) { dispatch(id, args) })
if c_load(cstr(path)) != 0 {
return Err(last_error())
}
Ok(())
}
///| The function that serves every host import.
pub fn set_handler(f : (Int, Array[Val]) -> Array[Val]) -> Unit {
handler.val = f
}
///| Define functions `names` of interface `iface` ("" for root imports) with ids `first_id`,
/// `first_id + 1`, ...
pub fn define_funcs(
iface : String,
names : Array[String],
first_id : Int,
) -> Result[Unit, String] {
let joined = names.iter().fold(init="", fn(acc, n) {
if acc == "" {
n
} else {
acc + "\n" + n
}
})
if c_define(cstr(iface), cstr(joined), first_id) != 0 {
Err(last_error())
} else {
Ok(())
}
}
///|
pub fn instantiate() -> Result[Unit, String] {
if c_instantiate() != 0 {
Err(last_error())
} else {
Ok(())
}
}
///| Call export `name` (of interface `iface`, "" for a root export).
pub fn call(
iface : String,
name : String,
args : Array[Val],
) -> Result[Array[Val], String] {
let out = c_call(cstr(iface), cstr(name), encode(args))
if out.length() == 0 {
Err(last_error())
} else {
Ok(decode(out))
}
}
+414
View File
@@ -0,0 +1,414 @@
/* 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 <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[1024];
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 ---- */
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;
moonbit_bytes_t in = enc_message(args, nargs);
moonbit_bytes_t out = dispatch(id, in); /* takes `in` */
int bad = dec_message(out, results, nresults);
moonbit_decref(out);
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;
}
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;
}
+4
View File
@@ -44,6 +44,10 @@ interface sys {
read-file: func(path: string) -> list<u8>;
write-file: func(path: string, data: list<u8>) -> s32;
/// Append `data` to the file at `path` (created if missing): 0, or -1 on error. Large files go
/// out as write-file plus appends of at most 1 MiB, because a host built on wasmtime's C API
/// moves list<u8> as one dynamic value per byte and wasmtime caps what one call may copy.
append-file: func(path: string, data: list<u8>) -> s32;
/// Contents of a small /proc or /sys file ("" when unreadable).
read-proc: func(path: string) -> list<u8>;
mkdir-p: func(path: string) -> bool;