Compile the compositor to a wasm component, run by a small wasmtime host
CI / test (push) Failing after 22s

The whole compositor (Wayland server, window manager, scene, rasteriser, shell) now builds as
build/components/compositor.wasm: a component that imports only moonplasma:host/sys
(wit/host/sys.wit: sockets + SCM_RIGHTS, memfd, poll, spawn, files, clock) and exports run().
host-wasm/ is the native side: a wasmtime program implementing that interface with libc.

- compositor/sys: per-target backends (sys_native.mbt over the C shim, sys_wasm.mbt over the WIT
  imports) behind one API; wayland/nested/host/shell/scene/renderer/gfx build for wasm unchanged.
- compositor/app: the entry point (arg parsing + main loop) as a library for both targets;
  --serve keeps refreshing a PNG so a live compositor can be inspected without a display.
- compositor/font, compositor/wasm: wasm-side placeholders (bitmap font; no panel modules yet,
  since a component can't embed a second wasm runtime: that becomes a host import).
- scripts/gen-native-stubs.py: native stand-ins for wasm-only generated imports.
- just compositor-wasm / host-wasm / run-wasm.

Verified: foot connects to the component's socket and renders into it; native build and
tests unchanged (16/23, the same 7 need unbuilt panel modules).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-25 01:41:31 -08:00
1 parent 92d2b29889
commit 6aba9b6a4f
42 files changed
+3163 -10

No files matched your search

+1168
View File
File diff suppressed because it is too large. Load diff
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "moon-plasma-host"
version = "0.1.0"
edition = "2021"
description = "Runs the moon-plasma compositor wasm component (build/components/compositor.wasm) and gives it the OS surface it imports (wit/host/sys.wit)."
[dependencies]
libc = "0.2"
wasmtime = { version = "50", default-features = false, features = ["component-model", "cranelift", "runtime", "std"] }
[profile.release]
opt-level = 2
+42
View File
@@ -0,0 +1,42 @@
# moon-plasma-host
Runs the compositor **as a WebAssembly component**.
```
just compositor-wasm # build/components/compositor.wasm (the compositor, a component)
just host-wasm # host-wasm/target/release/moon-plasma-host (this crate)
just run-wasm # both, then run in a window on your current Wayland session
```
The component (`components/compositor`, entry in `compositor/app`) imports exactly one interface,
`moonplasma:host/sys` ([`wit/host/sys.wit`](../wit/host/sys.wit)), and exports `run(args) -> s32`.
It is the same MoonBit code as the native compositor: the Wayland server, window manager, scene,
rasteriser and shell. Only `compositor/sys` differs per target (`sys_native.mbt` over a C shim,
`sys_wasm.mbt` over the WIT imports). The component holds integer handles and bytes only; every real
file descriptor lives in this host, which implements `sys` with libc (sockets and `SCM_RIGHTS`,
`memfd`, `poll`, spawn, files, clock).
```
moon-plasma-host build/components/compositor.wasm --socket PATH [--theme PATH] [--window]
moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.png # one frame
moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.png --serve # keep refreshing it
```
## Status
Working: Wayland server (real clients such as `foot` run and draw), window management, decorations,
the desktop card, input routing, the nested window on the host session.
Not yet in the component (the native compositor still has these):
- **Panel modules.** The panel is built from wasm modules, which the native build runs with wasmer.
A component can't embed another runtime, so this becomes a host import: the host instantiates the
modules with wasmtime and hands the compositor their draw ops (`compositor/wasm/wasm_unsupported.mbt`
is the placeholder; the panel is empty until then).
- **Real fonts.** `compositor/font` uses a C rasteriser; the component falls back to the bitmap font
until the host offers glyphs (`compositor/font/font_wasm.mbt`).
- **DRM/KMS and libinput** (`--drm`), the login-session backend.
Regenerating the host bindings: `wit-bindgen moonbit wit/host --world compositor --out-dir . --gen-dir
components/compositor/gen --project-name moonplasma/desktop --ignore-module-file --ignore-stub`, then
`scripts/gen-native-stubs.py interface/moonplasma/host/sys` (the imports are wasm-only; this restores
the native stand-ins and the per-file targets).
+430
View File
@@ -0,0 +1,430 @@
//! Native host for the moon-plasma compositor component.
//!
//! The compositor is a wasm component (build/components/compositor.wasm) that imports exactly one
//! interface, `moonplasma:host/sys` (wit/host/sys.wit): sockets, memfd, poll, spawn, files, time.
//! This program is the other side of that interface. The component only ever holds integer
//! handles; every real file descriptor lives here.
//!
//! moon-plasma-host [--component PATH] [-- compositor args...]
//! moon-plasma-host build/components/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window
use std::ffi::CString;
use std::io::Read;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use wasmtime::component::{Component, HasSelf, Linker};
use wasmtime::{Config, Engine, Result, Store};
wasmtime::component::bindgen!({
path: "../wit/host",
world: "compositor",
});
use moonplasma::host::sys::{Host, Received};
#[derive(Default)]
struct State {
/// Address of the private session bus launched apps use (started on first spawn).
private_bus: Option<String>,
bus_tried: bool,
started: Option<std::time::Instant>,
}
fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) {
let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() };
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
let bytes = path.as_bytes();
let n = bytes.len().min(addr.sun_path.len() - 1);
for (i, b) in bytes[..n].iter().enumerate() {
addr.sun_path[i] = *b as libc::c_char;
}
(addr, std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t)
}
fn set_nonblock_cloexec(fd: i32) {
unsafe {
let fl = libc::fcntl(fd, libc::F_GETFL, 0);
if fl >= 0 {
libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
}
let fdfl = libc::fcntl(fd, libc::F_GETFD, 0);
if fdfl >= 0 {
libc::fcntl(fd, libc::F_SETFD, fdfl | libc::FD_CLOEXEC);
}
}
}
impl State {
/// A private session bus, so single-instance apps (Firefox, Kate, Dolphin...) don't forward
/// their launch to an instance on the host session. Dies with this process.
fn private_bus(&mut self) -> Option<String> {
if self.bus_tried {
return self.private_bus.clone();
}
self.bus_tried = true;
let mut cmd = Command::new("dbus-daemon");
cmd.args(["--session", "--nofork", "--print-address=1"])
.stdout(Stdio::piped())
.stderr(Stdio::null());
unsafe {
cmd.pre_exec(|| {
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
Ok(())
});
}
let mut child = cmd.spawn().ok()?;
let mut out = child.stdout.take()?;
let mut buf = [0u8; 256];
let n = out.read(&mut buf).unwrap_or(0);
std::mem::forget(child); // keep it running; PDEATHSIG ends it with us
std::mem::forget(out);
if n > 0 {
let s = String::from_utf8_lossy(&buf[..n]);
self.private_bus = s.lines().next().map(|l| l.to_string());
}
self.private_bus.clone()
}
}
impl Host for State {
fn unix_listen(&mut self, path: String) -> i32 {
let _ = std::fs::remove_file(&path);
unsafe {
let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0);
if fd < 0 {
return -1;
}
set_nonblock_cloexec(fd);
let (addr, len) = sockaddr_un(&path);
if libc::bind(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 || libc::listen(fd, 16) < 0 {
libc::close(fd);
return -1;
}
fd
}
}
fn unix_accept(&mut self, listen_fd: i32) -> i32 {
unsafe {
let fd = libc::accept(listen_fd, std::ptr::null_mut(), std::ptr::null_mut());
if fd < 0 {
return -1;
}
set_nonblock_cloexec(fd);
fd
}
}
fn unix_connect(&mut self, path: String) -> i32 {
unsafe {
let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0);
if fd < 0 {
return -1;
}
let (addr, len) = sockaddr_un(&path);
if libc::connect(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 {
libc::close(fd);
return -1;
}
fd
}
}
fn close_fd(&mut self, fd: i32) {
if fd >= 0 {
unsafe { libc::close(fd) };
}
}
fn unlink(&mut self, path: String) {
let _ = std::fs::remove_file(path);
}
fn poll_read(&mut self, fd: i32, timeout_ms: i32) -> i32 {
let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 };
let r = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
if r < 0 {
-1
} else if r == 0 {
0
} else if pfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 {
1
} else {
0
}
}
fn recvmsg(&mut self, fd: i32, max_len: u32) -> Received {
let mut data = vec![0u8; max_len as usize];
if data.is_empty() {
return Received { count: 0, fd: -1, data };
}
unsafe {
let mut iov = libc::iovec { iov_base: data.as_mut_ptr() as *mut _, iov_len: data.len() };
let space = libc::CMSG_SPACE((std::mem::size_of::<i32>() * 4) as u32) as usize;
let mut cbuf = vec![0u8; space];
let mut msg: libc::msghdr = std::mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = cbuf.as_mut_ptr() as *mut _;
msg.msg_controllen = space as _;
let n = libc::recvmsg(fd, &mut msg, 0);
if n < 0 {
let e = *libc::__errno_location();
let c = if e == libc::EAGAIN || e == libc::EWOULDBLOCK { -1 } else { -2 };
return Received { count: c, fd: -1, data: Vec::new() };
}
let mut got = -1;
let mut cm = libc::CMSG_FIRSTHDR(&msg);
while !cm.is_null() {
if (*cm).cmsg_level == libc::SOL_SOCKET && (*cm).cmsg_type == libc::SCM_RIGHTS {
let n_fds = ((*cm).cmsg_len as usize - libc::CMSG_LEN(0) as usize) / std::mem::size_of::<i32>();
let fds = libc::CMSG_DATA(cm) as *const i32;
for i in 0..n_fds {
let f = *fds.add(i);
if i == 0 {
got = f;
} else {
libc::close(f);
}
}
}
cm = libc::CMSG_NXTHDR(&msg, cm);
}
data.truncate(n as usize);
Received { count: n as i32, fd: got, data }
}
}
fn sendmsg(&mut self, fd: i32, data: Vec<u8>, send_fd: i32) -> i32 {
if data.is_empty() {
return 0;
}
unsafe {
let mut total = 0usize;
let mut with_fd = send_fd >= 0;
while total < data.len() {
let mut iov = libc::iovec {
iov_base: data.as_ptr().add(total) as *mut _,
iov_len: data.len() - total,
};
let space = libc::CMSG_SPACE(std::mem::size_of::<i32>() as u32) as usize;
let mut cbuf = vec![0u8; space];
let mut msg: libc::msghdr = std::mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
if with_fd {
msg.msg_control = cbuf.as_mut_ptr() as *mut _;
msg.msg_controllen = space as _;
let cm = libc::CMSG_FIRSTHDR(&msg);
(*cm).cmsg_level = libc::SOL_SOCKET;
(*cm).cmsg_type = libc::SCM_RIGHTS;
(*cm).cmsg_len = libc::CMSG_LEN(std::mem::size_of::<i32>() as u32) as _;
std::ptr::copy_nonoverlapping(&send_fd as *const i32 as *const u8, libc::CMSG_DATA(cm), 4);
}
let sent = libc::sendmsg(fd, &msg, libc::MSG_NOSIGNAL);
if sent < 0 {
let e = *libc::__errno_location();
if e == libc::EAGAIN || e == libc::EWOULDBLOCK {
let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 };
libc::poll(&mut pfd, 1, 50);
continue;
}
return -1;
}
total += sent as usize;
with_fd = false; // ancillary data goes with the first chunk only
}
total as i32
}
}
fn memfd_create(&mut self, name: String, size: i32) -> i32 {
let Ok(cname) = CString::new(name) else { return -1 };
unsafe {
let fd = libc::memfd_create(cname.as_ptr(), libc::MFD_CLOEXEC);
if fd < 0 {
return -1;
}
if size > 0 && libc::ftruncate(fd, size as libc::off_t) < 0 {
libc::close(fd);
return -1;
}
fd
}
}
fn pwrite(&mut self, fd: i32, data: Vec<u8>, offset: i32) -> i32 {
let w = unsafe { libc::pwrite(fd, data.as_ptr() as *const _, data.len(), offset as libc::off_t) };
if w < 0 { -1 } else { w as i32 }
}
fn mmap_read(&mut self, fd: i32, size: i32) -> Vec<u8> {
if fd < 0 || size <= 0 {
return Vec::new();
}
unsafe {
let mut st: libc::stat = std::mem::zeroed();
if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < size as i64 {
return Vec::new();
}
let p = libc::mmap(std::ptr::null_mut(), size as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0);
if p == libc::MAP_FAILED {
return Vec::new();
}
let out = std::slice::from_raw_parts(p as *const u8, size as usize).to_vec();
libc::munmap(p, size as usize);
out
}
}
fn read_file(&mut self, path: String) -> Vec<u8> {
std::fs::read(path).unwrap_or_default()
}
fn write_file(&mut self, path: String, data: Vec<u8>) -> i32 {
match std::fs::write(path, &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() };
let mut out = Vec::new();
let _ = f.take(65536).read_to_end(&mut out);
out
}
fn mkdir_p(&mut self, path: String) -> bool {
std::fs::create_dir_all(path).is_ok()
}
fn list_desktop_files(&mut self, dir: String) -> Vec<String> {
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
rd.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".desktop"))
.collect()
}
fn sleep_ms(&mut self, ms: i32) {
if ms > 0 {
std::thread::sleep(std::time::Duration::from_millis(ms as u64));
}
}
fn monotonic_ms(&mut self) -> u64 {
self.started.get_or_insert_with(std::time::Instant::now).elapsed().as_millis() as u64
}
fn log(&mut self, message: String) {
eprintln!("{message}");
}
fn getpid(&mut self) -> i32 {
std::process::id() as i32
}
fn wall_time_field(&mut self, which: i32) -> i32 {
unsafe {
let t = libc::time(std::ptr::null_mut());
let mut tm: libc::tm = std::mem::zeroed();
libc::localtime_r(&t, &mut tm);
match which {
0 => tm.tm_year + 1900,
1 => tm.tm_mon + 1,
2 => tm.tm_mday,
3 => tm.tm_hour,
4 => tm.tm_min,
5 => tm.tm_sec,
6 => tm.tm_wday,
_ => 0,
}
}
}
fn getenv(&mut self, name: String) -> String {
std::env::var(name).unwrap_or_default()
}
fn has_exe(&mut self, name: String) -> bool {
let ok = |p: &std::path::Path| {
CString::new(p.as_os_str().as_encoded_bytes())
.map(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) == 0 })
.unwrap_or(false)
};
if name.contains('/') {
return ok(std::path::Path::new(&name));
}
std::env::var_os("PATH")
.map(|p| std::env::split_paths(&p).any(|d| ok(&d.join(&name))))
.unwrap_or(false)
}
fn spawn(&mut self, cmd: String, display: String) -> bool {
let bus = self.private_bus();
let mut c = Command::new("/bin/sh");
c.arg("-c").arg(&cmd);
// Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak on
// the real session bus, so they keep it; everything else gets the private bus.
if let Some(b) = bus {
if !cmd.contains("flatpak run") {
c.env("DBUS_SESSION_BUS_ADDRESS", b);
}
}
c.env("WAYLAND_DISPLAY", display)
.env_remove("DISPLAY")
// Make toolkits pick our Wayland socket, not X11 or the host session.
.env("XDG_SESSION_TYPE", "wayland")
.env("QT_QPA_PLATFORM", "wayland")
.env("GDK_BACKEND", "wayland")
.env("SDL_VIDEODRIVER", "wayland")
.env("MOZ_ENABLE_WAYLAND", "1")
.env("ELECTRON_OZONE_PLATFORM_HINT", "wayland")
.env("CLUTTER_BACKEND", "wayland")
.stdin(Stdio::null());
unsafe {
c.pre_exec(|| {
libc::setsid();
libc::signal(libc::SIGCHLD, libc::SIG_DFL);
Ok(())
});
}
c.spawn().is_ok()
}
}
fn main() -> Result<()> {
let mut args: Vec<String> = std::env::args().skip(1).collect();
// First argument may be the component path; otherwise use the default build location.
let component_path = if args.first().map(|a| a.ends_with(".wasm")).unwrap_or(false) {
args.remove(0)
} else {
"build/components/compositor.wasm".to_string()
};
if args.first().map(|a| a == "--").unwrap_or(false) {
args.remove(0);
}
// No zombies from launched apps.
unsafe { libc::signal(libc::SIGCHLD, libc::SIG_IGN) };
let mut config = Config::new();
config.wasm_component_model(true);
let engine = Engine::new(&config)?;
let component = match Component::from_file(&engine, &component_path) {
Ok(c) => c,
Err(e) => {
eprintln!("error: cannot load {component_path}: {e}\n build it with `just compositor-wasm`");
std::process::exit(1);
}
};
let mut linker: Linker<State> = Linker::new(&engine);
moonplasma::host::sys::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
let mut store = Store::new(&engine, State::default());
let compositor = Compositor::instantiate(&mut store, &component, &linker)?;
let code = compositor.call_run(&mut store, &args)?;
std::process::exit(code);
}