Launches that fail say why: command, exit status and what it printed
CI / test (push) Canceled after 17m11s

V: "kwi not starting from app menu or dock". Kwi is a Flatpak, and bwrap died
before it opened a window ("Can't find source path /run/user/1000/doc/by-app/
org.kde.kwi"); Chandra forked apps and forgot them, so the failure only reached
the session log and the click did nothing visible.

Every app the Applications menu, the dock, Super+1..9 and session restore start
now runs under a small monitor (sys spawn-watch, compositor/sys/sys_stub.c): it
copies the app's output to the session log as before, keeps its last 2 KiB,
and reports how sh -c CMD exited on a socket the main loop wakes on. The shell
(compositor/shell/launch.mbt) shows a red error notice for 15 s, and logs it,
when the app exits non-zero or by a signal within 30 s, or exits 0 without ever
opening a window here (after a 2 s grace for single-instance hand-offs): the
first line says what happened, then the command and the last lines it printed,
repeats folded ("(3 times)"). Status 127/126 say "command not found" / "not
executable". Launched apps no longer inherit the compositor's fds.

chandra-ctl launch ID starts a desktop app exactly as the dock does.

Tests: compositor/host/launch_test.mbt (bwrap-style failure incl. drawn notice,
127, SIGSEGV, exit 0 without a window, an app that keeps running), unit tests
in launch.mbt. Checked end to end with build/wasmhost + compositor.wasm
headless and a Flatpak-style kwi desktop file: chandra-ctl launch org.kde.kwi
shows the notice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiGJWeuHiTgtoyB4kb
This commit is contained in:
Claude committed 2026-11-26 05:48:39 +00:00
1 parent 77fcc4db1c
commit 50149e6b99
18 files changed
+686 -30

No files matched your search

+2
View File
@@ -358,6 +358,7 @@ pub fn run(args : Array[String]) -> Int {
fds.push(pfd)
}
fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
fds.append(comp.shell.launch_fds()) // launched apps' monitors reporting an exit
ignore(@sys.wait_readable(fds, comp.wake_timeout(idle.timeout())))
} else {
// Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work.
@@ -378,6 +379,7 @@ pub fn run(args : Array[String]) -> Int {
let wait_fds = comp.server.wait_fds()
wait_fds.append(comp.control_fds()) // chandra-ctl
wait_fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
wait_fds.append(comp.shell.launch_fds()) // launched apps' monitors reporting an exit
match nested {
Some(n) => {
if !n.poll() {
+3
View File
@@ -599,6 +599,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
self.auth_tick()
self.face_window_tick()
self.control_tick()
self.shell.launch_tick()
let events = self.server.poll_events()
for ev in events {
match ev {
@@ -910,6 +911,8 @@ pub fn ChandraCompositor::wake_timeout(self : ChandraCompositor, idle_ms : Int)
let d = self.shell.desktop_wake_ms(now)
let g = self.shell.gamelib_wake_ms(now)
let d = if g >= 0 && (d < 0 || g < d) { g } else { d }
let l = self.shell.launch_wake_ms(now)
let d = if l >= 0 && (d < 0 || l < d) { l } else { d }
if d >= 0 && d < idle_ms {
d
} else {
+15
View File
@@ -210,6 +210,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
"reload load every panel module again from disk", "reload NAME only the modules whose name, slot or path is NAME",
"shortcut ID do what shortcut ID does (launcher, overview, show-desktop, ...)",
"kiosk [lock|unlock|status] kiosk mode (--kiosk): lock it down or unlock it for admin work",
"launch ID start desktop app ID (e.g. org.kde.kwi) as the dock does; a failed start shows its notice",
"windows each window: frame, layout, box, shadow, size limits; and what is under the pointer",
"auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " +
@polkit.demo_modes.join(", "),
@@ -276,6 +277,20 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
}
(out, ok)
}
"launch" => {
if words.length() != 2 {
return (["error usage: launch DESKTOP-ID"], false)
}
match self.shell.command_for(words[1]) {
Some(cmd) =>
if self.shell.start_app(words[1], cmd) {
(["ok started: " + cmd + " (a failed start shows a notice and goes to the session log)"], true)
} else {
(["error could not create a process for: " + cmd], false)
}
None => (["error no installed .desktop file has the id " + words[1]], false)
}
}
"shortcut" => {
if words.length() != 2 {
return (["error usage: shortcut ID"], false)
+86
View File
@@ -0,0 +1,86 @@
///| Watched launches (compositor/shell/launch.mbt): an app that fails to start shows an error
/// notice with the command, its exit status and the last lines it printed.
///| Step `comp` until the shell shows an error notice or `ms` pass.
fn wait_notice(comp : @host.ChandraCompositor, ms : Int) -> Array[String] {
let t0 = @sys.monotonic_ms()
while (@sys.monotonic_ms() - t0).to_int() < ms {
comp.step()
if comp.shell.notice_frames > 0 && comp.shell.notice_lines.length() > 0 {
return comp.shell.notice_lines
}
@sys.sleep_ms(20)
}
[]
}
///|
test "a launch that fails shows the command, the exit status and what it printed" {
let comp = new_comp("launch-fail")
// What V's Flatpak kwi did: bwrap can't set up the sandbox, prints why and exits 1.
let cmd = "echo starting; for i in 1 2 3; do echo \"bwrap: Can't find source path /run/user/1000/doc/by-app/org.kde.kwi: No such file or directory\" >&2; done; exit 1"
assert_true(comp.shell.start_app("org.kde.kwi", cmd))
assert_eq(comp.shell.launch_fds().length(), 1)
let lines = wait_notice(comp, 5000)
assert_true(lines.length() >= 3)
assert_true(lines[0].has_prefix("Could not start org.kde.kwi: exited with status 1 after"))
assert_eq(lines[1], "Command: " + cmd)
assert_eq(lines[2], "starting")
assert_eq(
lines[3],
"bwrap: Can't find source path /run/user/1000/doc/by-app/org.kde.kwi: No such file or directory (3 times)",
)
// Drawn above the panel: a red edge at the notice's left side.
let f = comp.compose_frame()
let mut red = 0
for y = 0; y < 720; y = y + 1 {
for x = 0; x < 1280; x = x + 1 {
let i = (y * f.width + x) * 4
if f.data[i].to_int() > 200 && f.data[i + 1].to_int() < 100 && f.data[i + 2].to_int() < 100 {
red = red + 1
}
}
}
assert_true(red > 100)
ignore(@sys.write_file_bytes("/tmp/chandra-launch-notice.png", @renderer.encode_png(f)))
assert_eq(comp.shell.launch_fds().length(), 0)
}
///|
test "a command that isn't installed says so" {
let comp = new_comp("launch-127")
assert_true(comp.shell.start_app("nothere", "chandra-no-such-program-xyz --flag"))
let lines = wait_notice(comp, 5000)
assert_eq(lines[0], "Could not start nothere: failed: command not found (status 127)")
assert_true(lines[2].contains("chandra-no-such-program-xyz"))
}
///|
test "an app killed by a signal while starting says which" {
let comp = new_comp("launch-sig")
assert_true(comp.shell.start_app("crashy", "kill -SEGV $$"))
let lines = wait_notice(comp, 5000)
assert_true(lines[0].has_prefix("Could not start crashy: was killed by SIGSEGV after"))
assert_eq(lines[2], "It printed nothing. More in ~/.local/state/chandra/session.log")
}
///|
test "an app that exits 0 without ever opening a window is reported, after a grace period" {
let comp = new_comp("launch-nowin")
assert_true(comp.shell.start_app("handoff", "echo 'handed the launch to the running instance'"))
let t0 = @sys.monotonic_ms()
let lines = wait_notice(comp, 6000)
assert_true((@sys.monotonic_ms() - t0).to_int() >= 1900) // waited for a window first
assert_true(lines[0].has_prefix("Could not start handoff: exited (status 0) after"))
assert_true(lines[0].has_suffix("without opening a window"))
assert_eq(lines[2], "handed the launch to the running instance")
}
///|
test "an app that keeps running is not reported, and its output still reaches the log" {
let comp = new_comp("launch-ok")
assert_true(comp.shell.start_app("stays", "echo up; sleep 3"))
let lines = wait_notice(comp, 1500)
assert_eq(lines, [])
assert_eq(comp.shell.launch_fds().length(), 1)
}
+303
View File
@@ -0,0 +1,303 @@
///| Watched app launches. Every app the launcher, the dock, Super+1..9 or session restore starts
/// runs under a small monitor (`@sys.spawn_watch`) that reports how it exited. An app that fails
/// to start never fails quietly: when it exits with an error (or a signal) within
/// `launch_watch_ms`, or exits cleanly without ever showing a window, the shell shows a notice
/// with the command, the exit status and the last lines it printed, and logs the same.
///| How long after starting an app its exit counts as a failed launch (later exits are the user
/// quitting it, or a crash the session log keeps).
let launch_watch_ms : UInt64 = 30000UL
///| After an app exits 0 without a window, how long to wait for one (an app that hands the launch
/// to its running instance opens the window from there, a moment later).
let launch_grace_ms : UInt64 = 2000UL
///|
struct LaunchWatch {
/// Report socket from the monitor (-1 once closed).
mut fd : Int
id : String
name : String
command : String
started : UInt64
/// Whether the app already had a window here when it was started.
had_window : Bool
buf : Array[Byte]
/// Parsed report, once the pipe hit EOF.
mut report : LaunchReport?
/// When to check (exited 0 without a window yet) whether a window has appeared since.
mut check_at : UInt64
}
///| How a launched command ended, as the monitor reported it.
pub(all) struct LaunchReport {
/// "exit" or "signal" ("" when the report was unreadable).
how : String
/// Exit status or signal number.
code : Int
/// Milliseconds it ran.
ran_ms : Int
/// The end of what it printed (stdout and stderr).
output : String
} derive(Eq, Debug)
///| Parse the monitor's report: "exit CODE MS\n" or "signal NUM MS\n", then the output tail.
pub fn parse_launch_report(data : Bytes) -> LaunchReport {
let text = @utf8.decode_lossy(data)
let (head, rest) = match text.find("\n") {
Some(i) => (text[:i].to_string(), text[i + 1:].to_string())
None => (text, "")
}
let parts : Array[String] = head.split(" ").map(x => x.to_string()).collect()
if parts.length() != 3 || (parts[0] != "exit" && parts[0] != "signal") {
return { how: "", code: -1, ran_ms: 0, output: text }
}
let num = fn(s : String) {
let mut n = 0
for c in s {
if c < '0' || c > '9' {
return -1
}
n = n * 10 + (c.to_int() - '0'.to_int())
}
n
}
{ how: parts[0], code: num(parts[1]), ran_ms: num(parts[2]), output: rest }
}
///| The last `max` meaningful lines of `output`: blank lines dropped, a line repeated right after
/// itself shown once with "(N times)".
pub fn output_tail(output : String, max : Int) -> Array[String] {
let lines : Array[(String, Int)] = []
for raw in output.split("\n") {
let l = raw.trim(chars=" \t\r").to_string()
if l.length() == 0 {
continue
}
match lines.last() {
Some((prev, n)) if prev == l => lines[lines.length() - 1] = (prev, n + 1)
_ => lines.push((l, 1))
}
}
let start = if lines.length() > max { lines.length() - max } else { 0 }
let out : Array[String] = []
for i = start; i < lines.length(); i = i + 1 {
let (l, n) = lines[i]
out.push(if n > 1 { l + " (" + n.to_string() + " times)" } else { l })
}
out
}
///| Signal names for the ones apps die of.
fn signal_name(n : Int) -> String {
match n {
1 => "SIGHUP"
2 => "SIGINT"
4 => "SIGILL"
5 => "SIGTRAP"
6 => "SIGABRT"
7 => "SIGBUS"
8 => "SIGFPE"
9 => "SIGKILL"
11 => "SIGSEGV"
13 => "SIGPIPE"
15 => "SIGTERM"
_ => "signal " + n.to_string()
}
}
///| The notice for a failed launch of `name` (`command`), or None when `r` is not a failure.
/// `window` says whether the app has a window here now.
pub fn launch_failure(name : String, command : String, r : LaunchReport, window : Bool) -> Array[String]? {
let secs = fn(ms : Int) {
if ms < 1000 {
ms.to_string() + " ms"
} else {
(ms / 1000).to_string() + "." + (ms % 1000 / 100).to_string() + " s"
}
}
let what = match r.how {
"exit" if r.code == 0 =>
if window {
return None
} else {
"exited (status 0) after " + secs(r.ran_ms) + " without opening a window"
}
"exit" if r.code == 127 => "failed: command not found (status 127)"
"exit" if r.code == 126 => "failed: command not executable (status 126)"
"exit" => "exited with status " + r.code.to_string() + " after " + secs(r.ran_ms)
"signal" => "was killed by " + signal_name(r.code) + " after " + secs(r.ran_ms)
_ => "ended without a report from its monitor"
}
let lines = ["Could not start " + name + ": " + what, "Command: " + command]
let tail = output_tail(r.output, 4)
if tail.length() == 0 {
lines.push("It printed nothing. More in ~/.local/state/chandra/session.log")
} else {
lines.append(tail)
}
Some(lines)
}
///| Whether some window here belongs to desktop app `id`.
fn DesktopShell::has_window_for(self : DesktopShell, id : String) -> Bool {
self.win_list.iter().any(e => resolve_app_id(e.app_id, self.exec, self.wm_classes) == Some(id))
}
///| The catalog name of app `id` (its id when it has none).
fn DesktopShell::app_name(self : DesktopShell, id : String) -> String {
for a in self.apps {
if a.id == id {
return a.name
}
}
id
}
///| Start desktop app `id` with `command`, watched. False (with a notice) when nothing started.
pub fn DesktopShell::start_app(self : DesktopShell, id : String, command : String) -> Bool {
let name = self.app_name(id)
let fd = @sys.spawn_watch(command, self.display)
if fd < 0 {
self.say_error(["Could not start " + name + ": the process could not be created", "Command: " + command])
@sys.log("chandra: launch failed: " + name + " (" + id + "): could not create a process for `" + command + "`")
return false
}
@sys.log("chandra: launching " + name + " (" + id + "): " + command)
self.launches.push({
fd,
id,
name,
command,
started: @sys.monotonic_ms(),
had_window: self.has_window_for(id),
buf: [],
report: None,
check_at: 0UL,
})
true
}
///| Report sockets still open, for the main loop to wake on.
pub fn DesktopShell::launch_fds(self : DesktopShell) -> Array[Int] {
self.launches.filter(l => l.fd >= 0).map(l => l.fd)
}
///| Milliseconds until a launch needs looking at again (-1: nothing pending).
pub fn DesktopShell::launch_wake_ms(self : DesktopShell, now : UInt64) -> Int {
let mut best = -1
for l in self.launches {
let at = if l.check_at > 0UL { l.check_at } else if l.fd >= 0 { l.started + launch_watch_ms } else { now }
let d = if at <= now { 0 } else { (at - now).to_int() }
if best < 0 || d < best {
best = d
}
}
best
}
///| Read the monitors' reports and act on them: a notice for each failed launch.
pub fn DesktopShell::launch_tick(self : DesktopShell) -> Unit {
if self.launches.length() == 0 {
return
}
let now = @sys.monotonic_ms()
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
for l in self.launches {
if l.fd < 0 {
continue
}
let mut eof = false
while @sys.poll_read(l.fd, 0) > 0 {
let (n, extra) = @sys.recvmsg_fd(l.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
eof = true
break
}
for i = 0; i < n; i = i + 1 {
l.buf.push(buf[i])
}
}
if eof {
@sys.close_fd(l.fd)
l.fd = -1
let r = parse_launch_report(Bytes::from_array(l.buf))
l.report = Some(r)
let ran : UInt64 = if r.ran_ms > 0 { r.ran_ms.to_uint64() } else { 0UL }
if ran > launch_watch_ms {
// Ran a while: the user quit it, or it crashed; the monitor logged how.
l.check_at = 0UL
} else if r.how == "exit" && r.code == 0 && !l.had_window {
l.check_at = now + launch_grace_ms
} else {
l.check_at = now
}
} else if now - l.started > launch_watch_ms {
// Running past the watch window: it started. Stop listening (the monitor keeps logging).
@sys.close_fd(l.fd)
l.fd = -1
l.check_at = 0UL
}
}
let keep : Array[LaunchWatch] = []
for l in self.launches {
if l.fd >= 0 {
keep.push(l)
continue
}
match l.report {
Some(r) if l.check_at > 0UL =>
if l.check_at > now {
keep.push(l)
} else {
let window = l.had_window || self.has_window_for(l.id)
match launch_failure(l.name, l.command, r, window) {
Some(lines) => {
self.say_error(lines)
@sys.log("chandra: launch failed: " + l.id + ": " + lines.join("\n "))
}
None => ()
}
}
_ => ()
}
}
self.launches.clear()
self.launches.append(keep)
}
///|
test "parse_launch_report reads the monitor's report" {
let r = parse_launch_report(b"exit 1 230\nbwrap: no\n")
assert_eq(r, { how: "exit", code: 1, ran_ms: 230, output: "bwrap: no\n" })
let s = parse_launch_report(b"signal 11 5\n")
assert_eq(s.how, "signal")
assert_eq(s.code, 11)
assert_eq(parse_launch_report(b"").how, "")
}
///|
test "output_tail keeps the last lines and folds repeats" {
assert_eq(output_tail("a\n\nb\nb\nb\nc\n", 2), ["b (3 times)", "c"])
assert_eq(output_tail("", 4), [])
}
///|
test "launch_failure: a clean exit is fine once the app has a window" {
let r = { how: "exit", code: 0, ran_ms: 40, output: "" }
assert_eq(launch_failure("Kwi", "kwi", r, true), None)
match launch_failure("Kwi", "kwi", r, false) {
Some(l) => assert_eq(l[0], "Could not start Kwi: exited (status 0) after 40 ms without opening a window")
None => fail("expected a notice")
}
match launch_failure("Kwi", "kwi", { how: "exit", code: 2, ran_ms: 1500, output: "x" }, true) {
Some(l) => assert_eq(l, ["Could not start Kwi: exited with status 2 after 1.5 s", "Command: kwi", "x"])
None => fail("expected a notice")
}
}
+34 -2
View File
@@ -347,6 +347,11 @@ pub(all) struct DesktopShell {
mut notice : String
mut notice_frames : Int
mut notice_start : Int
/// A multi-line error notice (`say_error`): its lines, shown for `notice_secs`.
mut notice_lines : Array[String]
mut notice_secs : Int
/// Apps started and still watched for a failed launch (launch.mbt).
launches : Array[LaunchWatch]
/// Right-click menu.
mut menu_open : Bool
mut menu_rect : @scene.Rect
@@ -504,6 +509,9 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
notice: "",
notice_frames: 0,
notice_start: 0,
notice_lines: [],
notice_secs: 4,
launches: [],
menu_open: false,
menu_rect: zero,
menu_title: "",
@@ -1131,11 +1139,35 @@ pub fn DesktopShell::render(
self.menu_rect = { x: 0, y: 0, w: 0, h: 0 }
}
if self.notice_frames > 0 {
if (wall_secs() - self.notice_start + 86400) % 86400 >= 4 {
if (wall_secs() - self.notice_start + 86400) % 86400 >= self.notice_secs {
self.notice_frames = 0
}
}
if self.notice_frames > 0 {
if self.notice_frames > 0 && self.notice_lines.length() > 0 {
// An error: its lines in a box above the panel's right end, a red edge on the left.
let rows = notice_rows(self.notice_lines, 110)
let fs = tokens.font_size.reinterpret_as_int() - 3
let lh = fs + 6
let mut longest = 0
for r in rows {
longest = if r.length() > longest { r.length() } else { longest }
}
let nw = longest * 7 + 32
let nw = if nw > w - 24 { w - 24 } else { nw }
let nh = rows.length() * lh + 16
let red = @ui.color(229, 72, 77, 255)
let ops = [
@ui.fill_rect(@ui.rect(0, 0, nw, nh), tokens.palette.surface_popup, radius=tokens.radius.reinterpret_as_int()),
@ui.stroke_rect(@ui.rect(0, 0, nw, nh), red, radius=tokens.radius.reinterpret_as_int()),
@ui.fill_rect(@ui.rect(0, 0, 4, nh), red),
]
for i, r in rows {
ops.push(
@ui.text(16, 8 + i * lh + lh / 2, r, fs, if i == 0 { red } else { tokens.palette.foreground }),
)
}
translate(ops, w - nw - 12, self.panel_rect.y - nh - 12, panel_ops)
} else if self.notice_frames > 0 {
let nw = self.notice.length() * 7 + 24
translate(
[
+1 -1
View File
@@ -583,7 +583,7 @@ pub fn DesktopShell::launch_app_id(self : DesktopShell, app_id : String) -> Bool
match resolve_app_id(app_id, self.exec, self.wm_classes) {
Some(id) =>
match self.command_for(id) {
Some(cmd) => @sys.spawn(cmd, self.display)
Some(cmd) => self.start_app(id, cmd)
None => false
}
None => false
+40 -5
View File
@@ -215,10 +215,44 @@ fn DesktopShell::panel_fits(self : DesktopShell) -> Bool {
///| Show a short message above the panel for a few seconds.
pub fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit {
self.notice = msg
self.notice_lines = []
self.notice_secs = 4
self.notice_frames = 1
self.notice_start = wall_secs()
}
///| Show an error notice: the first line is what went wrong, the rest the details. It stays 15
/// seconds, and the same lines go to the session log.
pub fn DesktopShell::say_error(self : DesktopShell, lines : Array[String]) -> Unit {
self.notice = lines.get(0).unwrap_or("")
self.notice_lines = lines
self.notice_secs = 15
self.notice_frames = 1
self.notice_start = wall_secs()
}
///| The notice's lines as drawn: long ones wrapped at `max` characters, at most 10.
fn notice_rows(lines : Array[String], max : Int) -> Array[String] {
let out : Array[String] = []
for l in lines {
let chars = l.to_array()
let mut i = 0
while i < chars.length() || i == 0 {
let end = if i + max < chars.length() { i + max } else { chars.length() }
out.push(String::from_array(chars[i:end].to_array()))
i = end
if end == chars.length() {
break
}
}
}
if out.length() > 10 {
out[out.length() - 10:].to_array()
} else {
out
}
}
///| Seconds since local midnight (wall clock).
fn wall_secs() -> Int {
@sys.wall_time_field(3) * 3600 + @sys.wall_time_field(4) * 60 + @sys.wall_time_field(5)
@@ -829,14 +863,15 @@ pub fn DesktopShell::set_power_timeouts(self : DesktopShell, screen_off : Int, s
///| Start the catalog app `id` (a desktop file id) and remember it as the latest launch.
fn DesktopShell::launch_catalog_app(self : DesktopShell, id : String) -> Unit {
match self.command_for(id) {
Some(bin) =>
if @sys.spawn(bin, self.display) {
Some(cmd) =>
if self.start_app(id, cmd) {
self.note_recent(id)
self.apps_dirty = true
} else {
self.say("Could not start " + bin)
}
None => self.say("No executable for " + id)
None => {
self.say_error(["Could not start " + id + ": no installed .desktop file has that id"])
@sys.log("chandra: launch failed: no desktop file for " + id)
}
}
}
+11
View File
@@ -359,3 +359,14 @@ pub fn surface_thumbnail(_id : UInt, _w : Int, _h : Int, _reuse : UInt) -> UInt
pub fn frame_memfd() -> Int {
-1
}
///|
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
/// start) that reports, once `sh -c cmd` exits, "exit CODE MS\n" or "signal NUM MS\n" (MS = how
/// long it ran) followed by the last 2 KiB of its output, then closes. Its output still goes to
/// our stderr (the session log). See `@shell` launch.mbt.
pub fn spawn_watch(cmd : String, display : String) -> Int {
c_spawn_watch(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display))
}
+146 -16
View File
@@ -464,6 +464,27 @@ static void start_private_bus(void) {
}
}
/* The environment of a launched app (in the forked child): our Wayland socket, and the
* private bus when nested (see start_private_bus). */
static void app_env(const char *cmd, const char *display) {
/* SIG_IGN survives exec; apps (e.g. terminals that wait() on a helper) need the default. */
signal(SIGCHLD, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
/* Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak
* on the real session bus, so they keep it; the sandbox isolates their instances anyway. */
if (private_bus[0] && strstr(cmd, "flatpak run") == NULL) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1);
setenv("WAYLAND_DISPLAY", display, 1);
unsetenv("DISPLAY");
/* Make toolkits pick our Wayland socket, not X11 or the host session. */
setenv("XDG_SESSION_TYPE", "wayland", 1);
setenv("QT_QPA_PLATFORM", "wayland", 1);
setenv("GDK_BACKEND", "wayland", 1);
setenv("SDL_VIDEODRIVER", "wayland", 1);
setenv("MOZ_ENABLE_WAYLAND", "1", 1);
setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1);
setenv("CLUTTER_BACKEND", "wayland", 1);
}
/* Launch `cmd` detached, with WAYLAND_DISPLAY pointing at our socket. Returns 0 on fork success. */
MOONBIT_FFI_EXPORT
int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) {
@@ -477,28 +498,137 @@ int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) {
if (pid < 0) return -1;
if (pid == 0) {
setsid();
/* SIG_IGN survives exec; apps (e.g. terminals that wait() on a helper) need the default. */
signal(SIGCHLD, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
/* Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak
* on the real session bus, so they keep it; the sandbox isolates their instances anyway. */
if (private_bus[0] && strstr(cmd, "flatpak run") == NULL) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1);
setenv("WAYLAND_DISPLAY", display, 1);
unsetenv("DISPLAY");
/* Make toolkits pick our Wayland socket, not X11 or the host session. */
setenv("XDG_SESSION_TYPE", "wayland", 1);
setenv("QT_QPA_PLATFORM", "wayland", 1);
setenv("GDK_BACKEND", "wayland", 1);
setenv("SDL_VIDEODRIVER", "wayland", 1);
setenv("MOZ_ENABLE_WAYLAND", "1", 1);
setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1);
setenv("CLUTTER_BACKEND", "wayland", 1);
app_env(cmd, display);
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
_exit(127);
}
return 0;
}
static uint64_t mono_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void write_all(int fd, const char *p, size_t n) {
while (n > 0) {
ssize_t w = write(fd, p, n);
if (w < 0 && errno == EINTR) continue;
if (w <= 0) return;
p += w;
n -= (size_t)w;
}
}
/* Keep the last LAUNCH_TAIL bytes an app wrote. */
#define LAUNCH_TAIL 2048
struct tail { char buf[LAUNCH_TAIL]; size_t len; };
static void tail_add(struct tail *t, const char *p, size_t n) {
if (n >= LAUNCH_TAIL) { memcpy(t->buf, p + n - LAUNCH_TAIL, LAUNCH_TAIL); t->len = LAUNCH_TAIL; return; }
if (t->len + n > LAUNCH_TAIL) {
size_t drop = t->len + n - LAUNCH_TAIL;
memmove(t->buf, t->buf + drop, t->len - drop);
t->len -= drop;
}
memcpy(t->buf + t->len, p, n);
t->len += n;
}
/* Copy what is readable on `from` to our stderr (the session log) and into `t`. 0 at EOF. */
static int pump(int from, struct tail *t) {
char buf[4096];
for (;;) {
ssize_t n = read(from, buf, sizeof(buf));
if (n > 0) { write_all(2, buf, (size_t)n); tail_add(t, buf, (size_t)n); continue; }
if (n < 0 && errno == EINTR) continue;
if (n < 0 && errno == EAGAIN) return 1;
return 0;
}
}
/* 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();
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);
}
uint64_t t0 = mono_ms();
pid_t app = fork();
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);
_exit(1);
}
if (app == 0) {
/* The command's stdout and stderr go to the monitor; none of our other fds leak into it. */
dup2(out[1], 1);
dup2(out[1], 2);
for (int fd = 3; fd < 1024; fd++) close(fd);
app_env(cmd, display);
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
_exit(127);
}
close(out[1]);
fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL, 0) | O_NONBLOCK);
struct tail t = { .len = 0 };
int open_out = 1, reported = 0;
while (open_out || !reported) {
if (open_out) {
struct pollfd p = { .fd = out[0], .events = POLLIN };
poll(&p, 1, reported ? -1 : 100);
open_out = pump(out[0], &t);
}
if (!reported) {
int st = 0;
pid_t r = waitpid(app, &st, open_out ? WNOHANG : 0);
if (r == app) {
if (open_out) open_out = pump(out[0], &t); /* what it wrote just before exiting */
char head[64];
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);
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]);
reported = 1;
}
}
}
_exit(0);
}
close(rep[1]);
close(out[0]);
close(out[1]);
set_nonblock_cloexec(rep[0]);
return rep[0];
}
/* Names of "*.desktop" files in `dir`, newline-separated. */
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_list_desktop(moonbit_bytes_t dir_bytes) {
+5
View File
@@ -204,6 +204,11 @@ pub fn spawn(cmd : String, display : String) -> Bool {
@hostsys.spawn(cmd, display)
}
///| Launch `cmd` like `spawn`, watched: a socket that reports how it exited (see sys_native.mbt).
pub fn spawn_watch(cmd : String, display : String) -> Int {
@hostsys.spawn_watch(cmd, display)
}
///| True once after the host process got SIGUSR1 (reload the panel modules).
pub fn take_sigusr1() -> Bool {
@hostsys.take_sigusr1()