Fix the memory leak that filled RAM and swap; launch monitor, memory log

wasmhost leaked the arguments of every host call. wt_stub.c handed them to
the MoonBit dispatcher expecting it to own them, but the compiler borrowed
the parameter, so nothing released them (about 600 kB/s in a test with one
busy terminal; a long session reached over 16 GB resident plus swap).
MoonBit now allocates the buffer and C copies into it.

Also:
- Unannotated pointer FFI parameters default to #owned, and none of these C
  functions released theirs, including the native KMS present (a whole frame
  each). Annotated #borrow; the wasmhost build now fails on that warning,
  which --warn-list -a had hidden.
- Watched launches forked the whole compositor, and each monitor kept a
  snapshot of its heap for the app's lifetime. It now posix_spawns a fresh
  copy of the binary that takes over before main.
- The host logs memory, window buffers and images once a minute.
- chandra-session keeps the previous log as session.log.1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hj5m35Lj6Rt9vwwLGZ
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-26 17:10:47 -08:00
1 parent 44688453d7
commit ada9850b8d
11 files changed
+182 -46

No files matched your search

+3 -1
View File
@@ -96,7 +96,9 @@ Settings > Session > Lighter animations overrides it, and `CHANDRA_FRAME_TRACE=1
`CHANDRA_DEBUG_CONFIGURE=1` (any host) logs each window's configures, acks and committed buffer
sizes, for an app that draws at the wrong size.
The installed session logs to `~/.local/state/chandra/session.log`. Start it as yourself, never
The installed session logs to `~/.local/state/chandra/session.log`. The session before is kept as
`session.log.1`, and the host writes a timestamped line once a minute with its memory use and the
window buffers and images it holds. Start it as yourself, never
as root: `chandra-session` refuses to run as root (`CHANDRA_ALLOW_ROOT=1` overrides). Installing
goes through `scripts/as-root`, which prefers run0 and falls back to sudo, doas or pkexec
(`CHANDRA_AS_ROOT` picks one). What it installs and its flags: [docs/install.md](docs/install.md). To run a graphical app as root inside Chandra, use
+1
View File
@@ -5,6 +5,7 @@
extern "C" fn c_font_load(slot : Int, path : Bytes) -> Int = "mp_font_load"
///|
#borrow(info)
extern "C" fn c_font_metrics(
slot : Int,
cp : Int,
+10
View File
@@ -85,6 +85,16 @@ test "an app that keeps running is not reported, and its output still reaches th
assert_eq(comp.shell.launch_fds().length(), 1)
}
///|
test "the launch monitor is a fresh process, not a copy of the compositor" {
let comp = new_comp("launch-monitor")
// The app's parent is the monitor: it prints that process's command line.
assert_true(comp.shell.start_app("who", "tr '\\0' ' ' < /proc/$PPID/cmdline; echo; exit 3"))
let lines = wait_notice(comp, 5000)
assert_true(lines[0].has_prefix("Could not start who: exited with status 3 after"))
assert_true(lines[2].has_prefix("chandra-launch-monitor "))
}
///|
test "problems chandra-session found at login show as an error notice" {
let comp = new_comp("session-errors")
+2
View File
@@ -23,6 +23,7 @@ extern "C" fn c_poll() -> Int = "mp_kms_poll"
extern "C" fn c_frame_ready() -> Int = "mp_kms_frame_ready"
///|
#borrow(pixels)
extern "C" fn c_present(pixels : FixedArray[Byte], w : Int, h : Int) -> Int = "mp_kms_present"
///|
@@ -38,6 +39,7 @@ extern "C" fn c_arg(i : Int) -> Int = "mp_kms_arg"
extern "C" fn c_keymap_len() -> Int = "mp_kms_keymap_len"
///|
#borrow(out)
extern "C" fn c_keymap_copy(out : FixedArray[Byte]) -> Int = "mp_kms_keymap_copy"
///|
+7
View File
@@ -238,9 +238,11 @@ pub fn wall_time_field(which : Int) -> Int {
}
///|
#borrow(name)
extern "C" fn c_has_exe(name : Bytes) -> Int = "mp_has_exe"
///|
#borrow(cmd, display)
extern "C" fn c_spawn(cmd : Bytes, display : Bytes) -> Int = "mp_spawn"
///| Whether `name` is an executable on PATH.
@@ -254,6 +256,7 @@ pub fn spawn(cmd : String, display : String) -> Bool {
}
///|
#borrow(argv)
extern "C" fn c_spawn_socket(argv : Bytes) -> Int = "mp_spawn_socket"
///| Run `argv` (an absolute program path, then its arguments) with its stdin and stdout on a
@@ -272,9 +275,11 @@ pub fn take_sigusr1() -> Bool {
}
///|
#borrow(dir)
extern "C" fn c_list_desktop(dir : Bytes) -> Bytes = "mp_list_desktop"
///|
#borrow(name)
extern "C" fn c_getenv(name : Bytes) -> Bytes = "mp_getenv"
///| Newline-separated names of the `*.desktop` files directly in `dir`.
@@ -306,6 +311,7 @@ pub fn getenv(name : String) -> String {
}
///|
#borrow(path)
extern "C" fn c_mkdir_p(path : Bytes) -> Int = "mp_mkdir_p"
///| Create `path` and any missing parents; true when it exists afterwards.
@@ -361,6 +367,7 @@ pub fn frame_memfd() -> Int {
}
///|
#borrow(cmd, display)
extern "C" fn c_spawn_watch(cmd : Bytes, display : Bytes) -> Int = "mp_spawn_watch"
///| Launch `cmd` like `spawn`, watched: returns a non-blocking socket (-1 when nothing could
+65 -33
View File
@@ -13,6 +13,7 @@
#include <sys/wait.h>
#include <time.h>
#include <signal.h>
#include <spawn.h>
#include <sys/prctl.h>
#include <dirent.h>
#include <unistd.h>
@@ -631,41 +632,33 @@ static int pump(int from, struct tail *t) {
}
}
/* Launch `cmd` like mp_spawn, watched: a small monitor process starts it with its stdout and
* stderr on a pipe, copies that output to our stderr (the session log, as before) and keeps its
* last 2 KiB. When `sh -c cmd` exits the monitor reports on the returned socket (non-blocking):
* "exit CODE MS\n" or "signal NUM MS\n" (MS = how long it ran), then the output tail.
* The socket closes after that. The monitor keeps copying output from anything the command left
* running, until nothing holds the pipe open. Returns our end, or -1 when nothing could start. */
MOONBIT_FFI_EXPORT
int32_t mp_spawn_watch(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) {
char cmd[2048];
char display[512];
bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd));
bytes_to_cstr(display_bytes, display, sizeof(display));
signal(SIGCHLD, SIG_IGN); /* the monitor is never our zombie */
start_private_bus();
int rep[2];
/* A socket, not a pipe: the compositor reads every fd it watches with recvmsg. */
if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, rep) != 0) return -1;
int out[2];
if (pipe2(out, O_CLOEXEC) != 0) { close(rep[0]); close(rep[1]); return -1; }
pid_t mon = fork();
if (mon < 0) { close(rep[0]); close(rep[1]); close(out[0]); close(out[1]); return -1; }
if (mon == 0) {
setsid();
/* ---- the launch monitor ----
* A watched launch runs this binary again, as MONITOR_ARG0 (monitor_entry takes over before
* anything else in the new process starts). It must not be a plain fork of the compositor: that
* child lives as long as the app does and keeps a snapshot of the compositor's whole heap, which
* stays allocated (and went to swap) as the compositor's own copy changes. */
#define MONITOR_ARG0 "chandra-launch-monitor"
#define MONITOR_FD 3 /* its end of the report socket */
/* Start `cmd` with its stdout and stderr on a pipe, copy that output to our stderr (the session
* log) and keep its last 2 KiB; report on `report` when it exits (see mp_spawn_watch). `bus` is
* the compositor's private session bus, "" when there is none. */
static void launch_monitor(const char *cmd, const char *display, const char *bus, int report) {
prctl(PR_SET_NAME, "chandra-launch");
signal(SIGCHLD, SIG_DFL);
signal(SIGPIPE, SIG_IGN); /* the compositor may stop listening; keep copying output */
/* Hold nothing of the compositor's (DRM, seat, client sockets) for the app's lifetime. */
for (int fd = 3; fd < 1024; fd++) {
if (fd != rep[1] && fd != out[0] && fd != out[1]) close(fd);
}
for (int fd = 3; fd < 1024; fd++)
if (fd != report) close(fd);
fcntl(report, F_SETFD, FD_CLOEXEC);
snprintf(private_bus, sizeof(private_bus), "%s", bus);
int out[2];
uint64_t t0 = mono_ms();
pid_t app = fork();
pid_t app = pipe2(out, O_CLOEXEC) == 0 ? fork() : -1;
if (app < 0) {
char msg[128];
int n = snprintf(msg, sizeof(msg), "exit 127 0\nfork failed: %s\n", strerror(errno));
write_all(rep[1], msg, (size_t)n);
write_all(report, msg, (size_t)n);
_exit(1);
}
if (app == 0) {
@@ -696,19 +689,58 @@ int32_t mp_spawn_watch(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes)
int n = WIFSIGNALED(st)
? snprintf(head, sizeof(head), "signal %d %llu\n", WTERMSIG(st), (unsigned long long)(mono_ms() - t0))
: snprintf(head, sizeof(head), "exit %d %llu\n", WEXITSTATUS(st), (unsigned long long)(mono_ms() - t0));
write_all(rep[1], head, (size_t)n);
write_all(report, head, (size_t)n);
fprintf(stderr, "chandra-launch: `%s` %s", cmd, head); /* "... exit 1 230\n" in the session log */
write_all(rep[1], t.buf, t.len);
close(rep[1]);
write_all(report, t.buf, t.len);
close(report);
reported = 1;
}
}
}
_exit(0);
}
/* glibc passes constructors main's arguments. */
__attribute__((constructor)) static void monitor_entry(int argc, char **argv) {
if (argc == 4 && argv && strcmp(argv[0], MONITOR_ARG0) == 0)
launch_monitor(argv[1], argv[2], argv[3], MONITOR_FD);
}
/* Launch `cmd` like mp_spawn, watched: a small monitor process (above) starts it with its stdout
* and stderr on a pipe, copies that output to our stderr (the session log, as before) and keeps its
* last 2 KiB. When `sh -c cmd` exits the monitor reports on the returned socket (non-blocking):
* "exit CODE MS\n" or "signal NUM MS\n" (MS = how long it ran), then the output tail.
* The socket closes after that. The monitor keeps copying output from anything the command left
* running, until nothing holds the pipe open. Returns our end, or -1 when nothing could start. */
MOONBIT_FFI_EXPORT
int32_t mp_spawn_watch(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) {
char cmd[2048];
char display[512];
bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd));
bytes_to_cstr(display_bytes, display, sizeof(display));
signal(SIGCHLD, SIG_IGN); /* the monitor is never our zombie */
start_private_bus();
int rep[2];
/* A socket, not a pipe: the compositor reads every fd it watches with recvmsg. */
if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, rep) != 0) return -1;
posix_spawn_file_actions_t actions;
posix_spawnattr_t attr;
posix_spawn_file_actions_init(&actions);
posix_spawnattr_init(&attr);
/* (Onto itself, when it already is MONITOR_FD, this clears close-on-exec.) */
posix_spawn_file_actions_adddup2(&actions, rep[1], MONITOR_FD);
posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSID);
char *argv[] = { MONITOR_ARG0, cmd, display, private_bus, NULL };
pid_t mon;
/* /proc/self/exe: this very build, even after an update replaced the file. */
int err = posix_spawn(&mon, "/proc/self/exe", &actions, &attr, argv, environ);
posix_spawn_file_actions_destroy(&actions);
posix_spawnattr_destroy(&attr);
close(rep[1]);
close(out[0]);
close(out[1]);
if (err != 0) {
close(rep[0]);
return -1;
}
set_nonblock_cloexec(rep[0]);
return rep[0];
}
+3 -1
View File
@@ -19,7 +19,9 @@ if [ -d "$PIXI/lib" ]; then
export C_INCLUDE_PATH="$C_INCLUDE_PATH:$PIXI/include"
export LIBRARY_PATH="$LIBRARY_PATH:$PIXI/lib"
fi
moon build --target native --release --warn-list -a wasmhost/bin
# unannotated_ffi fails the build: an unannotated pointer parameter is owned by the C function, and
# one that doesn't release it leaks it on every call.
moon build --target native --release --warn-list -a+unannotated_ffi --deny-warn wasmhost/bin
mkdir -p build
# Replace it by renaming, so a running session (`just install --link` links to it) keeps its copy.
cp _build/native/release/build/wasmhost/bin/bin.exe build/wasmhost.new
+5 -1
View File
@@ -99,7 +99,11 @@ fi
mkdir -p "$HOME/.local/state/chandra"
log="$HOME/.local/state/chandra/session.log"
[ -n "$CHANDRA_SESSION_LOG_STARTED" ] || : >"$log"
if [ -z "$CHANDRA_SESSION_LOG_STARTED" ]; then
# Keep the last session's log: after a freeze and a reboot it is the one that matters.
[ -s "$log" ] && mv -f "$log" "$log.1"
echo "chandra-session: started $(date '+%F %T')" >"$log"
fi
export CHANDRA_SESSION_LOG_STARTED=1
# The compositor reads wit/ and config/ relative to its working directory.
+48 -1
View File
@@ -722,7 +722,12 @@ static void pool_maps_gc(int64_t now) {
}
/* Drop pool mappings not used for a while (called with each submitted frame). */
void rs_maps_gc(void) { pool_maps_gc(mono_ms()); }
static void rs_mem_log(void);
void rs_maps_gc(void) {
pool_maps_gc(mono_ms());
rs_mem_log();
}
/* The whole file behind fd (st_size bytes) mapped read-only, from the cache when it is there. */
static const uint8_t *pool_map(int fd, const struct stat *st) {
@@ -854,6 +859,48 @@ int32_t rs_blit_surface(uint32_t id, int32_t dx, int32_t dy, int32_t dw, int32_t
return 1;
}
/* ------------------------------------------------------------------ memory log */
/* A line of what the host holds, in the session log: once a minute (CHANDRA_MEM_LOG_SECS), so a
* session that grows until the machine swaps leaves a record of what grew. */
static void rs_mem_log(void) {
static int64_t last;
static int every_s = -1;
if (every_s < 0) {
const char *e = getenv("CHANDRA_MEM_LOG_SECS");
every_s = e && atoi(e) > 0 ? atoi(e) : 60;
}
int64_t now = mono_ms();
if (last && now - last < (int64_t)every_s * 1000) return;
last = now;
long rss = 0, swap = 0;
FILE *f = fopen("/proc/self/status", "r");
if (f) {
char line[128];
while (fgets(line, sizeof line, f)) {
sscanf(line, "VmRSS: %ld", &rss);
sscanf(line, "VmSwap: %ld", &swap);
}
fclose(f);
}
int surf_n = 0, img_n = 0;
size_t surf_bytes = 0, img_bytes = 0;
for (int i = 0; i < SURF_BUCKETS; i++)
for (Surface *s = surfaces[i]; s; s = s->next) { surf_n++; surf_bytes += (size_t)s->w * s->h * 4; }
for (int i = 0; i < n_images; i++) {
if (!images[i].used) continue;
img_n++;
if (images[i].rgba) img_bytes += (size_t)images[i].w * images[i].h * 4;
for (Sized *s = images[i].sized; s; s = s->next) img_bytes += (size_t)s->w * s->h * 4;
}
time_t wall = time(NULL);
struct tm tm;
char when[32] = "";
if (localtime_r(&wall, &tm)) strftime(when, sizeof when, "%F %T", &tm);
fprintf(stderr, "%s chandra-host: memory %ld MB resident, %ld MB swapped; %d window buffers (%zu MB), %d images (%zu MB)\n",
when, rss / 1024, swap / 1024, surf_n, surf_bytes >> 20, img_n, img_bytes >> 20);
}
/* ------------------------------------------------------------------ backdrop and output */
static uint8_t *backdrop;
+9 -3
View File
@@ -4,7 +4,11 @@
/// 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_set_dispatch(f : FuncRef[(Int, Int) -> Bytes]) = "wt_set_dispatch"
///|
#borrow(out)
extern "C" fn c_take_args(out : Bytes) = "wt_take_args"
///|
extern "C" fn c_last_error() -> Bytes = "wt_last_error"
@@ -33,7 +37,9 @@ let handler : Ref[(Int, Array[Val]) -> Array[Val]] = Ref(fn(id, _) {
})
///|
fn dispatch(id : Int, args : Bytes) -> Bytes {
fn dispatch(id : Int, len : Int) -> Bytes {
let args = Bytes::make(len, 0)
c_take_args(args)
encode((handler.val)(id, decode(args)))
}
@@ -52,7 +58,7 @@ 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) })
c_set_dispatch(fn(id, len) { dispatch(id, len) })
if c_load(cstr(path)) != 0 {
return Err(last_error())
}
+29 -6
View File
@@ -27,7 +27,11 @@
#define KIND_BLOB 0x80
typedef moonbit_bytes_t (*wt_dispatch_t)(int32_t id, moonbit_bytes_t args);
/* The dispatcher takes only the arguments' length and fetches them with wt_take_args, so no heap
* object passes from C into MoonBit: whether a MoonBit function owns or borrows a parameter is
* the compiler's choice (it borrowed this one, and every call's arguments leaked). What it
* returns is ours to release. */
typedef moonbit_bytes_t (*wt_dispatch_t)(int32_t id, int32_t len);
static wasm_engine_t *engine;
static wasmtime_store_t *store;
@@ -37,6 +41,8 @@ static wasmtime_component_t *component;
static wasmtime_component_instance_t instance;
static int have_instance;
static wt_dispatch_t dispatch;
static const uint8_t *pending_args; /* of the host call being dispatched */
static size_t pending_len;
static char last_error[16384]; /* wasmtime backtraces are long; the cause comes last */
static void set_error(const char *what, wasmtime_error_t *e) {
@@ -139,10 +145,14 @@ static moonbit_bytes_t to_moonbit(const Buf *b) {
return out;
}
static void put_message(Buf *b, const wasmtime_component_val_t *vals, size_t n) {
put_u32(b, (uint32_t)n);
for (size_t i = 0; i < n; i++) enc(b, &vals[i]);
}
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]);
put_message(&b, vals, n);
moonbit_bytes_t out = to_moonbit(&b);
free(b.p);
return out;
@@ -300,10 +310,16 @@ static wasmtime_error_t *host_call(void *env, wasmtime_context_t *c, const wasmt
int32_t id = (int32_t)(intptr_t)env;
if (profiling < 0) { profiling = getenv("WASMHOST_PROFILE") != NULL; prof_last = now_ns(); }
uint64_t t0 = profiling ? now_ns() : 0;
moonbit_bytes_t in = enc_message(args, nargs);
uint64_t t1 = 0, inlen = profiling ? (uint64_t)Moonbit_array_length(in) : 0;
Buf in = {0};
put_message(&in, args, nargs);
uint64_t t1 = 0, inlen = in.len;
if (profiling) t1 = now_ns();
moonbit_bytes_t out = dispatch(id, in); /* takes `in` */
pending_args = in.p;
pending_len = in.len;
moonbit_bytes_t out = dispatch(id, (int32_t)in.len);
pending_args = NULL;
pending_len = 0;
free(in.p);
uint64_t t2 = profiling ? now_ns() : 0;
int bad = dec_message(out, results, nresults);
moonbit_decref(out);
@@ -323,6 +339,13 @@ static wasmtime_error_t *host_call(void *env, wasmtime_context_t *c, const wasmt
void wt_set_dispatch(wt_dispatch_t f) { dispatch = f; }
/* Copy the arguments of the call being dispatched into `out` (made by MoonBit, borrowed here). */
void wt_take_args(moonbit_bytes_t out) {
size_t n = (size_t)Moonbit_array_length(out);
if (n > pending_len) n = pending_len;
if (n) memcpy(out, pending_args, n);
}
moonbit_bytes_t wt_last_error(void) {
size_t n = strlen(last_error);
moonbit_bytes_t out = moonbit_make_bytes((int32_t)n, 0);