Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Add a platform module for child handles, file watching and own path

oxydizer5aba00eacae0
diff --git a/AGENTS.md b/AGENTS.md
index 9aa7b52..f9734e5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,7 +5,8 @@ Tests: `TESTING.md`. Where code lives: [source map](docs/agent-notes/map.md).
Area notes are in an `AGENTS.md` beside the code; read
the one for the directory you work in: `src/files`, `src/editor`,
`src/desktop`, `src/input`, `src/control_center`, `src/ui`, `src/session`,
-`src/dm`, `src/accounts_helper`, `src/printing`, `scripts`, `src/wlr`.
+`src/dm`, `src/accounts_helper`, `src/printing`, `scripts`, `src/wlr`,
+`src/platform`.
## Working rules
@@ -250,6 +251,8 @@ panel painting. The key rules:
compositor imports). Parsing/persistence is `config/`, applying and reloads
`config_runtime/`, shared raster code (`text`, `anim`, `sdf`, icons) `ui/`.
`memory` owns the process allocator; executables own its shutdown.
+* **OS calls go through `src/platform/`**: use it, not `pidfd_*`, `inotify_*`
+ or `/proc/self/exe` (C and C++: its `child.h`, `self_exe.h`).
* Zig 0.17 has no `@cImport`: the build translates header roots in `src/c/`
into modules (`support.cHeaders`): `c` (libc), `c_gfx` (libc, cairo,
freetype, harfbuzz, fontconfig, xkbcommon), `c_pulse`, `c_libinput`,
diff --git a/TESTING.md b/TESTING.md
index b858522..cdf4099 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -12,6 +12,10 @@ python3 tests/<name>.py
installed headers and tests embedded input-device lifecycles; it is included
in `zig build test`.
+`zig build test-platform` runs the OS-specific parts (`src/platform/`: child
+handles, file watching, own executable path) against real processes and
+temporary directories.
+
Run affected integration suites after building. Find suites and flags in
[tests/](tests/) and build targets in [build/tests.zig](build/tests.zig).
Compare failures with a clean HEAD worktree before calling them regressions.
diff --git a/build.zig b/build.zig
index 51c9b2e..b2c7313 100644
--- a/build.zig
+++ b/build.zig
@@ -63,6 +63,8 @@ pub fn build(b: *std.Build) void {
// Module roots enforce one-way dependencies: shared code cannot import Server.
const memory_mod = b.createModule(.{ .root_source_file = b.path("src/memory/allocator.zig"), .target = target, .optimize = optimize });
+ // The OS-specific parts (children, file watching, own path): std only.
+ const platform_mod = b.createModule(.{ .root_source_file = b.path("src/platform/mod.zig"), .target = target, .optimize = optimize });
const i18n_tool = b.addExecutable(.{ .name = "i18n-tool", .root_module = b.createModule(.{ .root_source_file = b.path("tools/i18n.zig"), .target = b.graph.host, .optimize = .safe }) });
const catalog_compile = b.addRunArtifact(i18n_tool);
catalog_compile.setCwd(b.path("."));
@@ -210,6 +212,7 @@ pub fn build(b: *std.Build) void {
.i18n_mod = i18n_mod,
.ui_mod = ui_mod,
.dbus_mod = dbus_mod,
+ .platform_mod = platform_mod,
.config_mod = config_mod,
.protocol_mod = protocol_mod,
.c = c_headers,
@@ -260,6 +263,7 @@ pub fn build(b: *std.Build) void {
module.addImport("i18n", i18n_mod);
module.addImport("config", config_mod);
module.addImport("memory", memory_mod);
+ module.addImport("platform", platform_mod);
module.addImport("c", c_headers.libc);
module.addImport("c_gfx", c_headers.gfx);
}
diff --git a/build/apps.zig b/build/apps.zig
index fab47f4..00ff115 100644
--- a/build/apps.zig
+++ b/build/apps.zig
@@ -56,6 +56,7 @@ pub fn add(ctx: Context) Apps {
}
inline for (.{ "helper.cpp", "helper_transfers.cpp", "helper_peers.cpp", "helper_tray.cpp" }) |part| torrents.addFileArg(b.path("src/files/torrent/" ++ part));
torrents.addFileInput(b.path("src/files/torrent/helper.hpp"));
+ torrents.addFileInput(b.path("src/platform/self_exe.h"));
torrents.addArg("-o");
const torrent_binary = torrents.addOutputFileArg("rediwm-transfers");
const install_torrents = b.addInstallFileWithDir(torrent_binary, .bin, "rediwm-transfers");
diff --git a/build/context.zig b/build/context.zig
index 6643b0d..83c7ab5 100644
--- a/build/context.zig
+++ b/build/context.zig
@@ -19,6 +19,7 @@ pub const Context = struct {
i18n_mod: *std.Build.Module,
ui_mod: *std.Build.Module,
dbus_mod: *std.Build.Module,
+ platform_mod: *std.Build.Module,
config_mod: *std.Build.Module,
protocol_mod: *std.Build.Module,
c: CHeaders,
diff --git a/build/session.zig b/build/session.zig
index 0a8b314..090a7da 100644
--- a/build/session.zig
+++ b/build/session.zig
@@ -5,7 +5,6 @@ const Context = @import("context.zig").Context;
pub const Session = struct {
session_supervisor: *std.Build.Step.Compile,
- child_set_mod: *std.Build.Module,
dm_ipc_mod: *std.Build.Module,
ws_mod: *std.Build.Module,
};
@@ -48,7 +47,6 @@ pub fn add(ctx: Context) Session {
restart.root_module.addImport("install_paths", ctx.layout.options);
b.installArtifact(restart);
- const child_set_mod = b.createModule(.{ .root_source_file = b.path("src/child_set.zig"), .target = target, .optimize = optimize });
const dm_ipc_mod = b.createModule(.{
.root_source_file = b.path("src/session/dm_ipc.zig"),
.target = target,
@@ -77,7 +75,7 @@ pub fn add(ctx: Context) Session {
});
dm.root_module.addImport("install_paths", ctx.layout.options);
dm.root_module.addImport("c", ctx.c.libc);
- dm.root_module.addImport("child_set", child_set_mod);
+ dm.root_module.addImport("platform", ctx.platform_mod);
dm.root_module.addImport("dm_ipc", dm_ipc_mod);
dm.root_module.addImport("wayland_sessions", ws_mod);
dm.root_module.linkSystemLibrary("pam", .{});
@@ -112,5 +110,5 @@ pub fn add(ctx: Context) Session {
accounts_helper.root_module.addImport("dm_config", dm_config);
b.installArtifact(accounts_helper);
b.step("accounts-helper", "Build the privileged account-management helper").dependOn(&accounts_helper.step);
- return .{ .session_supervisor = session_supervisor, .child_set_mod = child_set_mod, .dm_ipc_mod = dm_ipc_mod, .ws_mod = ws_mod };
+ return .{ .session_supervisor = session_supervisor, .dm_ipc_mod = dm_ipc_mod, .ws_mod = ws_mod };
}
diff --git a/build/tests.zig b/build/tests.zig
index 6d63f93..b197baa 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -43,7 +43,6 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
const config_mod = ctx.config_mod;
const protocol_mod = ctx.protocol_mod;
const session_supervisor = session.session_supervisor;
- const child_set_mod = session.child_set_mod;
const dm_ipc_mod = session.dm_ipc_mod;
const ws_mod = session.ws_mod;
// The UI layout engine (src/ui/) isn't wired into the compositor's
@@ -105,6 +104,9 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
const i18n_tests = b.addTest(.{ .root_module = i18n_mod });
const run_i18n_tests = b.addRunArtifact(i18n_tests);
test_step.dependOn(&run_i18n_tests.step);
+ const run_platform_tests = b.addRunArtifact(b.addTest(.{ .root_module = ctx.platform_mod }));
+ test_step.dependOn(&run_platform_tests.step);
+ b.step("test-platform", "Test child handles, file watching and the program's own path").dependOn(&run_platform_tests.step);
const i18n_tool_tests = b.addTest(.{ .root_module = i18n_tool.root_module });
test_step.dependOn(&b.addRunArtifact(i18n_tool_tests).step);
b.step("test-i18n", "Test locale resolution, catalogs and formatting").dependOn(&run_i18n_tests.step);
@@ -115,6 +117,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
.link_libc = true,
}) });
monitor_tests.root_module.addImport("c", ctx.c.libc);
+ monitor_tests.root_module.addImport("platform", ctx.platform_mod);
const run_monitor_tests = b.addRunArtifact(monitor_tests);
const monitor_test_step = b.step("test-monitor", "Test System Monitor collection, process identity and model");
monitor_test_step.dependOn(&run_monitor_tests.step);
@@ -128,6 +131,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
printing_tests.root_module.addImport("c", ctx.c.libc);
printing_tests.root_module.addImport("dbus", dbus_mod);
printing_tests.root_module.addImport("i18n", i18n_mod);
+ printing_tests.root_module.addImport("platform", ctx.platform_mod);
printing_tests.root_module.addImport("wayland", wayland);
printing_tests.root_module.linkSystemLibrary("wayland-server", .{});
printing_tests.root_module.linkSystemLibrary("cups", .{});
@@ -252,7 +256,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
}) });
dm_tests.root_module.addImport("install_paths", ctx.layout.options);
dm_tests.root_module.addImport("c", ctx.c.libc);
- dm_tests.root_module.addImport("child_set", child_set_mod);
+ dm_tests.root_module.addImport("platform", ctx.platform_mod);
dm_tests.root_module.addImport("dm_ipc", dm_ipc_mod);
dm_tests.root_module.addImport("wayland_sessions", ws_mod);
dm_tests.root_module.linkSystemLibrary("pam", .{});
diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.md
index b9d2d0c..4f5b358 100644
--- a/docs/agent-notes/map.md
+++ b/docs/agent-notes/map.md
@@ -42,7 +42,9 @@ or a lowercase directory named after a TitleCase host (`Dock.zig` → `dock/`).
No compositor imports (`build.zig` enforces the direction): `ui` (`src/ui/`:
widgets, layout, text, theme, animation), `config` (`src/config/`: parsing and
saving `config.toml`), `dbus`, `i18n`, `memory` and `protocol`
-(`src/ipc/protocol.zig`, the IPC wire format shared with `rediwm-msg`).
+(`src/ipc/protocol.zig`, the IPC wire format shared with `rediwm-msg`). Also
+`platform` (`src/platform/`, std only): child-process handles, directory
+watching and the program's own path, the seam for other operating systems.
## Compositor
diff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.md
index 764a7b0..96806a9 100644
--- a/docs/plans/freebsd.md
+++ b/docs/plans/freebsd.md
@@ -1,6 +1,7 @@
# FreeBSD support plan
-Status: draft, 2026-10-30. Nothing implemented. Decisions D1–D6 are open.
+Status: draft, 2026-10-30. Preparation steps P.1–P.3 are done (Linux only,
+`src/platform/`); nothing else is implemented. Decisions D1–D6 are open.
Run RediWM on FreeBSD: first the compositor in a seatd session on DRM, then
the shell features and apps, and last `rediwm-dm` and packaging. Linux stays
@@ -21,22 +22,22 @@ Our own code is the problem: it has no OS abstraction at all (no
### 1. Compile barrier
-`src/c/libc.h` includes `linux/netlink.h`, `sys/inotify.h`, `sys/prctl.h` and
-`sys/eventfd.h`, so the `c` module, and with it every artifact, fails to
+`src/c/libc.h` includes `linux/netlink.h`, `sys/prctl.h` and `sys/eventfd.h`
+(`sys/inotify.h` left with P.2), so the `c` module, and with it every artifact, fails to
translate. About 47 Zig files call `std.os.linux.*` directly.
| Linux interface | Users | FreeBSD |
| --- | --- | --- |
| `eventfd` | ~38 files | Native (13+). Swap `linux.EFD` for `c.EFD_*`. |
| `memfd_create`, `timerfd` | few | Native on current releases (confirm in phase 0). |
-| `pidfd_open`, `pidfd_send_signal`, `waitid(P_PIDFD)` | `session/child.zig`, `child_set.zig` and ~8 ad hoc sites (supervisor, dm worker, terminal engine, IPC, `Toplevel`, folder picker, file chooser, system monitor) | No equivalent for an existing pid. kqueue `EVFILT_PROC`/`NOTE_EXIT`; the kqueue fd joins the wl event loop like a pidfd. Signals by pid, guarded by the still-unreaped zombie. |
-| `signalfd`, `epoll` | supervisor, dm daemon/worker, `child_set.zig` | kqueue `EVFILT_SIGNAL`, kqueue. |
-| `inotify` | 7 separate watchers (config, desktop, Files worker ×2, printing, start menu, system monitor settings) | Native in 15.0 (confirm); otherwise kqueue `EVFILT_VNODE`. |
+| `pidfd_open`, `pidfd_send_signal`, `waitid(P_PIDFD)` | `platform/child.zig` (`Handle`, `Set`) and `platform/child.h`, used by `session/child.zig`, the supervisor, dm worker and daemon, IPC, `Toplevel`, the pickers, System Monitor and the terminal engine | No equivalent for an existing pid. kqueue `EVFILT_PROC`/`NOTE_EXIT`; the kqueue fd joins the wl event loop like a pidfd. Signals by pid, guarded by the still-unreaped zombie. `Handle.pid()` has no counterpart: System Monitor needs another identity check. |
+| `signalfd`, `epoll` | supervisor, dm daemon/worker, `platform.child.Set` | kqueue `EVFILT_SIGNAL`, kqueue. |
+| `inotify` | `platform/watch.zig` (`Watcher`); all 7 users (config, desktop, Files worker ×2, printing, start menu, system monitor settings) call it | Native in 15.0 (confirm); otherwise kqueue `EVFILT_VNODE`, which has no names: diff the directory to synthesize them. |
| `prctl` | dm worker, lock, PAM worker, PDF print/sandbox, theme helper | `procctl(PROC_PDEATHSIG_CTL / PROC_NO_NEW_PRIVS_CTL / PROC_TRACE_CTL)`, `pthread_set_name_np`. |
| `statx`, `getdents64` | Files dirsize/properties, supervisor, session restart, IPC | `fstatat`, `getdirentries` or `std.Io.Dir`. |
| raw `linux.fork/execve/wait4/exit_group/close/read` | many | libc. Note the `-errno` vs `errno` convention change. |
| `SO_PEERCRED` | IPC peer checks (4 files) | `getpeereid` / `LOCAL_PEERCRED`. Security-relevant: sandbox allowances need the peer pid; confirm `cr_pid`. |
-| `/proc/self/exe` | 11 sites (Zig, `bass.c`, torrent helper; dm re-execs through it) | `sysctl KERN_PROC_PATHNAME` / `std.process.executablePath`; `fexecve` for the re-exec. |
+| `/proc/self/exe` | `platform/exe.zig` and `platform/self_exe.h` (Zig sites, `bass.c`, torrent helper; dm re-execs through `exe.execSelf`) | `sysctl KERN_PROC_PATHNAME` / `std.process.executablePath`; `fexecve` on a descriptor opened at startup for the re-exec. |
| `/proc/self/fd`, `fdinfo` | spawn paths | `closefrom`/`close_range`. |
| `/proc/<pid>/stat`, `/proc/stat`, `/proc/meminfo`, task children | system monitor, `ipc/processes.zig` | libprocstat / `kern.proc` sysctls behind a collector backend. |
| `pty.h` | terminal engine | `libutil.h` (`openpty`/`forkpty`), link `util`. |
@@ -106,12 +107,15 @@ Refactors that are worth doing for Linux alone and shrink the port. Each
lands separately, keeps behaviour, and is checked with the usual Debug,
ReleaseSafe, `zig build test` and affected integration suites.
-1. **Child watching:** move the ~8 ad hoc pidfd sites onto `session/child.zig`
- / `child_set.zig` (or one successor API). The port then reimplements one
- module instead of ten call sites.
-2. **File watching:** one watcher API for the 7 inotify users (directory,
- file, debounce, close). Removes duplicated event parsing.
-3. **Own executable:** one helper for the 11 `/proc/self/exe` readers.
+1. **Child watching** (done): the ad hoc pidfd sites and `child_set.zig` are
+ now `platform.child` (`Handle`, `Set`, `reap`) with `session/child.zig` as
+ the Wayland-loop adapter and `platform/child.h` for the terminal engine.
+ The port reimplements that module, not ten call sites. Left for P.4: plain
+ `kill`/`wait4`, the supervisor's `signalfd`/`epoll`, and the `/proc` walks.
+2. **File watching** (done): `platform.watch.Watcher` for the 7 inotify users,
+ with event parsing in one place and `sys/inotify.h` out of `libc.h`.
+3. **Own executable** (done): `platform.exe` and `self_exe.h` for the 11
+ `/proc/self/exe` readers.
4. **Raw syscalls to libc** where libc has the call (fork, execve, wait4,
close, read, getuid, …), keeping `std.os.linux` for what has no libc form.
5. **One sandbox interface:** move the PDF sandbox from libseccomp to the raw
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index bbfcf14..908b773 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -20,6 +20,7 @@ const gpa = @import("main.zig").gpa;
const window_rules = @import("config").window_rules;
const anim = @import("ui").anim;
const toplevel_create = @import("toplevel/create.zig");
+const Child = @import("session/child.zig");
const toplevel_info = @import("toplevel/info.zig");
const toplevel_focus_close = @import("toplevel/focus_close.zig");
const toplevel_configure = @import("toplevel/configure.zig");
@@ -54,23 +55,16 @@ pub const Placeholder = struct {
delay_timer: ?*wl.EventSource = null,
timeout_timer: ?*wl.EventSource = null,
- child_source: ?*wl.EventSource = null,
- child_pidfd: i32 = -1,
+ /// Watches the launched process; the services manager owns its status.
+ child: ?*Child = null,
launch_time_ms: i64,
matched: bool = false,
cancelled: bool = false,
pub fn setPid(self: *Placeholder, toplevel: *Toplevel, pid: i32) void {
self.pid = pid;
- if (pid <= 0 or self.child_source != null) return;
- const rc = std.os.linux.pidfd_open(pid, 0);
- if (std.os.linux.errno(rc) != .SUCCESS) return;
- self.child_pidfd = @intCast(rc);
- self.child_source = toplevel.server.wl_server.getEventLoop().addFd(*Toplevel, self.child_pidfd, .{ .readable = true }, handleChildExit, toplevel) catch {
- _ = std.os.linux.close(self.child_pidfd);
- self.child_pidfd = -1;
- return;
- };
+ if (pid <= 0 or self.child != null) return;
+ self.child = Child.observe(gpa, toplevel.server.wl_server.getEventLoop(), pid, toplevel, handleChildExit) catch null;
}
pub fn deinit(self: *Placeholder) void {
@@ -82,8 +76,7 @@ pub const Placeholder = struct {
t.remove();
self.timeout_timer = null;
}
- if (self.child_source) |source| source.remove();
- if (self.child_pidfd >= 0) _ = std.os.linux.close(self.child_pidfd);
+ if (self.child) |child| child.cancel();
gpa.free(self.desktop_id);
gpa.free(self.name);
gpa.free(self.app_id);
diff --git a/src/audio/bass.c b/src/audio/bass.c
index 011f2b9..4dc359f 100644
--- a/src/audio/bass.c
+++ b/src/audio/bass.c
@@ -5,6 +5,7 @@
* the binaries. */
#define _POSIX_C_SOURCE 200809L
#include "bass.h"
+#include "../platform/self_exe.h"
#include <pipewire/pipewire.h>
#include <pipewire/impl-module.h>
#include <pipewire/extensions/metadata.h>
@@ -210,12 +211,7 @@ static const struct pw_core_events core_events = { PW_VERSION_CORE_EVENTS, .erro
/* The DSP plugin is installed in lib/rediwm/ladspa beside bin/. */
static void find_plugin(struct rediwm_bass *b) {
char exe[sizeof(b->plugin)];
- ssize_t len = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
- char *slash = NULL;
- if (len > 0) {
- exe[len] = '\0';
- slash = strrchr(exe, '/');
- }
+ char *slash = rediwm_self_exe(exe, sizeof(exe)) > 0 ? strrchr(exe, '/') : NULL;
int n = slash ? snprintf(b->plugin, sizeof(b->plugin), "%.*s/../lib/rediwm/ladspa/rediwm-bass.so",
(int)(slash - exe), exe) : -1;
/* A quote or backslash would need escaping in the filter-chain arguments. */
diff --git a/src/c/libc.h b/src/c/libc.h
index 1bf6b97..cc3bdcf 100644
--- a/src/c/libc.h
+++ b/src/c/libc.h
@@ -25,7 +25,6 @@
#include <string.h>
#include <sys/eventfd.h>
#include <sys/file.h>
-#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
diff --git a/src/calculator/client.zig b/src/calculator/client.zig
index f6a6a78..89eab99 100644
--- a/src/calculator/client.zig
+++ b/src/calculator/client.zig
@@ -870,7 +870,7 @@ pub fn run(init: std.process.Init) !void {
var fds = [_]c.struct_pollfd{
.{ .fd = display.getFd(), .events = @intCast(c.POLLIN | @as(c_int, if (flushed == .AGAIN) c.POLLOUT else 0)), .revents = 0 },
- .{ .fd = watch.fd, .events = c.POLLIN, .revents = 0 },
+ .{ .fd = watch.fd(), .events = c.POLLIN, .revents = 0 },
};
const now = key_repeat.nowMs();
var timeout: c_int = if (self.key_repeat.timeoutMs(now)) |wait| @intCast(@min(wait, 60_000)) else -1;
diff --git a/src/child_set.zig b/src/child_set.zig
deleted file mode 100644
index b43a390..0000000
--- a/src/child_set.zig
+++ /dev/null
@@ -1,60 +0,0 @@
-//! Pidfds for poll-based clients. The epoll fd joins the application's normal
-//! event loop; a long-lived child requires no thread and causes no wakeups.
-const std = @import("std");
-const linux = std.os.linux;
-const Set = @This();
-const Entry = struct { pid: linux.pid_t, fd: i32 };
-pub const Exit = struct { pid: linux.pid_t, status: ?u32 };
-fd: i32 = -1,
-entries: std.ArrayList(Entry) = .empty,
-
-pub fn add(self: *Set, allocator: std.mem.Allocator, pid: linux.pid_t) !void {
- try self.entries.ensureUnusedCapacity(allocator, 1);
- if (self.fd < 0) {
- const rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
- if (linux.errno(rc) != .SUCCESS) return error.EpollFailed;
- self.fd = @intCast(rc);
- }
- const rc = linux.pidfd_open(pid, 0);
- if (linux.errno(rc) != .SUCCESS) return error.PidfdFailed;
- const fd: i32 = @intCast(rc);
- errdefer _ = linux.close(fd);
- var event: linux.epoll_event = .{ .events = linux.EPOLL.IN, .data = .{ .fd = fd } };
- if (linux.errno(linux.epoll_ctl(self.fd, linux.EPOLL.CTL_ADD, fd, &event)) != .SUCCESS) return error.EpollFailed;
- self.entries.appendAssumeCapacity(.{ .pid = pid, .fd = fd });
-}
-
-pub fn next(self: *Set) ?Exit {
- if (self.fd < 0) return null;
- var events: [1]linux.epoll_event = undefined;
- const rc = linux.epoll_wait(self.fd, &events, 1, 0);
- if (linux.errno(rc) != .SUCCESS or rc == 0) return null;
- for (self.entries.items, 0..) |entry, i| {
- if (entry.fd != events[0].data.fd) continue;
- _ = linux.epoll_ctl(self.fd, linux.EPOLL.CTL_DEL, entry.fd, null);
- _ = linux.close(entry.fd);
- _ = self.entries.swapRemove(i);
- var status: u32 = 0;
- while (true) {
- const result = linux.wait4(entry.pid, @ptrCast(&status), linux.W.NOHANG, null);
- switch (linux.errno(result)) {
- .INTR => continue,
- .SUCCESS => return .{ .pid = entry.pid, .status = if (result == entry.pid) status else null },
- else => return .{ .pid = entry.pid, .status = null },
- }
- }
- }
- unreachable;
-}
-
-pub fn signalAll(self: *Set, sig: linux.SIG) void {
- for (self.entries.items) |entry| _ = linux.pidfd_send_signal(entry.fd, sig, null, 0);
-}
-
-pub fn deinit(self: *Set, allocator: std.mem.Allocator) void {
- while (self.next() != null) {}
- for (self.entries.items) |entry| _ = linux.close(entry.fd);
- self.entries.deinit(allocator);
- if (self.fd >= 0) _ = linux.close(self.fd);
- self.* = .{};
-}
diff --git a/src/config_runtime/watcher.zig b/src/config_runtime/watcher.zig
index e5b0119..5d6fe0b 100644
--- a/src/config_runtime/watcher.zig
+++ b/src/config_runtime/watcher.zig
@@ -1,8 +1,7 @@
-// inotify watch on the compositor config file, wired into the Wayland event loop.
+// Watches the compositor config file's directory, wired into the Wayland event loop.
const std = @import("std");
-const posix = std.posix;
-const linux = std.os.linux;
const wl = @import("wayland").server.wl;
+const platform = @import("platform");
const Server = @import("../Server.zig");
const loader = @import("config").loader;
@@ -10,11 +9,9 @@ const loader = @import("config").loader;
const log = std.log.scoped(.config);
pub const ConfigWatcher = struct {
- fd: i32 = -1,
- wd: i32 = -1,
+ watcher: platform.watch.Watcher,
path: []const u8,
basename: []const u8,
- dir_z: [:0]const u8,
source: ?*wl.EventSource = null,
pub fn deinit(self: *ConfigWatcher, allocator: std.mem.Allocator) void {
@@ -22,12 +19,8 @@ pub const ConfigWatcher = struct {
src.remove();
self.source = null;
}
- if (self.fd >= 0) {
- _ = std.c.close(self.fd);
- self.fd = -1;
- }
+ self.watcher.deinit();
allocator.free(self.path);
- allocator.free(self.dir_z);
}
};
@@ -36,64 +29,46 @@ pub fn init(path: []const u8, server: *Server) !ConfigWatcher {
const owned_path = try allocator.dupe(u8, path);
errdefer allocator.free(owned_path);
- const dir = std.fs.path.dirname(path) orelse ".";
- const dir_z = try allocator.dupeSentinel(u8, dir, 0);
- errdefer allocator.free(dir_z);
-
- const fd = std.c.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC);
- if (fd < 0) return error.InotifyInitFailed;
- errdefer _ = std.c.close(fd);
+ var watcher = platform.watch.Watcher.init() catch return error.WatchFailed;
+ errdefer watcher.deinit();
- // MODIFY/CREATE can observe an editor's empty or half-written file. Only
- // reload completed writes and atomic replacements, especially now that a
- // transient empty config would reset live display scales and placement.
- const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.MOVED_TO;
- const wd = std.c.inotify_add_watch(fd, dir_z.ptr, mask);
- if (wd < 0) return error.InotifyWatchFailed;
+ // Completed writes and atomic replacements only: a modification can
+ // observe an editor's empty or half-written file, and a transient empty
+ // config would reset live display scales and placement.
+ _ = watcher.add(std.fs.path.dirname(path) orelse ".", .{ .written = true, .moved_to = true }) orelse return error.WatchFailed;
const event_loop = server.wl_server.getEventLoop();
const source = event_loop.addFd(
*Server,
- fd,
+ watcher.fd,
.{ .readable = true },
handleFd,
server,
) catch return error.EventLoopFailed;
return .{
- .fd = fd,
- .wd = wd,
+ .watcher = watcher,
.path = owned_path,
.basename = std.fs.path.basename(owned_path),
- .dir_z = dir_z,
.source = source,
};
}
-fn handleFd(fd: c_int, mask: wl.EventMask, server: *Server) c_int {
- _ = mask;
- const watcher = &(server.config_watcher orelse return 0);
- var buf: [4096]u8 align(@alignOf(linux.inotify_event)) = undefined;
- while (true) {
- const n = posix.read(fd, &buf) catch |err| switch (err) {
- error.WouldBlock => break,
- else => break,
- };
- if (n == 0) break;
- var off: usize = 0;
- var reload = false;
- while (off + @sizeOf(linux.inotify_event) <= n) {
- const ev: *const linux.inotify_event = @ptrCast(@alignCast(&buf[off]));
- const name = ev.getName();
- if (name == null or std.mem.eql(u8, name.?, watcher.basename)) {
- if (ev.mask & (linux.IN.CLOSE_WRITE | linux.IN.MOVED_TO) != 0) {
- reload = true;
- }
- }
- off += @sizeOf(linux.inotify_event) + ev.len;
- }
- if (reload) reloadConfig(server);
+const Pending = struct {
+ basename: []const u8,
+ reload: bool = false,
+
+ fn event(self: *Pending, ev: platform.watch.Event) void {
+ if (ev.name.len != 0 and !std.mem.eql(u8, ev.name, self.basename)) return;
+ if (ev.flags.matches(.{ .written = true, .moved_to = true })) self.reload = true;
}
+};
+
+fn handleFd(_: c_int, _: wl.EventMask, server: *Server) c_int {
+ const watcher = &(server.config_watcher orelse return 0);
+ var pending: Pending = .{ .basename = watcher.basename };
+ watcher.watcher.drain(&pending, Pending.event) catch {};
+ if (pending.reload) reloadConfig(server);
return 0;
}
diff --git a/src/control_center/folder_picker.zig b/src/control_center/folder_picker.zig
index 358aa3b..d83da8b 100644
--- a/src/control_center/folder_picker.zig
+++ b/src/control_center/folder_picker.zig
@@ -7,6 +7,7 @@ const wl = @import("wayland").server.wl;
const Server = @import("../Server.zig");
const chooser = @import("../files/chooser.zig");
const c = @import("c");
+const platform = @import("platform");
const a = std.heap.c_allocator;
/// A path in JSON; anything larger is not a result.
@@ -15,7 +16,7 @@ const max_output = 64 * 1024;
const Picker = struct {
server: *Server,
fd: c_int,
- pidfd: c_int,
+ process: platform.child.Handle,
source: ?*wl.EventSource = null,
output: std.ArrayList(u8) = .empty,
owner: ?*anyopaque,
@@ -24,8 +25,8 @@ const Picker = struct {
fn destroy(self: *Picker) void {
if (active == self) active = null;
if (self.source) |s| s.remove();
- _ = std.os.linux.pidfd_send_signal(self.pidfd, .TERM, null, 0);
- _ = c.close(self.pidfd);
+ self.process.signal(.TERM) catch {};
+ self.process.close();
_ = c.close(self.fd);
self.output.deinit(a);
a.destroy(self);
@@ -106,21 +107,18 @@ pub fn startWithOptions(server: *Server, opts: chooser.Options, owner: ?*anyopaq
var env = try server.environ.createMap(a);
defer env.deinit();
try server.applyChildEnv(&env);
- var pathbuf: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &pathbuf, pathbuf.len);
- const executable = if (n > 0 and n < pathbuf.len) try std.fmt.allocPrint(alloc, "{s}/rediwm-files", .{std.fs.path.dirname(pathbuf[0..@intCast(n)]).?}) else "rediwm-files";
+ var pathbuf: [platform.exe.max_path]u8 = undefined;
+ const executable: []const u8 = platform.exe.sibling(&pathbuf, "rediwm-files") orelse "rediwm-files";
var child = try std.process.spawn(server.io, .{ .argv = &.{ executable, "--chooser-stdin" }, .environ_map = &env, .stdin = .{ .file = .{ .handle = input, .flags = .{ .nonblocking = false } } }, .stdout = .pipe });
errdefer child.kill(server.io);
@import("../session/app_scope.zig").place(server, child.id.?, "file-chooser");
- const pidfd_result = std.os.linux.pidfd_open(child.id.?, 0);
- if (std.os.linux.errno(pidfd_result) != .SUCCESS) return error.PidfdFailed;
- const pidfd: c_int = @intCast(pidfd_result);
- errdefer _ = c.close(pidfd);
+ const process = try platform.child.Handle.open(child.id.?);
+ errdefer process.close();
const fd = child.stdout.?.handle;
if (c.fcntl(fd, c.F_SETFL, @as(c_int, c.O_NONBLOCK)) < 0) return error.NonblockingFailed;
const picker = try a.create(Picker);
errdefer a.destroy(picker);
- picker.* = .{ .server = server, .fd = fd, .pidfd = pidfd, .owner = owner, .on_done = on_done };
+ picker.* = .{ .server = server, .fd = fd, .process = process, .owner = owner, .on_done = on_done };
picker.source = try server.wl_server.getEventLoop().addFd(*Picker, fd, .{ .readable = true }, Picker.readable, picker);
errdefer picker.source.?.remove();
_ = try @import("../session/child.zig").watch(a, server.wl_server.getEventLoop(), child.id.?, null, null);
diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zig
index 91e1f0b..e122cfe 100644
--- a/src/desktop/watcher.zig
+++ b/src/desktop/watcher.zig
@@ -2,6 +2,7 @@
const i18n = @import("i18n");
const std = @import("std");
const c = @import("c.zig").api;
+const platform = @import("platform");
const icons = @import("../icon_cache.zig");
const theme = @import("../icon_theme.zig");
const desktop = @import("dotdesktop.zig");
@@ -412,15 +413,14 @@ pub const Worker = struct {
};
const zdir = a.dupeSentinel(u8, self.dir, 0) catch return;
defer a.free(zdir);
- const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
- defer if (fd >= 0) {
- _ = c.close(fd);
- };
- var wd: c_int = -1;
+ // Without file watching `watcher.fd` stays -1 and only commands wake the loop.
+ var watcher = platform.watch.Watcher.init() catch platform.watch.Watcher{};
+ defer watcher.deinit();
+ var watch = platform.watch.none;
while (!self.stop.load(.acquire)) {
- if (fd >= 0 and wd < 0) {
+ if (watcher.fd >= 0 and watch < 0) {
_ = c.mkdir(zdir, 0o755);
- wd = c.inotify_add_watch(fd, zdir, c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_CLOSE_WRITE | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF);
+ watch = watcher.add(self.dir, .listing) orelse platform.watch.none;
}
_ = c.pthread_mutex_lock(&self.mutex);
if (self.pending_child_env) |env| {
@@ -446,7 +446,7 @@ pub const Worker = struct {
if (self.scan()) |snap| {
_ = c.pthread_mutex_lock(&self.mutex);
const old = self.pending;
- // Preserve an unconsumed result when inotify replaces a snapshot.
+ // Preserve an unconsumed result when a file change replaces a snapshot.
snap.created_folder = self.created_folder;
self.created_folder = null;
if (old) |previous| {
@@ -463,25 +463,22 @@ pub const Worker = struct {
}
var fds = [2]c.struct_pollfd{
.{ .fd = self.wake_worker, .events = c.POLLIN, .revents = 0 },
- .{ .fd = fd, .events = c.POLLIN, .revents = 0 },
+ .{ .fd = watcher.fd, .events = c.POLLIN, .revents = 0 },
};
// Only a failed watch retry needs a clock; commands and
// filesystem changes wake the poll directly.
- const timeout: c_int = if (fd >= 0 and wd < 0) 1000 else -1;
+ const timeout: c_int = if (watcher.fd >= 0 and watch < 0) 1000 else -1;
_ = c.poll(&fds, fds.len, timeout);
if (fds[0].revents & c.POLLIN != 0) drain(self.wake_worker);
if (fds[1].revents & c.POLLIN != 0) {
- var buf: [16384]u8 align(@alignOf(c.struct_inotify_event)) = undefined;
- while (true) {
- const n = c.read(fd, &buf, buf.len);
- if (n <= 0) break;
- var off: usize = 0;
- while (off + @sizeOf(c.struct_inotify_event) <= @as(usize, @intCast(n))) {
- const ev: *const c.struct_inotify_event = @ptrCast(@alignCast(&buf[off]));
- if (ev.mask & (c.IN_IGNORED | c.IN_DELETE_SELF | c.IN_MOVE_SELF) != 0) wd = -1;
- off += @sizeOf(c.struct_inotify_event) + ev.len;
+ var events: struct {
+ watch: platform.watch.Watch,
+ fn event(s: *@This(), ev: platform.watch.Event) void {
+ if (ev.flags.lost()) s.watch = platform.watch.none;
}
- }
+ } = .{ .watch = watch };
+ watcher.drain(&events, @TypeOf(events).event) catch {};
+ watch = events.watch;
self.refresh.store(true, .release);
}
}
diff --git a/src/dm/daemon.zig b/src/dm/daemon.zig
index 30b6fbb..b7e8236 100644
--- a/src/dm/daemon.zig
+++ b/src/dm/daemon.zig
@@ -13,6 +13,7 @@ const state_mod = @import("state.zig");
const proto = @import("proto.zig");
const dm_ipc = @import("dm_ipc");
const ws = @import("wayland_sessions");
+const platform = @import("platform");
const c = @import("c");
@@ -62,7 +63,7 @@ pub const Daemon = struct {
range: ws.UidRange = .{},
relay: state_mod.Relay,
- children: @import("child_set") = .{},
+ children: platform.child.Set = .{},
signal_fd: i32 = -1,
timer_fd: i32 = -1,
timer: Timer = .none,
@@ -292,7 +293,7 @@ pub const Daemon = struct {
n += 2;
}
if (self.is_test) args[n] = "--test";
- _ = linux.execve("/proc/self/exe", &args, @ptrCast(std.c.environ));
+ platform.exe.execSelf(&args, @ptrCast(std.c.environ));
linux.exit_group(127);
}
diff --git a/src/dm/worker.zig b/src/dm/worker.zig
index 66939ad..9d15dfc 100644
--- a/src/dm/worker.zig
+++ b/src/dm/worker.zig
@@ -9,6 +9,7 @@ const linux = std.os.linux;
const proto = @import("proto.zig");
const c = @import("c");
+const platform = @import("platform");
pub const pam_handle_t = opaque {};
@@ -121,15 +122,13 @@ pub fn runWorker(ctrl_fd: c_int, greeter_fd: c_int, confdir: ?[]const u8, is_tes
/// Waits for the session child. A termination signal ends its process group
/// (SIGTERM, then SIGKILL after `stop_grace_ms`); returns the wait status.
fn supervise(pid: linux.pid_t, signal_fd: i32) u32 {
- const pidfd_rc = linux.pidfd_open(pid, 0);
- if (linux.errno(pidfd_rc) == .SUCCESS) {
- const pidfd: i32 = @intCast(pidfd_rc);
- defer _ = linux.close(pidfd);
+ if (platform.child.Handle.open(pid)) |process| {
+ defer process.close();
var deadline: ?i64 = null;
var killed = false;
while (true) {
var fds = [_]linux.pollfd{
- .{ .fd = pidfd, .events = linux.POLL.IN, .revents = 0 },
+ .{ .fd = process.fd, .events = linux.POLL.IN, .revents = 0 },
.{ .fd = signal_fd, .events = linux.POLL.IN, .revents = 0 },
};
const timeout: i32 = if (deadline) |d| @intCast(@max(0, d - monotonicMs())) else -1;
@@ -150,7 +149,7 @@ fn supervise(pid: linux.pid_t, signal_fd: i32) u32 {
deadline = null;
}
}
- }
+ } else |_| {}
var status: u32 = 0;
while (linux.errno(linux.waitpid(pid, @ptrCast(&status), 0)) == .INTR) {}
return status;
diff --git a/src/editor/operation.zig b/src/editor/operation.zig
index ff9f22d..b790bad 100644
--- a/src/editor/operation.zig
+++ b/src/editor/operation.zig
@@ -1,6 +1,7 @@
//! Immutable file/chooser jobs. The UI only consumes results after the eventfd wakes it.
const std = @import("std");
const c = @import("../files/c.zig").api;
+const platform = @import("platform");
const document = @import("document.zig");
const Document = document.Document;
const a = std.heap.c_allocator;
@@ -125,17 +126,6 @@ fn ensureMemory(size: usize) !void {
const available = availableMemory() orelse return;
if (size + size / 8 > available) return error.OutOfMemory;
}
-pub fn executable(buf: []u8, name: []const u8) []const u8 {
- var path: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &path, path.len);
- if (n > 0 and n < path.len) {
- if (std.fs.path.dirname(path[0..@intCast(n)])) |dir| {
- const sibling = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch return name;
- if (c.access(sibling, c.X_OK) == 0) return sibling;
- }
- }
- return name;
-}
pub const Operation = struct {
pub const Kind = enum { load, save, open_dialog, save_dialog };
kind: Kind,
@@ -298,9 +288,9 @@ pub const Operation = struct {
defer _ = c.close(output);
try writeAll(input, json);
if (c.lseek(input, 0, c.SEEK_SET) < 0) return error.ReadFailed;
- var exe: [4096]u8 = undefined;
+ var exe: [platform.exe.max_path]u8 = undefined;
var child = try std.process.spawn(self.io, .{
- .argv = &.{ executable(&exe, "rediwm-files"), "--chooser-stdin" },
+ .argv = &.{ platform.exe.siblingOrName(&exe, "rediwm-files"), "--chooser-stdin" },
.stdin = .{ .file = .{ .handle = input, .flags = .{ .nonblocking = false } } },
.stdout = .{ .file = .{ .handle = output, .flags = .{ .nonblocking = false } } },
});
diff --git a/src/files/app.zig b/src/files/app.zig
index 226d467..b576c86 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -5,6 +5,7 @@ const scrollbar = @import("ui").widgets.scrollbar;
const splitter = @import("ui").widgets.splitter;
const anim = @import("ui").anim;
const c = @import("c.zig").api;
+const platform = @import("platform");
const worker_mod = @import("worker.zig");
const history_mod = @import("history.zig");
const ops_mod = @import("ops.zig");
@@ -69,7 +70,7 @@ pub const App = struct {
closed: bool = false,
torrents: @import("torrents.zig").Client = .{},
transfer_view: app_torrents.View = .{},
- children: @import("../child_set.zig") = .{},
+ children: platform.child.Set = .{},
chooser: ?chooser_mod.Options = null,
filename: Editor = .{},
chooser_done: bool = false,
diff --git a/src/files/app_opening.zig b/src/files/app_opening.zig
index 6ba2b16..b078caa 100644
--- a/src/files/app_opening.zig
+++ b/src/files/app_opening.zig
@@ -6,6 +6,7 @@ const tr = i18n.tr;
const App = @import("app.zig").App;
const archive = @import("archive.zig");
const c = @import("c.zig").api;
+const platform = @import("platform");
const image_formats = @import("../images/formats.zig");
const theme = @import("../icon_theme.zig");
const chooser_mod = @import("chooser.zig");
@@ -56,9 +57,9 @@ pub fn launchEditor(self: *App, token: []const u8) void {
const path = self.editor_path orelse return;
self.editor_path = null;
defer self.allocator.free(path);
- var exe: [4096]u8 = undefined;
+ var exe: [platform.exe.max_path]u8 = undefined;
var child = std.process.spawn(self.io, .{
- .argv = &.{ @import("../editor/operation.zig").executable(&exe, "rediwm-editor"), "--activation-token", token, "--", path },
+ .argv = &.{ platform.exe.siblingOrName(&exe, "rediwm-editor"), "--activation-token", token, "--", path },
}) catch {
self.setStatusNotice(tr("Could not open Text Editor"), true);
return;
@@ -93,16 +94,8 @@ pub fn launchPreview(self: *App, selected: usize) !void {
pub fn launchImageList(self: *App, fd: c_int, index: usize) !void {
var index_buf: [32]u8 = undefined;
const index_arg = try std.fmt.bufPrint(&index_buf, "{d}", .{index});
- var exe_buf: [4096]u8 = undefined;
- var sibling_buf: [4096]u8 = undefined;
- var executable: []const u8 = "rediwm-images";
- const n = c.readlink("/proc/self/exe", &exe_buf, exe_buf.len);
- if (n > 0 and n < exe_buf.len) {
- if (std.fs.path.dirname(exe_buf[0..@intCast(n)])) |dir| {
- const sibling = try std.fmt.bufPrintSentinel(&sibling_buf, "{s}/rediwm-images", .{dir}, 0);
- if (c.access(sibling, c.X_OK) == 0) executable = sibling;
- }
- }
+ var sibling_buf: [platform.exe.max_path]u8 = undefined;
+ const executable = platform.exe.siblingOrName(&sibling_buf, "rediwm-images");
var child = try std.process.spawn(self.io, .{
.argv = &.{ executable, "--list-stdin", index_arg },
.stdin = .{ .file = .{ .handle = fd, .flags = .{ .nonblocking = false } } },
@@ -153,17 +146,8 @@ pub fn openFile(self: *App, path: []const u8) void {
self.worker.recordOpened(path);
return;
}
- var executable: []const u8 = "rediwm-pdf";
- var exe_buf: [4096]u8 = undefined;
- var sibling_buf: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &exe_buf, exe_buf.len);
- if (n > 0 and n < exe_buf.len) {
- if (std.fs.path.dirname(exe_buf[0..@intCast(n)])) |dir| {
- if (std.fmt.bufPrintSentinel(&sibling_buf, "{s}/rediwm-pdf", .{dir}, 0)) |sibling| {
- if (c.access(sibling, c.X_OK) == 0) executable = sibling;
- } else |_| {}
- }
- }
+ var sibling_buf: [platform.exe.max_path]u8 = undefined;
+ const executable = platform.exe.siblingOrName(&sibling_buf, "rediwm-pdf");
var child = std.process.spawn(self.io, .{
.argv = &.{ executable, "--", path },
}) catch |err| {
@@ -240,9 +224,8 @@ pub fn chooseExtractionFolder(self: *App) void {
if (self.extract_picker_fd != null) return;
const path = self.selectedArchive() orelse return;
const source = self.allocator.dupe(u8, path) catch return;
- var exe: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &exe, exe.len);
- const executable: []const u8 = if (n > 0 and n < exe.len) exe[0..@intCast(n)] else "rediwm-files";
+ var exe: [platform.exe.max_path]u8 = undefined;
+ const executable: []const u8 = platform.exe.path(&exe) orelse "rediwm-files";
var child = std.process.spawn(self.io, .{
.argv = &.{ executable, "--folder", std.fs.path.dirname(path) orelse "/" },
.stdout = .pipe,
diff --git a/src/files/app_places.zig b/src/files/app_places.zig
index 80e436d..27d9297 100644
--- a/src/files/app_places.zig
+++ b/src/files/app_places.zig
@@ -5,6 +5,7 @@ const i18n = @import("i18n");
const tr = i18n.tr;
const App = @import("app.zig").App;
const c = @import("c.zig").api;
+const platform = @import("platform");
const recent = @import("recent.zig");
const volumes_mod = @import("volumes.zig");
const header = @import("header.zig");
@@ -113,9 +114,8 @@ pub fn openPlaceWindow(self: *App, index: usize) void {
self.setStatusNotice(tr("Could not open folder"), true);
return;
}
- var exe: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &exe, exe.len);
- const executable: []const u8 = if (n > 0 and n < exe.len) exe[0..@intCast(n)] else "rediwm-files";
+ var exe: [platform.exe.max_path]u8 = undefined;
+ const executable: []const u8 = platform.exe.path(&exe) orelse "rediwm-files";
var child = std.process.spawn(self.io, .{
.argv = &.{ executable, path },
}) catch {
diff --git a/src/files/app_terminal.zig b/src/files/app_terminal.zig
index 58936e8..dddd731 100644
--- a/src/files/app_terminal.zig
+++ b/src/files/app_terminal.zig
@@ -6,6 +6,7 @@ const App = @import("app.zig").App;
const model = @import("terminal/model.zig");
const tc = model.c;
const c = @import("c.zig").api;
+const platform = @import("platform");
const ui = @import("ui");
const Rect = @import("header.zig").Rect;
const scrollbar = ui.widgets.scrollbar;
@@ -143,11 +144,8 @@ pub fn terminalScopes(self: *App) bool {
}
pub fn terminalHelper(self: *App, name: []const u8, buffer: []u8) ![:0]u8 {
_ = self;
- var executable: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &executable, executable.len);
- if (n <= 0 or n >= executable.len) return error.NoExecutable;
- const directory = std.fs.path.dirname(executable[0..@intCast(n)]) orelse return error.NoExecutable;
- return std.fmt.bufPrintSentinel(buffer, "{s}/{s}", .{ directory, name }, 0);
+ const helper = platform.exe.sibling(buffer, name) orelse return error.NoExecutable;
+ return buffer[0..helper.len :0];
}
pub fn terminalStart(self: *App) void {
if (self.chooser != null or self.terminal.close_at != null) return;
diff --git a/src/files/main.zig b/src/files/main.zig
index c9b3fb7..d43c719 100644
--- a/src/files/main.zig
+++ b/src/files/main.zig
@@ -315,7 +315,7 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
if (self.app.terminal.session) |session| {
fds[19] = .{ .fd = terminal_c.ft_pty(session), .events = @intCast(c.POLLIN | @as(c_int, if (terminal_c.ft_wants_write(session)) c.POLLOUT else 0)), .revents = 0 };
fds[20] = .{ .fd = terminal_c.ft_channel(session), .events = @intCast(c.POLLIN | @as(c_int, if (terminal_c.ft_wants_request(session)) c.POLLOUT else 0)), .revents = 0 };
- fds[21].fd = terminal_c.ft_pidfd(session);
+ fds[21].fd = terminal_c.ft_exit_fd(session);
}
fds[22].fd = self.app.torrents.fd;
const send_count = self.sends.items.len;
diff --git a/src/files/settings.zig b/src/files/settings.zig
index d4e9be1..0cd2ac4 100644
--- a/src/files/settings.zig
+++ b/src/files/settings.zig
@@ -1,10 +1,11 @@
//! Follow the compositor's persisted theme without blocking the UI thread.
-//! `watch` arms inotify on the files' directories so followers sleep until a
+//! `watch` watches the files' directories so followers sleep until a
//! change; `poll` stats at most once per second and reads only after changes,
//! including atomic replacement. Shared by the Files, Images, PDF and System
//! Monitor clients.
const std = @import("std");
const c = @import("c.zig").api;
+const platform = @import("platform");
const anim = @import("ui").anim;
const anim_config = @import("config").animations;
const theme = @import("ui").theme;
@@ -109,19 +110,14 @@ pub const Settings = struct {
if (self.theme_path) |p| a.free(p);
}
- /// Adds inotify watches on the directories holding the config and theme
- /// files, so atomic saves are seen too. A missing directory is replaced by
- /// its nearest existing parent: call again after events, so a created
- /// directory gets its own watch (re-adding a watch is harmless).
- pub fn watch(self: *const Settings, fd: c_int) void {
+ /// Watches the directories holding the config and theme files, so atomic
+ /// saves are seen too. A missing directory is replaced by its nearest
+ /// existing parent: call again after events, so a created directory gets
+ /// its own watch (re-adding a watch is harmless).
+ pub fn watch(self: *const Settings, watcher: platform.watch.Watcher) void {
for ([_]?[:0]const u8{ self.config_path, self.theme_path }) |maybe_path| {
- var parent = std.fs.path.dirname(maybe_path orelse continue) orelse continue;
- while (true) {
- var buf: [4096]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&buf, "{s}", .{parent}, 0) catch break;
- if (c.inotify_add_watch(fd, path, c.IN_CLOSE_WRITE | c.IN_MOVED_TO | c.IN_CREATE | c.IN_DELETE | c.IN_DELETE_SELF | c.IN_MOVE_SELF) >= 0) break;
- parent = std.fs.path.dirname(parent) orelse break;
- }
+ const parent = std.fs.path.dirname(maybe_path orelse continue) orelse continue;
+ _ = watcher.addOrParent(parent, .{ .written = true, .moved_to = true, .created = true, .deleted = true });
}
}
diff --git a/src/files/terminal/engine.c b/src/files/terminal/engine.c
index 3320ae5..a1103bc 100644
--- a/src/files/terminal/engine.c
+++ b/src/files/terminal/engine.c
@@ -20,8 +20,8 @@
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
-#include <sys/syscall.h>
#include <sys/wait.h>
+#include "../../platform/child.h"
#if VTERM_VERSION_MAJOR != 0 || VTERM_VERSION_MINOR != 3 || VTERM_VERSION_PATCH < 3
#error Files requires libvterm 0.3.3 (0.3 ABI)
@@ -42,7 +42,7 @@ struct ft_terminal {
VTerm *vt;
VTermScreen *screen;
VTermState *state;
- int master, channel, pidfd;
+ int master, channel, process;
pid_t pid;
bool exited, eof, changed, cursor_visible, reverse, alternate;
int exit_status, rows, cols, mouse, cursor_shape;
@@ -171,7 +171,7 @@ FT *ft_new_alloc(int rows, int cols, const FT_Allocator *allocator) {
FT *t=a.alloc(a.owner,sizeof *t);
if (!t) return NULL;
memset(t,0,sizeof *t); t->allocator=a;
- t->master=t->channel=t->pidfd=-1;
+ t->master=t->channel=t->process=-1;
t->rows=rows; t->cols=cols; t->cursor_visible=true; t->cursor_shape=1;
if (setjmp(t->allocation_failure)) { allocation_failed(t); ft_free(t); return NULL; }
t->vt=vterm_new_with_allocator(rows,cols,(VTermAllocatorFunctions *)&terminal_allocator,t);
@@ -219,8 +219,8 @@ int ft_start(FT *t, const char *helper, const char *plugin, const char *director
posix_spawn_file_actions_destroy(&actions);
if (rc) { errno=rc; goto failed; }
close(slave); close(pair[1]); t->master=master; t->channel=pair[0];
- t->pidfd=(int)syscall(SYS_pidfd_open,t->pid,0);
- if (t->pidfd<0) { ft_close(t,true); t->error="Could not watch terminal process"; return -1; }
+ t->process=rediwm_child_open(t->pid);
+ if (t->process<0) { ft_close(t,true); t->error="Could not watch terminal process"; return -1; }
t->changed=true; return 0;
failed:
if (master>=0) close(master);
@@ -248,7 +248,7 @@ void ft_feed(FT *t, const char *bytes, size_t len) {
}
int ft_pty(const FT *t) { return t->master; }
int ft_channel(const FT *t) { return t->channel; }
-int ft_pidfd(const FT *t) { return t->exited ? -1 : t->pidfd; }
+int ft_exit_fd(const FT *t) { return t->exited ? -1 : t->process; }
bool ft_wants_write(const FT *t) { return t->out_len>0 && !t->eof; }
bool ft_wants_request(const FT *t) { return t->channel>=0 && t->request_queued; }
@@ -295,10 +295,10 @@ static void signal_session(FT *t, int sig) {
char *end; long value=strtol(entry->d_name,&end,10);
if (!*entry->d_name || *end || value<=0 || value>INT_MAX || value==t->pid) continue;
pid_t pid=(pid_t)value;
- int fd=(int)syscall(SYS_pidfd_open,pid,0);
- if (fd<0) continue;
- if (getsid(pid)==t->pid) (void)syscall(SYS_pidfd_send_signal,fd,sig,NULL,0);
- close(fd);
+ int member=rediwm_child_open(pid);
+ if (member<0) continue;
+ if (getsid(pid)==t->pid) (void)rediwm_child_signal(member,sig);
+ rediwm_child_close(member);
}
closedir(proc);
}
@@ -317,7 +317,7 @@ void ft_io(FT *t, bool read_pty, bool write_pty, bool channel, bool exited) {
if (channel) integration(t);
if (exited && t->pid>0 && !t->exited) {
int status=0;
- /* pidfd readiness proves exit; retain the zombie until all remaining
+ /* Readiness of the exit descriptor proves exit; retain the zombie until all remaining
* members of this terminal's session have received their final signal. */
signal_session(t,SIGKILL);
pid_t rc=waitpid(t->pid,&status,WNOHANG);
@@ -336,7 +336,7 @@ void ft_close(FT *t, bool force) {
if (t->pid>0 && !t->exited) {
int signal=force ? SIGKILL : SIGHUP;
signal_session(t,signal);
- if (t->pidfd>=0) (void)syscall(SYS_pidfd_send_signal,t->pidfd,signal,NULL,0);
+ if (t->process>=0) (void)rediwm_child_signal(t->process,signal);
else (void)kill(t->pid,signal);
}
}
@@ -346,7 +346,7 @@ void ft_free(FT *t) {
if (t->pid>0 && !t->exited) (void)waitpid(t->pid,NULL,WNOHANG);
if (t->master>=0) close(t->master);
if (t->channel>=0) close(t->channel);
- if (t->pidfd>=0) close(t->pidfd);
+ if (t->process>=0) rediwm_child_close(t->process);
while(t->count) drop_oldest(t);
if (t->vt) vterm_free(t->vt);
while (t->allocations) terminal_free(t->allocations+1,t);
diff --git a/src/files/terminal/engine.h b/src/files/terminal/engine.h
index 23a4a49..8fd2a1c 100644
--- a/src/files/terminal/engine.h
+++ b/src/files/terminal/engine.h
@@ -27,7 +27,7 @@ void ft_resize(FT *t, int rows, int cols);
void ft_feed(FT *t, const char *bytes, size_t len);
int ft_pty(const FT *t);
int ft_channel(const FT *t);
-int ft_pidfd(const FT *t);
+int ft_exit_fd(const FT *t);
bool ft_wants_write(const FT *t);
bool ft_wants_request(const FT *t);
void ft_io(FT *t, bool read_pty, bool write_pty, bool channel, bool exited);
diff --git a/src/files/torrent/helper.cpp b/src/files/torrent/helper.cpp
index d0cd7dd..c2b601a 100644
--- a/src/files/torrent/helper.cpp
+++ b/src/files/torrent/helper.cpp
@@ -7,6 +7,7 @@
// and takes their commands; helper_tray.cpp is the StatusNotifierItem and
// its menu. helper.hpp has what they share.
#include "helper.hpp"
+#include "../../platform/self_exe.h"
namespace helper {
@@ -269,9 +270,10 @@ int main(int argc, char **argv) {
if (lstat(state_dir.c_str(), &state_stat) || !S_ISDIR(state_stat.st_mode) ||
state_stat.st_uid != getuid() || (state_stat.st_mode & 077))
throw std::runtime_error("Transfer state directory is not private");
- executable =
- (fs::canonical("/proc/self/exe").parent_path() / "rediwm-files")
- .string();
+ char self[4096];
+ if (rediwm_self_exe(self, sizeof self) < 0)
+ throw std::runtime_error("Cannot locate the Files executable");
+ executable = (fs::path(self).parent_path() / "rediwm-files").string();
// Scope policy is supplied by the Files launcher, which uses the same
// native/nested rules as its other user-app launches.
use_scopes = argc > 1 && !strcmp(argv[1], "--scope");
diff --git a/src/files/worker.zig b/src/files/worker.zig
index ff607df..4d53ca6 100644
--- a/src/files/worker.zig
+++ b/src/files/worker.zig
@@ -3,6 +3,7 @@ const tr = @import("i18n").tr;
const archive = @import("archive.zig");
const appimage = @import("appimage.zig");
const c = @import("c.zig").api;
+const platform = @import("platform");
const theme = @import("../icon_theme.zig");
const icons = @import("../icon_cache.zig");
const git = @import("git.zig");
@@ -32,6 +33,18 @@ pub const Item = struct {
icon_candidates: []const []const u8 = &.{},
};
+/// What a pass over the browsed folder's events found: whether anything
+/// changed, and whether its watch must be set up again.
+const DirScan = struct {
+ watch: platform.watch.Watch,
+ changed: bool = false,
+
+ fn event(self: *DirScan, ev: platform.watch.Event) void {
+ if (ev.flags.isChange()) self.changed = true;
+ if (ev.watch == self.watch and ev.flags.lost()) self.watch = platform.watch.none;
+ }
+};
+
pub const Snapshot = struct {
arena: std.heap.ArenaAllocator,
request_id: u64,
@@ -286,17 +299,14 @@ pub const Worker = struct {
fn run(self: *Worker) void {
var settings: @import("settings.zig").Settings = @import("settings.zig").Settings.init(self.allocator, self.environ) catch .{};
defer settings.deinit(self.allocator);
- const inotify_fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
- defer if (inotify_fd >= 0) {
- _ = c.close(inotify_fd);
- };
- // Its own descriptor: the browsed folder can be the config directory,
+ // Without file watching the watchers keep fd -1 and the loop polls.
+ var dir_watcher = platform.watch.Watcher.init() catch platform.watch.Watcher{};
+ defer dir_watcher.deinit();
+ // Its own watcher: the browsed folder can be the config directory,
// and leaving it must not drop the theme watch.
- const theme_fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
- defer if (theme_fd >= 0) {
- _ = c.close(theme_fd);
- };
- if (theme_fd >= 0) settings.watch(theme_fd);
+ var theme_watcher = platform.watch.Watcher.init() catch platform.watch.Watcher{};
+ defer theme_watcher.deinit();
+ if (theme_watcher.fd >= 0) settings.watch(theme_watcher);
var theme_changed = true;
var watched_dir: ?[]u8 = null;
@@ -304,8 +314,8 @@ pub const Worker = struct {
var archive_cache: ArchiveCache = .{};
defer archive_cache.clear(self.allocator);
- var inotify_wd: c_int = -1;
- var git_watches: [4]c_int = @splat(-1);
+ var dir_watch = platform.watch.none;
+ var git_watches: [4]platform.watch.Watch = @splat(platform.watch.none);
while (true) {
_ = c.pthread_mutex_lock(&self.mutex);
@@ -333,7 +343,7 @@ pub const Worker = struct {
var opened_storage = opened;
opened_storage.deinit(self.allocator);
if (self.stop.load(.acquire)) break;
- const update = if (theme_fd < 0) settings.poll(self.allocator, self.io) else if (theme_changed) settings.reload(self.allocator, self.io) else null;
+ const update = if (theme_watcher.fd < 0) settings.poll(self.allocator, self.io) else if (theme_changed) settings.reload(self.allocator, self.io) else null;
theme_changed = false;
if (update) |t| {
const requested = collation.Locale.requested(t.region.formats, self.environ);
@@ -372,31 +382,21 @@ pub const Worker = struct {
const dir_changed = watched_dir == null or !std.mem.eql(u8, watched_dir.?, cur_dir);
if (dir_changed) {
- if (inotify_fd >= 0 and inotify_wd >= 0) {
- _ = c.inotify_rm_watch(inotify_fd, inotify_wd);
- inotify_wd = -1;
+ if (dir_watcher.fd >= 0 and dir_watch >= 0) {
+ dir_watcher.remove(dir_watch);
+ dir_watch = platform.watch.none;
}
if (watched_dir) |d| self.allocator.free(d);
watched_dir = self.allocator.dupe(u8, cur_dir) catch null;
- if (inotify_fd >= 0 and watched_dir != null) {
- var zpath_buf: [4096]u8 = undefined;
+ if (dir_watcher.fd >= 0 and watched_dir != null) {
const recent_path = if (recent.isLocation(cur_dir)) recent.path(self.allocator, self.environ) catch null else null;
defer if (recent_path) |p| self.allocator.free(p);
- var watch_path = if (recent_path) |p| std.fs.path.dirname(p).? else if (cur_archive_len > 0) std.fs.path.dirname(cur_dir[0..cur_archive_len]) orelse "/" else watched_dir.?;
- while (true) {
- const zp = std.fmt.bufPrintSentinel(&zpath_buf, "{s}", .{watch_path}, 0) catch break;
- inotify_wd = c.inotify_add_watch(
- inotify_fd,
- zp,
- c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO |
- c.IN_CLOSE_WRITE | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF,
- );
- // A first-run data directory may not exist yet. Watch
- // its nearest existing parent until it is created.
- if (inotify_wd >= 0 or recent_path == null) break;
- watch_path = std.fs.path.dirname(watch_path) orelse break;
- }
+ const watch_path = if (recent_path) |p| std.fs.path.dirname(p).? else if (cur_archive_len > 0) std.fs.path.dirname(cur_dir[0..cur_archive_len]) orelse "/" else watched_dir.?;
+ // A first-run data directory may not exist yet. Watch
+ // its nearest existing parent until it is created.
+ const found = if (recent_path != null) dir_watcher.addOrParent(watch_path, .listing) else dir_watcher.add(watch_path, .listing);
+ dir_watch = found orelse platform.watch.none;
}
}
@@ -409,16 +409,15 @@ pub const Worker = struct {
};
// Register new watches before dropping old ones. Re-adding an
// existing path returns its descriptor and creates no events.
- var next_watches: [4]c_int = @splat(-1);
- if (inotify_fd >= 0) {
+ var next_watches: [4]platform.watch.Watch = @splat(platform.watch.none);
+ if (dir_watcher.fd >= 0) {
if (snap.repository) |repo| {
for (repo.watch_paths, 0..) |path, i| {
- const zp = snap.arena.allocator().dupeSentinel(u8, path, 0) catch continue;
- next_watches[i] = c.inotify_add_watch(inotify_fd, zp, c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_CLOSE_WRITE | c.IN_DELETE_SELF | c.IN_MOVE_SELF);
+ next_watches[i] = dir_watcher.add(path, .{ .created = true, .deleted = true, .moved_from = true, .moved_to = true, .written = true }) orelse platform.watch.none;
}
}
- for (git_watches) |wd| {
- if (wd >= 0 and std.mem.indexOfScalar(c_int, &next_watches, wd) == null) _ = c.inotify_rm_watch(inotify_fd, wd);
+ for (git_watches) |watch| {
+ if (watch >= 0 and std.mem.indexOfScalar(platform.watch.Watch, &next_watches, watch) == null) dir_watcher.remove(watch);
}
}
git_watches = next_watches;
@@ -430,19 +429,18 @@ pub const Worker = struct {
if (old) |o| o.destroy();
}
- if (inotify_fd >= 0) {
+ if (dir_watcher.fd >= 0) {
var fds = [3]c.struct_pollfd{
.{ .fd = self.wake, .events = c.POLLIN, .revents = 0 },
- .{ .fd = inotify_fd, .events = c.POLLIN, .revents = 0 },
- .{ .fd = theme_fd, .events = c.POLLIN, .revents = 0 },
+ .{ .fd = dir_watcher.fd, .events = c.POLLIN, .revents = 0 },
+ .{ .fd = theme_watcher.fd, .events = c.POLLIN, .revents = 0 },
};
// Requests, directory and theme changes wake the poll. Without
// a theme watch the timeout paces Settings.poll's once-a-second stat.
- const poll_res = c.poll(&fds, fds.len, if (theme_fd >= 0) -1 else 1000);
+ const poll_res = c.poll(&fds, fds.len, if (theme_watcher.fd >= 0) -1 else 1000);
if (poll_res > 0 and (fds[2].revents & c.POLLIN != 0)) {
- var buf: [4096]u8 align(@alignOf(c.struct_inotify_event)) = undefined;
- while (c.read(theme_fd, &buf, buf.len) > 0) {}
- settings.watch(theme_fd);
+ _ = theme_watcher.flush();
+ settings.watch(theme_watcher);
theme_changed = true;
}
if (poll_res > 0 and (fds[0].revents & c.POLLIN != 0)) {
@@ -450,22 +448,10 @@ pub const Worker = struct {
_ = c.read(self.wake, &count, @sizeOf(u64));
}
if (poll_res > 0 and (fds[1].revents & c.POLLIN != 0)) {
- var buf: [4096]u8 align(@alignOf(c.struct_inotify_event)) = undefined;
- var changed = false;
- while (true) {
- const n = c.read(inotify_fd, &buf, buf.len);
- if (n <= 0) break;
- var off: usize = 0;
- while (off + @sizeOf(c.struct_inotify_event) <= @as(usize, @intCast(n))) {
- const ev: *const c.struct_inotify_event = @ptrCast(@alignCast(&buf[off]));
- if (ev.mask & ~@as(u32, c.IN_IGNORED) != 0) changed = true;
- if (ev.wd == inotify_wd and ev.mask & (c.IN_IGNORED | c.IN_DELETE_SELF | c.IN_MOVE_SELF) != 0) {
- inotify_wd = -1;
- }
- off += @sizeOf(c.struct_inotify_event) + ev.len;
- }
- }
- if (changed) {
+ var events: DirScan = .{ .watch = dir_watch };
+ dir_watcher.drain(&events, DirScan.event) catch {};
+ dir_watch = events.watch;
+ if (events.changed) {
self.rescan_requested.store(true, .release);
if (recent.isLocation(cur_dir)) {
// Re-establish the watch after creation or replacement
diff --git a/src/ipc/server.zig b/src/ipc/server.zig
index 4bf167e..191dc7d 100644
--- a/src/ipc/server.zig
+++ b/src/ipc/server.zig
@@ -1,5 +1,6 @@
const std = @import("std");
const wl = @import("wayland").server.wl;
+const platform = @import("platform");
const CompositorServer = @import("../Server.zig");
const protocol = @import("protocol.zig");
@@ -326,9 +327,6 @@ const Ucred = extern struct {
gid: std.posix.gid_t,
};
-const SO_PEERPIDFD: c_int = 77;
-extern "c" fn pidfd_send_signal(pidfd: c_int, sig: c_int, info: ?*anyopaque, flags: c_uint) c_int;
-
pub fn parseFlatpakAppId(content: []const u8) ?[]const u8 {
var in_application_section = false;
var line_it = std.mem.splitScalar(u8, content, '\n');
@@ -359,17 +357,8 @@ pub fn parseFlatpakAppId(content: []const u8) ?[]const u8 {
fn detectSandbox(pid: i32, client_fd: c_int, allocator: std.mem.Allocator) ?SandboxCaller {
if (pid <= 0) return null;
- var pidfd: c_int = -1;
- var pidfd_len: std.posix.socklen_t = @sizeOf(c_int);
- if (c.getsockopt(client_fd, std.posix.SOL.SOCKET, SO_PEERPIDFD, @ptrCast(&pidfd), &pidfd_len) < 0 or pidfd < 0) {
- const rc = std.os.linux.pidfd_open(pid, 0);
- if (std.os.linux.errno(rc) == .SUCCESS) {
- pidfd = @intCast(rc);
- } else {
- pidfd = -1;
- }
- }
- defer if (pidfd >= 0) closeFd(pidfd);
+ const process: ?platform.child.Handle = platform.child.Handle.peer(client_fd) orelse platform.child.Handle.open(pid) catch null;
+ defer if (process) |handle| handle.close();
var proc_buf: [64]u8 = undefined;
const proc_path = std.fmt.bufPrintSentinel(&proc_buf, "/proc/{d}", .{pid}, 0) catch return null;
@@ -388,16 +377,9 @@ fn detectSandbox(pid: i32, client_fd: c_int, allocator: std.mem.Allocator) ?Sand
}
defer closeFd(file_fd);
- if (pidfd >= 0) {
- if (pidfd_send_signal(pidfd, 0, null, 0) != 0) {
- return .{ .app_id = null, .engine = "org.flatpak" };
- }
- } else {
- const rc = std.os.linux.syscall2(.kill, @as(usize, @bitCast(@as(isize, pid))), 0);
- if (std.os.linux.errno(rc) != .SUCCESS) {
- return .{ .app_id = null, .engine = "org.flatpak" };
- }
- }
+ // The peer must still be the process whose root we read.
+ const present = if (process) |handle| handle.alive() else platform.child.exists(pid);
+ if (!present) return .{ .app_id = null, .engine = "org.flatpak" };
var buf: [16 * 1024]u8 = undefined;
const nread = c.read(file_fd, &buf, buf.len);
diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.md
new file mode 100644
index 0000000..1bcbae3
--- /dev/null
+++ b/src/platform/AGENTS.md
@@ -0,0 +1,24 @@
+# Platform module
+
+The one place the OS shows: child handles (`child.zig`), directory watching
+(`watch.zig`), the program's own path (`exe.zig`), and `child.h`/`self_exe.h`
+for C and C++. Std only, no compositor imports. Linux today; the FreeBSD port
+(`docs/plans/freebsd.md`) adds `freebsd_*.zig` parts without changing callers.
+
+* **A `Handle` is not a pid.** Hold it for as long as you may signal; a bare
+ `kill(pid)` is only safe while you have not reaped the child. `pid()` is
+ null once reaped, but an unreaped zombie keeps its pid: check `exited()` too.
+* **`Child` reaps, `Child.observe` does not.** Use `observe` when another owner
+ (`session/services.zig`) collects the status; two reapers race.
+* **Watch directories, not files**, so atomic replacement is seen. Adding a
+ watched directory again returns the same `Watch` and queues nothing: add the
+ new watches before removing the old. `isChange()` is "something happened or
+ events were lost"; `lost()` means re-add the watch. Prefer `written` and
+ `moved_to` over `modified` (often half-written).
+* `drain` returning `error.Broken` means stop using the watcher. Callbacks may
+ add watches, not call `drain`. Event names are valid only in the callback.
+* Nothing here arms a timer or starts a thread; a caller retrying a failed
+ `add` owns that clock.
+
+Still direct Linux calls (later steps of the plan's phase P): `signalfd`/`epoll`
+in the supervisor and DM daemon, `kill`/`wait4`, `/proc` walks, `SO_PEERCRED`.
diff --git a/src/platform/child.h b/src/platform/child.h
new file mode 100644
index 0000000..1c421d3
--- /dev/null
+++ b/src/platform/child.h
@@ -0,0 +1,27 @@
+/* Process handles for the C code that cannot import platform/child.zig; the
+ * same contract as child.Handle. A handle names one process even after its
+ * pid is reused, and its descriptor turns readable when the process exits,
+ * without reaping it. Linux uses pidfds. */
+#ifndef REDIWM_CHILD_H
+#define REDIWM_CHILD_H
+
+#include <stddef.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+/* A handle on a running process, or -1. */
+static inline int rediwm_child_open(pid_t pid) {
+ return (int)syscall(SYS_pidfd_open, pid, 0);
+}
+
+/* Signals the process the handle was opened for; 0 on success. */
+static inline int rediwm_child_signal(int handle, int sig) {
+ return (int)syscall(SYS_pidfd_send_signal, handle, sig, NULL, 0);
+}
+
+static inline void rediwm_child_close(int handle) {
+ close(handle);
+}
+
+#endif
diff --git a/src/platform/child.zig b/src/platform/child.zig
new file mode 100644
index 0000000..60725ae
--- /dev/null
+++ b/src/platform/child.zig
@@ -0,0 +1,240 @@
+//! Child processes by identity, not by pid. A `Handle` addresses the process
+//! it was opened for even after the pid is reused, and its `fd` turns readable
+//! when the process exits, without reaping it: the owner still collects the
+//! status with `reap`. Linux backs it with pidfds. Callers poll `fd` from the
+//! Wayland loop, `poll` or a `Set`; nothing here starts a thread or a timer.
+const std = @import("std");
+const linux = std.os.linux;
+
+pub const Pid = linux.pid_t;
+pub const Signal = linux.SIG;
+
+pub const Error = error{
+ /// The process is gone (or was never there).
+ NoSuchProcess,
+ PermissionDenied,
+ /// The system cannot give a handle on a process.
+ Unsupported,
+ Failed,
+};
+
+fn classify(err: linux.E) Error {
+ return switch (err) {
+ .SRCH, .NOENT => error.NoSuchProcess,
+ .PERM, .ACCES => error.PermissionDenied,
+ .NOSYS, .INVAL => error.Unsupported,
+ else => error.Failed,
+ };
+}
+
+pub const Handle = struct {
+ /// Readable once the process has exited; never carries data.
+ fd: i32,
+
+ /// Opens a handle on a running process. The caller closes it.
+ pub fn open(process: Pid) Error!Handle {
+ const rc = linux.pidfd_open(process, 0);
+ if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
+ return .{ .fd = @intCast(rc) };
+ }
+
+ /// The handle of the process at the other end of a connected Unix socket,
+ /// when the system can name it race-free. Null otherwise: fall back to
+ /// `open` on the credentials' pid.
+ pub fn peer(socket: i32) ?Handle {
+ const so_peerpidfd = 77;
+ var fd: i32 = -1;
+ var len: u32 = @sizeOf(i32);
+ const rc = linux.getsockopt(socket, linux.SOL.SOCKET, so_peerpidfd, @ptrCast(&fd), &len);
+ if (linux.errno(rc) != .SUCCESS or fd < 0) return null;
+ return .{ .fd = fd };
+ }
+
+ pub fn close(self: Handle) void {
+ _ = linux.close(self.fd);
+ }
+
+ /// Signals the process this handle was opened for, never a pid reused
+ /// since. Signal 0 only checks that it is still there.
+ pub fn signal(self: Handle, sig: Signal) Error!void {
+ const rc = linux.pidfd_send_signal(self.fd, sig, null, 0);
+ if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
+ }
+
+ pub fn alive(self: Handle) bool {
+ self.signal(@enumFromInt(0)) catch return false;
+ return true;
+ }
+
+ /// A nonblocking check of `fd`: has the process exited.
+ pub fn exited(self: Handle) bool {
+ var fds = [_]linux.pollfd{.{ .fd = self.fd, .events = linux.POLL.IN, .revents = 0 }};
+ return linux.errno(linux.poll(&fds, 1, 0)) == .SUCCESS and fds[0].revents != 0;
+ }
+
+ /// The pid of the process this handle is on: null once it has exited and
+ /// been reaped, even if the number was reused since. An unreaped zombie
+ /// still has its pid (see `exited`). Unavailable when the system cannot say.
+ pub fn pid(self: Handle) error{Unavailable}!?Pid {
+ var path: [64]u8 = undefined;
+ const name = std.fmt.bufPrintSentinel(&path, "/proc/self/fdinfo/{d}", .{self.fd}, 0) catch unreachable;
+ const opened = linux.openat(linux.AT.FDCWD, name.ptr, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NOFOLLOW = true }, 0);
+ if (linux.errno(opened) != .SUCCESS) return error.Unavailable;
+ const info_fd: i32 = @intCast(opened);
+ defer _ = linux.close(info_fd);
+ var buf: [4096]u8 = undefined;
+ var len: usize = 0;
+ while (len < buf.len) {
+ const rc = linux.read(info_fd, buf[len..].ptr, buf.len - len);
+ switch (linux.errno(rc)) {
+ .SUCCESS => {},
+ .INTR => continue,
+ else => return error.Unavailable,
+ }
+ if (rc == 0) break;
+ len += rc;
+ } else return error.Unavailable;
+ var lines = std.mem.splitScalar(u8, buf[0..len], '\n');
+ while (lines.next()) |line| {
+ if (!std.mem.startsWith(u8, line, "Pid:")) continue;
+ const value = std.fmt.parseInt(Pid, std.mem.trim(u8, line["Pid:".len..], " \t"), 10) catch return error.Unavailable;
+ return if (value < 0) null else value;
+ }
+ return null;
+ }
+};
+
+/// Collects the wait status of a child that has exited (or null: still
+/// running, or somebody else reaped it). Never blocks.
+pub fn reap(pid: Pid) ?u32 {
+ var status: u32 = 0;
+ while (true) {
+ const rc = linux.wait4(pid, @ptrCast(&status), linux.W.NOHANG, null);
+ switch (linux.errno(rc)) {
+ .INTR => continue,
+ .SUCCESS => return if (rc == pid) status else null,
+ else => return null,
+ }
+ }
+}
+
+/// Whether a process with this pid exists right now. Racy by nature: the pid
+/// may be another process's by the time it matters; prefer a `Handle`.
+pub fn exists(pid: Pid) bool {
+ return linux.errno(linux.kill(pid, @enumFromInt(0))) == .SUCCESS;
+}
+
+/// Signals every member of the process group `pgid`, a leader's own pid.
+pub fn signalGroup(pgid: Pid, sig: Signal) void {
+ _ = linux.kill(-pgid, sig);
+}
+
+/// Handles for poll-based clients. One fd joins the application's normal
+/// event loop and turns readable when any member exits; a long-lived child
+/// requires no thread and causes no wakeups.
+pub const Set = struct {
+ const Entry = struct { pid: Pid, handle: Handle };
+ pub const Exit = struct { pid: Pid, status: ?u32 };
+
+ /// Readable while `next` has an exit to report; -1 until the first `add`.
+ fd: i32 = -1,
+ entries: std.ArrayList(Entry) = .empty,
+
+ pub fn add(self: *Set, allocator: std.mem.Allocator, pid: Pid) !void {
+ try self.entries.ensureUnusedCapacity(allocator, 1);
+ if (self.fd < 0) {
+ const rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
+ if (linux.errno(rc) != .SUCCESS) return error.Failed;
+ self.fd = @intCast(rc);
+ }
+ const handle = try Handle.open(pid);
+ errdefer handle.close();
+ var event: linux.epoll_event = .{ .events = linux.EPOLL.IN, .data = .{ .fd = handle.fd } };
+ if (linux.errno(linux.epoll_ctl(self.fd, linux.EPOLL.CTL_ADD, handle.fd, &event)) != .SUCCESS) return error.Failed;
+ self.entries.appendAssumeCapacity(.{ .pid = pid, .handle = handle });
+ }
+
+ /// The next child that exited, reaped, or null when none has.
+ pub fn next(self: *Set) ?Exit {
+ if (self.fd < 0) return null;
+ var events: [1]linux.epoll_event = undefined;
+ const rc = linux.epoll_wait(self.fd, &events, 1, 0);
+ if (linux.errno(rc) != .SUCCESS or rc == 0) return null;
+ for (self.entries.items, 0..) |entry, i| {
+ if (entry.handle.fd != events[0].data.fd) continue;
+ _ = linux.epoll_ctl(self.fd, linux.EPOLL.CTL_DEL, entry.handle.fd, null);
+ entry.handle.close();
+ _ = self.entries.swapRemove(i);
+ return .{ .pid = entry.pid, .status = reap(entry.pid) };
+ }
+ unreachable;
+ }
+
+ pub fn signalAll(self: *Set, sig: Signal) void {
+ for (self.entries.items) |entry| entry.handle.signal(sig) catch {};
+ }
+
+ pub fn deinit(self: *Set, allocator: std.mem.Allocator) void {
+ while (self.next() != null) {}
+ for (self.entries.items) |entry| entry.handle.close();
+ self.entries.deinit(allocator);
+ if (self.fd >= 0) _ = linux.close(self.fd);
+ self.* = .{};
+ }
+};
+
+fn waitReadable(fd: i32, timeout_ms: i32) bool {
+ var fds = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.IN, .revents = 0 }};
+ return linux.errno(linux.poll(&fds, 1, timeout_ms)) == .SUCCESS and fds[0].revents != 0;
+}
+
+test "a handle follows one process through signal, exit and reap" {
+ const io = std.testing.io;
+ var child = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ const pid = child.id.?;
+ const handle = try Handle.open(pid);
+ defer handle.close();
+ try std.testing.expect(handle.alive());
+ try std.testing.expect(!handle.exited());
+ try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+
+ try handle.signal(.TERM);
+ try std.testing.expect(waitReadable(handle.fd, 5000));
+ try std.testing.expect(handle.exited());
+ // The zombie keeps its pid until it is reaped; then the handle names nobody.
+ try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
+ const status = reap(pid).?;
+ try std.testing.expect(linux.W.IFSIGNALED(status) and linux.W.TERMSIG(status) == .TERM);
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+ try std.testing.expectEqual(@as(?Pid, null), try handle.pid());
+ try std.testing.expectError(error.NoSuchProcess, handle.signal(.TERM));
+ child.id = null;
+}
+
+test "a handle cannot be opened on a process that does not exist" {
+ try std.testing.expectError(error.NoSuchProcess, Handle.open(std.math.maxInt(Pid)));
+}
+
+test "a set reports each exit once with its status and signals the rest" {
+ const io = std.testing.io;
+ var quick = try std.process.spawn(io, .{ .argv = &.{ "/bin/sh", "-c", "exit 3" } });
+ var slow = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ var set: Set = .{};
+ defer set.deinit(std.testing.allocator);
+ try set.add(std.testing.allocator, quick.id.?);
+ try set.add(std.testing.allocator, slow.id.?);
+ try std.testing.expect(waitReadable(set.fd, 5000));
+ const first = set.next().?;
+ try std.testing.expectEqual(quick.id.?, first.pid);
+ try std.testing.expectEqual(@as(u8, 3), linux.W.EXITSTATUS(first.status.?));
+ try std.testing.expect(set.next() == null);
+ set.signalAll(.KILL);
+ try std.testing.expect(waitReadable(set.fd, 5000));
+ const second = set.next().?;
+ try std.testing.expectEqual(slow.id.?, second.pid);
+ try std.testing.expect(linux.W.IFSIGNALED(second.status.?));
+ try std.testing.expectEqual(@as(usize, 0), set.entries.items.len);
+ quick.id = null;
+ slow.id = null;
+}
diff --git a/src/platform/exe.zig b/src/platform/exe.zig
new file mode 100644
index 0000000..ba7d0d7
--- /dev/null
+++ b/src/platform/exe.zig
@@ -0,0 +1,51 @@
+//! The running program's own executable, for launching its siblings
+//! (`rediwm-files`, `rediwm-pdf`, the Files terminal helper) and itself.
+//! Linux reads `/proc/self/exe`; `self_exe.h` is the C side.
+const std = @import("std");
+const linux = std.os.linux;
+
+/// Room for any path the callers hand to `std.process.spawn`.
+pub const max_path = 4096;
+
+/// The absolute path of the running executable, in `buf`. Null when the link
+/// cannot be read or the path does not fit.
+pub fn path(buf: []u8) ?[]const u8 {
+ const rc = linux.readlink("/proc/self/exe", buf.ptr, buf.len);
+ if (linux.errno(rc) != .SUCCESS or rc == 0 or rc >= buf.len) return null;
+ return buf[0..rc];
+}
+
+/// `<directory of this executable>/<name>`, NUL-terminated in `buf`. Null
+/// when the executable's path is unknown or the result does not fit.
+pub fn sibling(buf: []u8, name: []const u8) ?[:0]const u8 {
+ var exe: [max_path]u8 = undefined;
+ const dir = std.fs.path.dirname(path(&exe) orelse return null) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch null;
+}
+
+/// The sibling when it exists and is executable, else bare `name`, which the
+/// spawner looks up on `PATH`.
+pub fn siblingOrName(buf: []u8, name: []const u8) []const u8 {
+ const found = sibling(buf, name) orelse return name;
+ return if (linux.errno(linux.access(found.ptr, std.posix.X_OK)) == .SUCCESS) found else name;
+}
+
+/// Replaces this process with a fresh copy of the same program image. Returns
+/// only when the exec failed; callable between fork and exec (no allocation).
+pub fn execSelf(argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) void {
+ _ = linux.execve("/proc/self/exe", argv, envp);
+}
+
+test "own path is absolute and siblings sit beside it" {
+ var buf: [max_path]u8 = undefined;
+ const self = path(&buf).?;
+ try std.testing.expect(std.fs.path.isAbsolute(self));
+ var other: [max_path]u8 = undefined;
+ const beside = sibling(&other, "rediwm-files").?;
+ try std.testing.expectEqualStrings(std.fs.path.dirname(self).?, std.fs.path.dirname(beside).?);
+ try std.testing.expectEqualStrings("rediwm-files", std.fs.path.basename(beside));
+ // No such sibling: the bare name is left to the spawner's PATH lookup.
+ try std.testing.expectEqualStrings("rediwm-no-such-program", siblingOrName(&other, "rediwm-no-such-program"));
+ // The test binary itself is an executable sibling.
+ try std.testing.expectEqualStrings(self, siblingOrName(&other, std.fs.path.basename(self)));
+}
diff --git a/src/platform/mod.zig b/src/platform/mod.zig
new file mode 100644
index 0000000..74a17e9
--- /dev/null
+++ b/src/platform/mod.zig
@@ -0,0 +1,13 @@
+//! Everything that differs between operating systems, behind one interface:
+//! child processes, file-change notification and the program's own path.
+//! Callers never test the OS; `std.os.linux` is used only in here (see
+//! `AGENTS.md` beside this file). No compositor imports.
+pub const child = @import("child.zig");
+pub const exe = @import("exe.zig");
+pub const watch = @import("watch.zig");
+
+test {
+ _ = child;
+ _ = exe;
+ _ = watch;
+}
diff --git a/src/platform/self_exe.h b/src/platform/self_exe.h
new file mode 100644
index 0000000..93c03c0
--- /dev/null
+++ b/src/platform/self_exe.h
@@ -0,0 +1,20 @@
+/* The running program's own path, for the C and C++ code that cannot import
+ * platform/exe.zig. Linux reads /proc/self/exe. */
+#ifndef REDIWM_SELF_EXE_H
+#define REDIWM_SELF_EXE_H
+
+#include <stddef.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+/* Writes the NUL-terminated absolute path of the running executable into
+ * `buf`. Returns its length, or -1 when it cannot be read or does not fit. */
+static inline ssize_t rediwm_self_exe(char *buf, size_t size) {
+ if (size < 2) return -1;
+ ssize_t len = readlink("/proc/self/exe", buf, size - 1);
+ if (len <= 0) return -1;
+ buf[len] = '\0';
+ return len;
+}
+
+#endif
diff --git a/src/platform/watch.zig b/src/platform/watch.zig
new file mode 100644
index 0000000..e08627a
--- /dev/null
+++ b/src/platform/watch.zig
@@ -0,0 +1,284 @@
+//! File-change notification for directories. A `Watcher` is one pollable fd
+//! that turns readable while events are queued; hand `fd` to the Wayland
+//! loop or a `poll` and call `drain` when it fires. Linux backs it with
+//! inotify; events carry the entry name and neutral flags, so a backend
+//! without names can synthesize them by diffing the directory.
+const std = @import("std");
+const linux = std.os.linux;
+
+/// One watched directory. Negative means none.
+pub const Watch = i32;
+pub const none: Watch = -1;
+
+/// What to be told about (`add`), and what happened (`Event.flags`).
+pub const Flags = packed struct(u16) {
+ /// An entry appeared in the directory.
+ created: bool = false,
+ deleted: bool = false,
+ /// An entry's contents changed. Often half-written; prefer `written`.
+ modified: bool = false,
+ moved_from: bool = false,
+ moved_to: bool = false,
+ /// A writer closed an entry: the contents are complete.
+ written: bool = false,
+ attrib: bool = false,
+ /// Event only: the watched directory itself was deleted, moved or
+ /// unmounted. Always reported, and followed by `dropped`.
+ self_gone: bool = false,
+ /// Event only: the watch no longer exists (removed, or its directory
+ /// went away). Always reported.
+ dropped: bool = false,
+ /// Event only: the queue overflowed and events were lost.
+ overflow: bool = false,
+ /// Event only: the entry is a directory.
+ is_dir: bool = false,
+ _: u5 = 0,
+
+ /// What a directory listing shows: names, contents, attributes.
+ pub const listing: Flags = .{ .created = true, .deleted = true, .moved_from = true, .moved_to = true, .written = true, .attrib = true };
+
+ pub fn matches(self: Flags, other: Flags) bool {
+ return @as(u16, @bitCast(self)) & @as(u16, @bitCast(other)) != 0;
+ }
+
+ /// Something happened to the directory's contents or the directory
+ /// itself, or events were lost. Not the bookkeeping `dropped` alone.
+ pub fn isChange(self: Flags) bool {
+ const bookkeeping: Flags = .{ .dropped = true, .is_dir = true };
+ return @as(u16, @bitCast(self)) & ~@as(u16, @bitCast(bookkeeping)) != 0;
+ }
+
+ /// The watch is dead: re-add it if the directory is still wanted.
+ pub fn lost(self: Flags) bool {
+ return self.matches(.{ .self_gone = true, .dropped = true });
+ }
+};
+
+pub const Event = struct {
+ watch: Watch,
+ /// The entry inside the watched directory; empty for the directory itself.
+ /// Valid only during the callback.
+ name: []const u8,
+ flags: Flags,
+};
+
+pub const Watcher = struct {
+ fd: i32 = -1,
+
+ pub fn init() error{Unavailable}!Watcher {
+ const rc = linux.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC);
+ if (linux.errno(rc) != .SUCCESS) return error.Unavailable;
+ return .{ .fd = @intCast(rc) };
+ }
+
+ pub fn deinit(self: *Watcher) void {
+ if (self.fd >= 0) _ = linux.close(self.fd);
+ self.fd = -1;
+ }
+
+ /// Watches a directory, which must exist. Adding one already watched
+ /// returns its existing `Watch`, changes only the interest, and queues no
+ /// events, so a set of watches can be refreshed before the old ones go.
+ pub fn add(self: Watcher, path: []const u8, interest: Flags) ?Watch {
+ var buf: [std.posix.PATH_MAX]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null;
+ const rc = linux.inotify_add_watch(self.fd, z.ptr, mask(interest));
+ if (linux.errno(rc) != .SUCCESS) return null;
+ return @intCast(rc);
+ }
+
+ /// `add`, falling back to the nearest existing parent directory, for
+ /// places that may not exist yet. Call again after events to move the
+ /// watch down once the directory has been created.
+ pub fn addOrParent(self: Watcher, path: []const u8, interest: Flags) ?Watch {
+ var at = path;
+ while (true) {
+ if (self.add(at, interest)) |watch| return watch;
+ at = std.fs.path.dirname(at) orelse return null;
+ }
+ }
+
+ pub fn remove(self: Watcher, watch: Watch) void {
+ _ = linux.inotify_rm_watch(self.fd, watch);
+ }
+
+ /// Calls `onEvent(ctx, event)` for every queued event. `Broken` means the
+ /// stream ended or was malformed: stop using this watcher.
+ pub fn drain(self: Watcher, ctx: anytype, comptime onEvent: fn (@TypeOf(ctx), Event) void) error{Broken}!void {
+ return self.drainBounded(ctx, onEvent, std.math.maxInt(usize));
+ }
+
+ /// `drain`, reading at most `max_batches` buffers (8 KiB, a few hundred
+ /// events each); the fd stays readable if more remain.
+ pub fn drainBounded(self: Watcher, ctx: anytype, comptime onEvent: fn (@TypeOf(ctx), Event) void, max_batches: usize) error{Broken}!void {
+ var buf: [8192]u8 align(@alignOf(linux.inotify_event)) = undefined;
+ var batches: usize = 0;
+ while (batches < max_batches) : (batches += 1) {
+ const rc = linux.read(self.fd, &buf, buf.len);
+ switch (linux.errno(rc)) {
+ .SUCCESS => {},
+ .INTR => continue,
+ .AGAIN => return,
+ else => return error.Broken,
+ }
+ if (rc == 0) return error.Broken;
+ var off: usize = 0;
+ while (off < rc) {
+ const body = off + @sizeOf(linux.inotify_event);
+ if (body > rc) return error.Broken;
+ const raw: *const linux.inotify_event = @ptrCast(@alignCast(&buf[off]));
+ if (raw.len > rc - body) return error.Broken;
+ onEvent(ctx, .{
+ .watch = raw.wd,
+ .name = std.mem.sliceTo(buf[body..][0..raw.len], 0),
+ .flags = flags(raw.mask),
+ });
+ off = body + raw.len;
+ }
+ }
+ }
+
+ /// Discards the queued events. True when there were any.
+ pub fn flush(self: Watcher) bool {
+ var seen = false;
+ self.drain(&seen, struct {
+ fn event(s: *bool, _: Event) void {
+ s.* = true;
+ }
+ }.event) catch return true;
+ return seen;
+ }
+};
+
+fn mask(interest: Flags) u32 {
+ var m: u32 = linux.IN.DELETE_SELF | linux.IN.MOVE_SELF;
+ if (interest.created) m |= linux.IN.CREATE;
+ if (interest.deleted) m |= linux.IN.DELETE;
+ if (interest.modified) m |= linux.IN.MODIFY;
+ if (interest.moved_from) m |= linux.IN.MOVED_FROM;
+ if (interest.moved_to) m |= linux.IN.MOVED_TO;
+ if (interest.written) m |= linux.IN.CLOSE_WRITE;
+ if (interest.attrib) m |= linux.IN.ATTRIB;
+ return m;
+}
+
+fn flags(m: u32) Flags {
+ return .{
+ .created = m & linux.IN.CREATE != 0,
+ .deleted = m & linux.IN.DELETE != 0,
+ .modified = m & linux.IN.MODIFY != 0,
+ .moved_from = m & linux.IN.MOVED_FROM != 0,
+ .moved_to = m & linux.IN.MOVED_TO != 0,
+ .written = m & linux.IN.CLOSE_WRITE != 0,
+ .attrib = m & linux.IN.ATTRIB != 0,
+ .self_gone = m & (linux.IN.DELETE_SELF | linux.IN.MOVE_SELF | linux.IN.UNMOUNT) != 0,
+ .dropped = m & linux.IN.IGNORED != 0,
+ .overflow = m & linux.IN.Q_OVERFLOW != 0,
+ .is_dir = m & linux.IN.ISDIR != 0,
+ };
+}
+
+const Seen = struct {
+ watch: Watch = none,
+ names: [8][16]u8 = undefined,
+ flags: [8]Flags = undefined,
+ count: usize = 0,
+
+ fn event(self: *Seen, ev: Event) void {
+ if (self.count == self.names.len) return;
+ self.watch = ev.watch;
+ self.names[self.count] = @splat(0);
+ @memcpy(self.names[self.count][0..ev.name.len], ev.name);
+ self.flags[self.count] = ev.flags;
+ self.count += 1;
+ }
+
+ fn name(self: *const Seen, i: usize) []const u8 {
+ return std.mem.sliceTo(&self.names[i], 0);
+ }
+};
+
+fn tempDirectory(tmp: anytype) ![:0]u8 {
+ return tmp.dir.realPathFileAlloc(std.testing.io, ".", std.testing.allocator);
+}
+
+test "a watcher reports names and completed writes in a directory" {
+ const t = std.testing;
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tempDirectory(&tmp);
+ defer t.allocator.free(root);
+ var watcher = try Watcher.init();
+ defer watcher.deinit();
+ const watch = watcher.add(root, .{ .written = true, .moved_to = true }).?;
+ try t.expect(!watcher.flush());
+
+ try tmp.dir.writeFile(t.io, .{ .sub_path = "config.toml", .data = "a" });
+ var seen: Seen = .{};
+ try watcher.drain(&seen, Seen.event);
+ try t.expectEqual(@as(usize, 1), seen.count);
+ try t.expectEqual(watch, seen.watch);
+ try t.expectEqualStrings("config.toml", seen.name(0));
+ try t.expect(seen.flags[0].written and seen.flags[0].isChange() and !seen.flags[0].lost());
+
+ // An atomic replacement arrives as a move into the directory.
+ try tmp.dir.writeFile(t.io, .{ .sub_path = "config.tmp", .data = "b" });
+ _ = watcher.flush();
+ try tmp.dir.rename("config.tmp", tmp.dir, "config.toml", t.io);
+ seen = .{};
+ try watcher.drain(&seen, Seen.event);
+ try t.expectEqual(@as(usize, 1), seen.count);
+ try t.expect(seen.flags[0].moved_to and !seen.flags[0].written);
+}
+
+test "a directory that goes away reports a lost watch" {
+ const t = std.testing;
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tempDirectory(&tmp);
+ defer t.allocator.free(root);
+ const inner = try std.fs.path.join(t.allocator, &.{ root, "inner" });
+ defer t.allocator.free(inner);
+ try tmp.dir.createDir(t.io, "inner", .default_dir);
+ var watcher = try Watcher.init();
+ defer watcher.deinit();
+ const watch = watcher.add(inner, Flags.listing).?;
+ try tmp.dir.deleteDir(t.io, "inner");
+ var seen: Seen = .{};
+ try watcher.drain(&seen, Seen.event);
+ try t.expect(seen.count >= 1);
+ var lost = false;
+ for (seen.flags[0..seen.count]) |flag| lost = lost or flag.lost();
+ try t.expect(lost);
+ try t.expectEqual(watch, seen.watch);
+ // A removal made by the owner only drops the watch: not a change.
+ try tmp.dir.createDir(t.io, "inner", .default_dir);
+ const readded = watcher.add(inner, Flags.listing).?;
+ _ = watcher.flush();
+ watcher.remove(readded);
+ seen = .{};
+ try watcher.drain(&seen, Seen.event);
+ try t.expectEqual(@as(usize, 1), seen.count);
+ try t.expect(seen.flags[0].dropped and !seen.flags[0].isChange());
+}
+
+test "a missing directory falls back to its nearest parent and re-adding keeps the watch" {
+ const t = std.testing;
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tempDirectory(&tmp);
+ defer t.allocator.free(root);
+ const missing = try std.fs.path.join(t.allocator, &.{ root, "not", "yet" });
+ defer t.allocator.free(missing);
+ var watcher = try Watcher.init();
+ defer watcher.deinit();
+ try t.expect(watcher.add(missing, Flags.listing) == null);
+ const parent = watcher.addOrParent(missing, Flags.listing).?;
+ try t.expectEqual(parent, watcher.add(root, Flags.listing).?);
+ try tmp.dir.createDir(t.io, "not", .default_dir);
+ var seen: Seen = .{};
+ try watcher.drain(&seen, Seen.event);
+ try t.expectEqual(@as(usize, 1), seen.count);
+ try t.expect(seen.flags[0].created and seen.flags[0].is_dir);
+ try t.expectEqualStrings("not", seen.name(0));
+}
diff --git a/src/printing/client.zig b/src/printing/client.zig
index c0369f6..7046ef0 100644
--- a/src/printing/client.zig
+++ b/src/printing/client.zig
@@ -236,7 +236,7 @@ pub const Client = struct {
};
state.remote = (try endpoint.parseServer(socket)).unix == null;
state.admin_local = std.mem.eql(u8, socket, "/run/cups/cups.sock") or std.mem.eql(u8, socket, "/var/run/cups/cups.sock");
- if (self.watch) |*watch| if (watch.fd < 0) {
+ if (self.watch) |*watch| if (watch.fd() < 0) {
watch.deinit(a);
self.watch = null;
};
@@ -384,7 +384,7 @@ pub const Client = struct {
}
if (self.reload.load(.acquire)) continue;
const timeout: c_int = if (rescan_at) |deadline| @intCast(@max(0, deadline - http.nowMs())) else -1;
- var fds = [_]c.struct_pollfd{ .{ .fd = self.wake_worker, .events = c.POLLIN, .revents = 0 }, .{ .fd = netlink, .events = c.POLLIN, .revents = 0 }, .{ .fd = if (self.watch) |watch| watch.fd else -1, .events = c.POLLIN, .revents = 0 } };
+ var fds = [_]c.struct_pollfd{ .{ .fd = self.wake_worker, .events = c.POLLIN, .revents = 0 }, .{ .fd = netlink, .events = c.POLLIN, .revents = 0 }, .{ .fd = if (self.watch) |watch| watch.fd() else -1, .events = c.POLLIN, .revents = 0 } };
const n = c.poll(&fds, fds.len, timeout);
if (n < 0) {
if (std.posix.errno(n) == .INTR) continue;
diff --git a/src/printing/daemon_watch.zig b/src/printing/daemon_watch.zig
index 9e7cf0d..9024d1a 100644
--- a/src/printing/daemon_watch.zig
+++ b/src/printing/daemon_watch.zig
@@ -1,14 +1,14 @@
//! Socket-directory events complement CUPS subscriptions: a daemon can vanish
//! before sending an IPP notification. This watcher never opens the socket.
const std = @import("std");
+const platform = @import("platform");
const endpoint = @import("endpoint.zig");
-const c = @import("c");
const A = std.mem.Allocator;
pub const Watch = struct {
- fd: c_int,
+ watcher: platform.watch.Watcher,
basename: []u8,
- watch: c_int,
+ watch: platform.watch.Watch,
/// No watcher is needed for a remote server. Missing/inaccessible parent
/// directories retain explicit refresh rather than starting a retry timer.
@@ -18,81 +18,59 @@ pub const Watch = struct {
const parent = std.fs.path.dirname(socket) orelse return null;
const name = std.fs.path.basename(socket);
if (name.len == 0 or std.mem.eql(u8, name, "/")) return null;
- const basename = try a.dupe(u8, name);
- errdefer a.free(basename);
- const directory = try a.dupeSentinel(u8, parent, 0);
- defer a.free(directory);
- const fd = c.inotify_init1(c.IN_CLOEXEC | c.IN_NONBLOCK);
- if (fd < 0) {
- a.free(basename);
+ var watcher = platform.watch.Watcher.init() catch return null;
+ const watch = watcher.add(parent, .{ .created = true, .deleted = true, .moved_to = true, .moved_from = true, .attrib = true }) orelse {
+ watcher.deinit();
return null;
- }
- const watch = c.inotify_add_watch(fd, directory, c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_TO | c.IN_MOVED_FROM | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_UNMOUNT);
- if (watch < 0) {
- _ = c.close(fd);
- a.free(basename);
- return null;
- }
- return .{ .fd = fd, .basename = basename, .watch = watch };
+ };
+ const basename = a.dupe(u8, name) catch |err| {
+ watcher.deinit();
+ return err;
+ };
+ return .{ .watcher = watcher, .basename = basename, .watch = watch };
}
pub fn deinit(self: *Watch, a: A) void {
- if (self.fd >= 0) _ = c.close(self.fd);
+ self.watcher.deinit();
a.free(self.basename);
self.* = undefined;
}
+ /// The descriptor to poll; negative once the watch has been invalidated.
+ pub fn fd(self: Watch) c_int {
+ return self.watcher.fd;
+ }
+
+ const Scan = struct {
+ watch: platform.watch.Watch,
+ basename: []const u8,
+ changed: bool = false,
+ lost: bool = false,
+
+ fn event(self: *Scan, ev: platform.watch.Event) void {
+ if (ev.flags.overflow) self.changed = true;
+ if (ev.watch != self.watch) return;
+ if (ev.flags.lost()) {
+ self.lost = true;
+ } else if (std.mem.eql(u8, ev.name, self.basename)) {
+ self.changed = true;
+ }
+ }
+ };
+
/// Drain a bounded burst, coalescing all relevant events into one reload.
/// Invalidated watches close immediately so poll cannot spin on an error.
pub fn changed(self: *Watch) bool {
- if (self.fd < 0) return false;
- var changed_socket = false;
- var reads: usize = 0;
- while (reads < 8) : (reads += 1) {
- var bytes: [8192]u8 = undefined;
- const n = c.read(self.fd, &bytes, bytes.len);
- if (n < 0) {
- const err = std.posix.errno(n);
- if (err == .INTR) continue;
- if (err == .AGAIN) return changed_socket;
- self.close();
- return true;
- }
- if (n == 0) {
- self.close();
- return true;
- }
- var offset: usize = 0;
- const data = bytes[0..@intCast(n)];
- while (data.len - offset >= @sizeOf(c.struct_inotify_event)) {
- const event = std.mem.bytesToValue(c.struct_inotify_event, data[offset..][0..@sizeOf(c.struct_inotify_event)]);
- offset += @sizeOf(c.struct_inotify_event);
- if (event.len > data.len - offset) {
- self.close();
- return true;
- }
- if (event.mask & c.IN_Q_OVERFLOW != 0) changed_socket = true;
- if (event.wd == self.watch) {
- if (event.mask & (c.IN_IGNORED | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_UNMOUNT) != 0) {
- self.close();
- return true;
- }
- const name = std.mem.sliceTo(data[offset..][0..event.len], 0);
- if (std.mem.eql(u8, name, self.basename)) changed_socket = true;
- }
- offset += event.len;
- }
- if (offset != data.len) {
- self.close();
- return true;
- }
+ if (self.watcher.fd < 0) return false;
+ var scan: Scan = .{ .watch = self.watch, .basename = self.basename };
+ self.watcher.drainBounded(&scan, Scan.event, 8) catch {
+ scan.lost = true;
+ };
+ if (scan.lost) {
+ self.watcher.deinit();
+ return true;
}
- return changed_socket;
- }
-
- fn close(self: *Watch) void {
- if (self.fd >= 0) _ = c.close(self.fd);
- self.fd = -1;
+ return scan.changed;
}
};
@@ -126,7 +104,7 @@ test "CUPS socket watcher coalesces exact-name create, rename, delete and parent
try std.Io.Dir.cwd().rename(root, .cwd(), moved, io);
defer std.Io.Dir.cwd().rename(moved, .cwd(), root, io) catch {};
try t.expect(watcher.changed());
- try t.expectEqual(@as(c_int, -1), watcher.fd);
+ try t.expectEqual(@as(c_int, -1), watcher.fd());
try t.expect(!watcher.changed());
}
diff --git a/src/session/child.zig b/src/session/child.zig
index 4d79e74..60f86f0 100644
--- a/src/session/child.zig
+++ b/src/session/child.zig
@@ -3,12 +3,12 @@
//! or timer is needed, and signals always address the original process.
const std = @import("std");
const wl = @import("wayland").server.wl;
-const linux = std.os.linux;
+const platform = @import("platform");
const Child = @This();
allocator: std.mem.Allocator,
-pid: linux.pid_t,
-fd: i32,
+pid: platform.child.Pid,
+handle: platform.child.Handle,
source: *wl.EventSource,
loop_destroy: wl.Listener(*wl.EventLoop) = .init(loopDestroyed),
owner: ?*anyopaque,
@@ -16,22 +16,30 @@ callback: ?*const fn (?*anyopaque, *Child, ?u32) void,
/// A session helper owns its process group. Kill descendants before reaping
/// its leader, while the PID is still reserved.
kill_group: bool = false,
+/// False for `observe`: another owner collects the exit status.
+reaps: bool = true,
-pub fn watch(allocator: std.mem.Allocator, loop: *wl.EventLoop, pid: linux.pid_t, owner: ?*anyopaque, callback: @FieldType(Child, "callback")) !*Child {
+pub fn watch(allocator: std.mem.Allocator, loop: *wl.EventLoop, pid: platform.child.Pid, owner: ?*anyopaque, callback: @FieldType(Child, "callback")) !*Child {
const self = try allocator.create(Child);
errdefer allocator.destroy(self);
- const rc = linux.pidfd_open(pid, 0);
- if (linux.errno(rc) != .SUCCESS) return error.PidfdFailed;
- const fd: i32 = @intCast(rc);
- errdefer _ = linux.close(fd);
- self.* = .{ .allocator = allocator, .pid = pid, .fd = fd, .source = undefined, .owner = owner, .callback = callback };
- self.source = try loop.addFd(*Child, fd, .{ .readable = true }, ready, self);
+ const handle = try platform.child.Handle.open(pid);
+ errdefer handle.close();
+ self.* = .{ .allocator = allocator, .pid = pid, .handle = handle, .source = undefined, .owner = owner, .callback = callback };
+ self.source = try loop.addFd(*Child, handle.fd, .{ .readable = true }, ready, self);
loop.addDestroyListener(&self.loop_destroy);
return self;
}
-pub fn signal(self: *Child, sig: linux.SIG) void {
- _ = linux.pidfd_send_signal(self.fd, sig, null, 0);
+/// `watch` for a child whose status someone else collects: the callback gets
+/// no status, and the process is never reaped here.
+pub fn observe(allocator: std.mem.Allocator, loop: *wl.EventLoop, pid: platform.child.Pid, owner: ?*anyopaque, callback: @FieldType(Child, "callback")) !*Child {
+ const self = try watch(allocator, loop, pid, owner, callback);
+ self.reaps = false;
+ return self;
+}
+
+pub fn signal(self: *Child, sig: platform.child.Signal) void {
+ self.handle.signal(sig) catch {};
}
pub fn detach(self: *Child) void {
@@ -39,12 +47,16 @@ pub fn detach(self: *Child) void {
self.callback = null;
}
+/// Stops watching without a callback; the process runs on.
+pub fn cancel(self: *Child) void {
+ self.destroy();
+}
+
/// Explicit nonblocking drain for bounded shutdown, never an exit poll timer.
/// Returns true if this call destroyed the watch.
pub fn dispatch(self: *Child) bool {
- var fds = [_]linux.pollfd{.{ .fd = self.fd, .events = linux.POLL.IN, .revents = 0 }};
- if (linux.errno(linux.poll(&fds, 1, 0)) != .SUCCESS or fds[0].revents == 0) return false;
- if (self.kill_group) _ = linux.kill(-self.pid, .KILL);
+ if (!self.handle.exited()) return false;
+ if (self.kill_group) platform.child.signalGroup(self.pid, .KILL);
const status = self.reap();
if (self.callback) |callback| callback(self.owner, self, status);
self.destroy();
@@ -52,15 +64,7 @@ pub fn dispatch(self: *Child) bool {
}
fn reap(self: *Child) ?u32 {
- var status: u32 = 0;
- while (true) {
- const rc = linux.wait4(self.pid, @ptrCast(&status), linux.W.NOHANG, null);
- switch (linux.errno(rc)) {
- .INTR => continue,
- .SUCCESS => return if (rc == self.pid) status else null,
- else => return null,
- }
- }
+ return if (self.reaps) platform.child.reap(self.pid) else null;
}
fn ready(_: c_int, _: wl.EventMask, self: *Child) c_int {
@@ -79,6 +83,41 @@ fn loopDestroyed(listener: *wl.Listener(*wl.EventLoop), _: *wl.EventLoop) void {
fn destroy(self: *Child) void {
self.source.remove();
self.loop_destroy.link.remove();
- _ = linux.close(self.fd);
+ self.handle.close();
self.allocator.destroy(self);
}
+
+test "an observed child is reported without being reaped, and a cancelled watch stays silent" {
+ const loop = try wl.EventLoop.create();
+ defer loop.destroy();
+ const Seen = struct {
+ calls: u32 = 0,
+ status: ?u32 = 0,
+ fn exited(owner: ?*anyopaque, _: *Child, status: ?u32) void {
+ const self: *@This() = @ptrCast(@alignCast(owner.?));
+ self.calls += 1;
+ self.status = status;
+ }
+ };
+ var seen: Seen = .{};
+
+ var quick = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sh", "-c", "exit 5" } });
+ defer quick.kill(std.testing.io);
+ const quick_pid = quick.id.?;
+ _ = try observe(std.testing.allocator, loop, quick_pid, &seen, Seen.exited);
+ try loop.dispatch(2000);
+ try std.testing.expectEqual(@as(u32, 1), seen.calls);
+ // The exit was observed, not collected: the real owner still gets the status.
+ try std.testing.expectEqual(@as(?u32, null), seen.status);
+ const status = platform.child.reap(quick_pid).?;
+ try std.testing.expectEqual(@as(u8, 5), std.os.linux.W.EXITSTATUS(status));
+ quick.id = null;
+
+ var slow = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ defer slow.kill(std.testing.io);
+ const cancelled = try observe(std.testing.allocator, loop, slow.id.?, &seen, Seen.exited);
+ cancelled.cancel();
+ try loop.dispatch(0);
+ try std.testing.expectEqual(@as(u32, 1), seen.calls);
+ try std.testing.expect(platform.child.exists(slow.id.?));
+}
diff --git a/src/session/file_chooser.zig b/src/session/file_chooser.zig
index d7b4c62..79c4911 100644
--- a/src/session/file_chooser.zig
+++ b/src/session/file_chooser.zig
@@ -10,6 +10,7 @@ const model = @import("../files/chooser.zig");
const protocol = @import("file_chooser_protocol.zig");
const settings = @import("settings_portal.zig");
const c = @import("c");
+const platform = @import("platform");
const a = std.heap.c_allocator;
const interface = "org.freedesktop.impl.portal.FileChooser";
const Request = struct {
@@ -19,7 +20,7 @@ const Request = struct {
options: model.Options,
deferred: dbus.Connection.Deferred,
fd: c_int,
- pidfd: c_int,
+ process: platform.child.Handle,
source: ?*wl.EventSource = null,
output: std.ArrayList(u8) = .empty,
@@ -28,8 +29,8 @@ const Request = struct {
conn.unregisterMethodsByOwner(self);
conn.releaseDeferred(&self.deferred);
if (self.source) |s| s.remove();
- _ = std.os.linux.pidfd_send_signal(self.pidfd, .TERM, null, 0);
- _ = c.close(self.pidfd);
+ self.process.signal(.TERM) catch {};
+ self.process.close();
_ = c.close(self.fd);
self.output.deinit(a);
self.arena.deinit();
@@ -169,20 +170,17 @@ fn open(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) !void {
var env = try self.server.environ.createMap(a);
defer env.deinit();
try self.server.applyChildEnv(&env);
- var pathbuf: [4096]u8 = undefined;
- const n = c.readlink("/proc/self/exe", &pathbuf, pathbuf.len);
- const executable = if (n > 0 and n < pathbuf.len) try std.fmt.allocPrint(alloc, "{s}/rediwm-files", .{std.fs.path.dirname(pathbuf[0..@intCast(n)]).?}) else "rediwm-files";
+ var pathbuf: [platform.exe.max_path]u8 = undefined;
+ const executable: []const u8 = platform.exe.sibling(&pathbuf, "rediwm-files") orelse "rediwm-files";
var child = try std.process.spawn(self.server.io, .{ .argv = &.{ executable, "--chooser-stdin" }, .environ_map = &env, .stdin = .{ .file = .{ .handle = input, .flags = .{ .nonblocking = false } } }, .stdout = .pipe });
errdefer child.kill(self.server.io);
- const pidfd_result = std.os.linux.pidfd_open(child.id.?, 0);
- if (std.os.linux.errno(pidfd_result) != .SUCCESS) return error.PidfdFailed;
- const pidfd: c_int = @intCast(pidfd_result);
- errdefer _ = c.close(pidfd);
+ const process = try platform.child.Handle.open(child.id.?);
+ errdefer process.close();
const fd = child.stdout.?.handle;
if (c.fcntl(fd, c.F_SETFL, @as(c_int, c.O_NONBLOCK)) < 0) return error.NonblockingFailed;
const r = try a.create(Request);
errdefer a.destroy(r);
- r.* = .{ .manager = self, .arena = arena, .handle = handle, .options = opts, .deferred = try conn.deferReply(msg), .fd = fd, .pidfd = pidfd };
+ r.* = .{ .manager = self, .arena = arena, .handle = handle, .options = opts, .deferred = try conn.deferReply(msg), .fd = fd, .process = process };
errdefer conn.releaseDeferred(&r.deferred);
try conn.register(.{ .path = handle, .interface = "org.freedesktop.impl.portal.Request", .member = "Close", .owner = r, .callback = close });
errdefer conn.unregisterMethodsByOwner(r);
diff --git a/src/session/supervisor.zig b/src/session/supervisor.zig
index e13be5d..fd96299 100644
--- a/src/session/supervisor.zig
+++ b/src/session/supervisor.zig
@@ -6,8 +6,10 @@ const std = @import("std");
const linux = std.os.linux;
const sys = @import("login_sys.zig");
const publication = @import("publication.zig");
+const platform = @import("platform");
const Pid = linux.pid_t;
+const Handle = platform.child.Handle;
const PidSet = std.AutoArrayHashMapUnmanaged(Pid, void);
const max_crashes = 5;
@@ -98,18 +100,18 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8
return err;
};
sys.close(child);
- const pidfd: i32 = @intCast(try sys.check(linux.pidfd_open(pid, 0)));
+ const process = try Handle.open(pid);
var status: ?u32 = null;
{
defer {
sys.close(parent);
parent_open = false;
- status = stopGroup(allocator, pid, pidfd, &preexisting);
- sys.close(pidfd);
+ status = stopGroup(allocator, pid, process, &preexisting);
+ process.close();
if (options.publication) |p| p.restore() catch |err| sys.diagnostic("activation cleanup pending: {t}", .{err});
}
- stopping = try waitForExit(allocator, pid, parent, pidfd, signal_fd, options.publication, &locked);
+ stopping = try waitForExit(allocator, pid, parent, process, signal_fd, options.publication, &locked);
}
if (stopping) return 0;
const raw = status orelse return 1;
@@ -125,13 +127,13 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8
/// Serves readiness handshakes and records lock reports until the compositor
/// exits (false) or the supervisor is asked to stop (true).
-fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, pidfd: i32, signal_fd: i32, maybe_publication: anytype, locked: *bool) !bool {
+fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, process: Handle, signal_fd: i32, maybe_publication: anytype, locked: *bool) !bool {
var deadline: ?i64 = sys.monotonicMs() + readiness_timeout_ms;
var parent_open = true;
var packet: [16384]u8 = undefined;
while (true) {
var fds = [_]linux.pollfd{
- .{ .fd = pidfd, .events = linux.POLL.IN, .revents = 0 },
+ .{ .fd = process.fd, .events = linux.POLL.IN, .revents = 0 },
.{ .fd = signal_fd, .events = linux.POLL.IN, .revents = 0 },
.{ .fd = if (parent_open) parent else -1, .events = linux.POLL.IN, .revents = 0 },
};
@@ -291,22 +293,22 @@ fn descendants(allocator: std.mem.Allocator, root: Pid) !PidSet {
return result;
}
-/// Holds pidfds throughout so an exiting or reused PID can never redirect a
-/// signal to an unrelated process. Returns the compositor's wait status, or
-/// null when it is stuck in the kernel.
-fn stopGroup(allocator: std.mem.Allocator, compositor: Pid, compositor_fd: i32, preexisting: *const PidSet) ?u32 {
- var handles: std.AutoArrayHashMapUnmanaged(Pid, i32) = .empty;
+/// Holds process handles throughout so an exiting or reused PID can never
+/// redirect a signal to an unrelated process. Returns the compositor's wait
+/// status, or null when it is stuck in the kernel.
+fn stopGroup(allocator: std.mem.Allocator, compositor: Pid, compositor_handle: Handle, preexisting: *const PidSet) ?u32 {
+ var handles: std.AutoArrayHashMapUnmanaged(Pid, Handle) = .empty;
defer {
- for (handles.values()) |fd| sys.close(fd);
+ for (handles.values()) |handle| handle.close();
handles.deinit(allocator);
}
collect(allocator, &handles, compositor, preexisting);
- send(&handles, compositor_fd, .TERM);
+ send(&handles, compositor_handle, .TERM);
// One bounded grace period, ended early once everything has exited.
- awaitExit(allocator, &handles, compositor_fd, 1000);
+ awaitExit(allocator, &handles, compositor_handle, 1000);
collect(allocator, &handles, compositor, preexisting);
- send(&handles, compositor_fd, .KILL);
- awaitExit(allocator, &handles, compositor_fd, 2000);
+ send(&handles, compositor_handle, .KILL);
+ awaitExit(allocator, &handles, compositor_handle, 2000);
var status: u32 = 0;
const reaped = sys.retry(linux.wait4, .{ compositor, @as(*i32, @ptrCast(&status)), linux.W.NOHANG, null }) catch 0;
@@ -321,35 +323,34 @@ fn stopGroup(allocator: std.mem.Allocator, compositor: Pid, compositor_fd: i32,
return status;
}
-fn collect(allocator: std.mem.Allocator, handles: *std.AutoArrayHashMapUnmanaged(Pid, i32), compositor: Pid, preexisting: *const PidSet) void {
+fn collect(allocator: std.mem.Allocator, handles: *std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor: Pid, preexisting: *const PidSet) void {
var tree = descendants(allocator, linux.getpid()) catch return;
defer tree.deinit(allocator);
for (tree.keys()) |pid| {
if (pid == compositor or preexisting.contains(pid) or handles.contains(pid)) continue;
- const rc = linux.pidfd_open(pid, 0);
- if (linux.errno(rc) != .SUCCESS) continue;
- handles.put(allocator, pid, @intCast(rc)) catch sys.close(@intCast(rc));
+ const handle = Handle.open(pid) catch continue;
+ handles.put(allocator, pid, handle) catch handle.close();
}
}
-fn send(handles: *const std.AutoArrayHashMapUnmanaged(Pid, i32), compositor_fd: i32, sig: linux.SIG) void {
- signalPidfd(compositor_fd, sig);
- for (handles.values()) |fd| signalPidfd(fd, sig);
+fn send(handles: *const std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor_handle: Handle, sig: linux.SIG) void {
+ signalHandle(compositor_handle, sig);
+ for (handles.values()) |handle| signalHandle(handle, sig);
}
-fn signalPidfd(fd: i32, sig: linux.SIG) void {
- switch (linux.errno(linux.pidfd_send_signal(fd, sig, null, 0))) {
- .PERM => sys.diagnostic("privileged descendant must be stopped by logind session teardown", .{}),
+fn signalHandle(handle: Handle, sig: linux.SIG) void {
+ handle.signal(sig) catch |err| switch (err) {
+ error.PermissionDenied => sys.diagnostic("privileged descendant must be stopped by logind session teardown", .{}),
else => {},
- }
+ };
}
-/// Waits for every pidfd to become readable (exited), up to `timeout_ms`.
-fn awaitExit(allocator: std.mem.Allocator, handles: *const std.AutoArrayHashMapUnmanaged(Pid, i32), compositor_fd: i32, timeout_ms: i64) void {
+/// Waits for every handle to become readable (exited), up to `timeout_ms`.
+fn awaitExit(allocator: std.mem.Allocator, handles: *const std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor_handle: Handle, timeout_ms: i64) void {
const fds = allocator.alloc(linux.pollfd, handles.count() + 1) catch return;
defer allocator.free(fds);
- fds[0] = .{ .fd = compositor_fd, .events = linux.POLL.IN, .revents = 0 };
- for (handles.values(), fds[1..]) |fd, *p| p.* = .{ .fd = fd, .events = linux.POLL.IN, .revents = 0 };
+ fds[0] = .{ .fd = compositor_handle.fd, .events = linux.POLL.IN, .revents = 0 };
+ for (handles.values(), fds[1..]) |handle, *p| p.* = .{ .fd = handle.fd, .events = linux.POLL.IN, .revents = 0 };
const deadline = sys.monotonicMs() + timeout_ms;
while (true) {
const remaining = deadline - sys.monotonicMs();
diff --git a/src/start_menu/applications.zig b/src/start_menu/applications.zig
index 7c5faed..36e7cf1 100644
--- a/src/start_menu/applications.zig
+++ b/src/start_menu/applications.zig
@@ -12,7 +12,7 @@ const Io = std.Io;
const posix = std.posix;
const c = std.posix.system;
const wl = @import("wayland").server.wl;
-const linux = std.os.linux;
+const platform = @import("platform");
const catalog_cache = @import("catalog_cache.zig");
const startup = @import("../startup.zig");
@@ -108,9 +108,8 @@ pub const Catalog = struct {
thread: ?std.Thread = null,
delay_ns: u64 = 0,
- watch_fd: i32 = -1,
+ watcher: ?platform.watch.Watcher = null,
watch_source: ?*wl.EventSource = null,
- watch_wds: std.ArrayList(i32) = .empty,
watched_paths: std.StringHashMapUnmanaged(void) = .empty,
/// `scan` false leaves the catalog empty and never touches the cache
@@ -163,14 +162,12 @@ pub const Catalog = struct {
}
pub fn attachWatch(self: *Catalog, loop: *wl.EventLoop) void {
- const fd = std.c.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC);
- if (fd < 0) return;
- self.watch_fd = fd;
- self.watch_source = loop.addFd(*Catalog, fd, .{ .readable = true }, handleInotify, self) catch {
- _ = std.c.close(fd);
- self.watch_fd = -1;
+ var watcher = platform.watch.Watcher.init() catch return;
+ self.watch_source = loop.addFd(*Catalog, watcher.fd, .{ .readable = true }, handleWatch, self) catch {
+ watcher.deinit();
return;
};
+ self.watcher = watcher;
self.syncWatches();
}
@@ -182,11 +179,10 @@ pub const Catalog = struct {
if (self.thread) |t| t.join();
if (self.watch_source) |src| src.remove();
- if (self.watch_fd >= 0) _ = std.c.close(self.watch_fd);
+ if (self.watcher) |*w| w.deinit();
var it = self.watched_paths.keyIterator();
while (it.next()) |k| self.allocator.free(k.*);
self.watched_paths.deinit(self.allocator);
- self.watch_wds.deinit(self.allocator);
if (self.eventfd >= 0) _ = c.close(self.eventfd);
if (self.pending) |snap| snap.release();
@@ -397,64 +393,47 @@ pub const Catalog = struct {
}
fn syncWatches(self: *Catalog) void {
- if (self.watch_fd < 0) return;
+ const watcher = self.watcher orelse return;
var tmp = std.heap.ArenaAllocator.init(self.allocator);
defer tmp.deinit();
const a = tmp.allocator();
- const mask: u32 = linux.IN.CREATE | linux.IN.DELETE | linux.IN.MODIFY | linux.IN.MOVED_FROM |
- linux.IN.MOVED_TO | linux.IN.ATTRIB | linux.IN.CLOSE_WRITE | linux.IN.DELETE_SELF;
if (resolveApplicationDirs(a, self.environ)) |dirs| {
- for (dirs) |dir| self.addWatch(dir, mask);
+ for (dirs) |dir| self.addWatch(watcher, dir);
} else |_| {}
// Directories already visited by the scan, without walking the tree again
// on the compositor thread.
for (self.current.sources) |src| {
- if (std.fs.path.dirname(src.path)) |dir| self.addWatch(dir, mask);
+ if (std.fs.path.dirname(src.path)) |dir| self.addWatch(watcher, dir);
}
}
- fn addWatch(self: *Catalog, dir: []const u8, mask: u32) void {
+ fn addWatch(self: *Catalog, watcher: platform.watch.Watcher, dir: []const u8) void {
if (self.watched_paths.contains(dir)) return;
- var zbuf: [std.posix.PATH_MAX]u8 = undefined;
- const zdir = std.fmt.bufPrintSentinel(&zbuf, "{s}", .{dir}, 0) catch return;
- const wd = std.c.inotify_add_watch(self.watch_fd, zdir.ptr, mask);
- if (wd < 0) return;
+ _ = watcher.add(dir, .{ .created = true, .deleted = true, .modified = true, .moved_from = true, .moved_to = true, .attrib = true, .written = true }) orelse return;
const owned = self.allocator.dupe(u8, dir) catch return;
- self.watched_paths.put(self.allocator, owned, {}) catch {
- self.allocator.free(owned);
- return;
- };
- self.watch_wds.append(self.allocator, wd) catch {};
+ self.watched_paths.put(self.allocator, owned, {}) catch self.allocator.free(owned);
}
};
-fn handleInotify(fd: c_int, mask: wl.EventMask, catalog: *Catalog) c_int {
- _ = mask;
- var buf: [4096]u8 align(@alignOf(linux.inotify_event)) = undefined;
- var saw = false;
- while (true) {
- const n = posix.read(fd, &buf) catch |err| switch (err) {
- error.WouldBlock => break,
- else => break,
- };
- if (n == 0) break;
- var off: usize = 0;
- while (off + @sizeOf(linux.inotify_event) <= n) {
- const ev: *const linux.inotify_event = @ptrCast(@alignCast(&buf[off]));
- if (ev.mask & (linux.IN.CREATE | linux.IN.DELETE | linux.IN.MODIFY | linux.IN.MOVED_FROM |
- linux.IN.MOVED_TO | linux.IN.ATTRIB | linux.IN.CLOSE_WRITE | linux.IN.DELETE_SELF) != 0)
- {
- saw = true;
- if (ev.mask & linux.IN.CREATE != 0 and ev.mask & linux.IN.ISDIR != 0) {
- catalog.syncWatches();
- }
- }
- off += @sizeOf(linux.inotify_event) + ev.len;
- }
+const Changes = struct {
+ catalog: *Catalog,
+ saw: bool = false,
+
+ fn event(self: *Changes, ev: platform.watch.Event) void {
+ if (!ev.flags.isChange()) return;
+ self.saw = true;
+ // A new directory may hold applications of its own.
+ if (ev.flags.created and ev.flags.is_dir) self.catalog.syncWatches();
}
- if (saw) catalog.requestRefresh();
+};
+
+fn handleWatch(_: c_int, _: wl.EventMask, catalog: *Catalog) c_int {
+ const watcher = catalog.watcher orelse return 0;
+ var changes: Changes = .{ .catalog = catalog };
+ watcher.drain(&changes, Changes.event) catch {};
+ if (changes.saw) catalog.requestRefresh();
return 0;
}
diff --git a/src/system_monitor/actions.zig b/src/system_monitor/actions.zig
index 72aa0f8..4f976ec 100644
--- a/src/system_monitor/actions.zig
+++ b/src/system_monitor/actions.zig
@@ -1,14 +1,13 @@
//! Action authority is checked again at execution, never trusted from a row.
const std = @import("std");
+const platform = @import("platform");
const proc = @import("proc.zig");
const c = proc.c;
pub const Kind = enum { end, force };
pub fn execute(identity: proc.Identity, kind: Kind) !void {
- const rc = std.os.linux.pidfd_open(identity.pid, 0);
- if (std.os.linux.errno(rc) != .SUCCESS) return signalError(std.os.linux.errno(rc));
- const pidfd: i32 = @intCast(rc);
- defer _ = c.close(pidfd);
+ const process = platform.child.Handle.open(identity.pid) catch |err| return signalError(err);
+ defer process.close();
// Open the proc directory AFTER the pidfd. If PID reuse occurs between
// them, the old pidfd becomes readable and the final liveness gate fails.
const dir = try proc.openProcess(identity.pid);
@@ -20,33 +19,20 @@ pub fn execute(identity: proc.Identity, kind: Kind) !void {
const uids = proc.parseUids(try proc.readAt(dir, "status", &status_buf)) orelse return error.IdentityUnavailable;
if (!proc.owned(uids, c.getuid())) return error.PermissionDenied;
if (try proc.protectedAt(dir, identity.pid)) return error.ProtectedProcess;
- // fdinfo identifies the task referred to by THIS pidfd, not whichever task
- // currently occupies /proc/PID. An exited pidfd reports Pid: -1.
- var path_buf: [64]u8 = undefined;
- const path = try std.fmt.bufPrintSentinel(&path_buf, "/proc/self/fdinfo/{d}", .{pidfd}, 0);
- var info_buf: [4096]u8 = undefined;
- const info = try proc.readAt(c.AT_FDCWD, path, &info_buf);
- var lines = std.mem.splitScalar(u8, info, '\n');
- var pid_matches = false;
- while (lines.next()) |line| {
- if (std.mem.startsWith(u8, line, "Pid:")) {
- const pid = std.fmt.parseInt(i32, std.mem.trim(u8, line[4..], " \t"), 10) catch return error.IdentityUnavailable;
- pid_matches = pid == identity.pid;
- }
- }
- if (!pid_matches) return error.ProcessExited;
- var fd = c.struct_pollfd{ .fd = pidfd, .events = c.POLLIN, .revents = 0 };
- if (c.poll(&fd, 1, 0) != 0) return error.ProcessExited;
- const result = std.os.linux.pidfd_send_signal(pidfd, if (kind == .end) std.posix.SIG.TERM else std.posix.SIG.KILL, null, 0);
- if (std.os.linux.errno(result) != .SUCCESS) return signalError(std.os.linux.errno(result));
+ // The handle names the task it was opened on, not whichever task
+ // currently occupies /proc/PID.
+ const live = process.pid() catch return error.IdentityUnavailable;
+ if (live != identity.pid) return error.ProcessExited;
+ if (process.exited()) return error.ProcessExited;
+ process.signal(if (kind == .end) .TERM else .KILL) catch |err| return signalError(err);
}
-fn signalError(err: std.os.linux.E) error{ ProcessExited, PermissionDenied, PidfdUnavailable, SignalFailed } {
+fn signalError(err: platform.child.Error) error{ ProcessExited, PermissionDenied, PidfdUnavailable, SignalFailed } {
return switch (err) {
- .SRCH, .NOENT => error.ProcessExited,
- .PERM, .ACCES => error.PermissionDenied,
- .NOSYS, .INVAL => error.PidfdUnavailable,
- else => error.SignalFailed,
+ error.NoSuchProcess => error.ProcessExited,
+ error.PermissionDenied => error.PermissionDenied,
+ error.Unsupported => error.PidfdUnavailable,
+ error.Failed => error.SignalFailed,
};
}
diff --git a/src/system_monitor/client.zig b/src/system_monitor/client.zig
index a2ce938..acfa1b0 100644
--- a/src/system_monitor/client.zig
+++ b/src/system_monitor/client.zig
@@ -869,7 +869,7 @@ pub fn run(init: std.process.Init) !void {
var fds = [_]c.struct_pollfd{
.{ .fd = display.getFd(), .events = @intCast(c.POLLIN | @as(c_int, if (flushed == .AGAIN) c.POLLOUT else 0)), .revents = 0 },
.{ .fd = self.app.worker.notify_fd, .events = c.POLLIN, .revents = 0 },
- .{ .fd = watch.fd, .events = c.POLLIN, .revents = 0 },
+ .{ .fd = watch.fd(), .events = c.POLLIN, .revents = 0 },
};
const now = key_repeat.nowMs();
var timeout: c_int = if (self.key_repeat.timeoutMs(now)) |wait| @intCast(@min(wait, 60_000)) else -1;
diff --git a/src/system_monitor/settings_watch.zig b/src/system_monitor/settings_watch.zig
index 9350291..de384bc 100644
--- a/src/system_monitor/settings_watch.zig
+++ b/src/system_monitor/settings_watch.zig
@@ -1,28 +1,31 @@
-//! Theme changes wake the UI through inotify, including while sampling is
+//! Theme changes wake the UI through file watching, including while sampling is
//! paused or suspended. Watch parent directories so atomic saves work too.
const std = @import("std");
-const c = @import("../files/c.zig").api;
+const platform = @import("platform");
const settings = @import("../files/settings.zig");
const a = std.heap.c_allocator;
pub const Watch = struct {
- fd: c_int,
+ watcher: platform.watch.Watcher,
settings: settings.Settings,
io: std.Io,
pub fn init(io: std.Io, env: std.process.Environ) !Watch {
- const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
- if (fd < 0) return error.ThemeWatchFailed;
- errdefer _ = c.close(fd);
- var self: Watch = .{ .fd = fd, .settings = try settings.Settings.init(a, env), .io = io };
+ var watcher = platform.watch.Watcher.init() catch return error.ThemeWatchFailed;
+ errdefer watcher.deinit();
+ var self: Watch = .{ .watcher = watcher, .settings = try settings.Settings.init(a, env), .io = io };
self.arm();
_ = self.apply();
return self;
}
pub fn deinit(self: *Watch) void {
self.settings.deinit(a);
- _ = c.close(self.fd);
+ self.watcher.deinit();
+ }
+ /// The descriptor to poll for a change.
+ pub fn fd(self: *const Watch) c_int {
+ return self.watcher.fd;
}
fn arm(self: *Watch) void {
- self.settings.watch(self.fd);
+ self.settings.watch(self.watcher);
}
fn apply(self: *Watch) bool {
if (self.settings.reload(a, self.io)) |update| {
@@ -33,10 +36,7 @@ pub const Watch = struct {
return false;
}
pub fn poll(self: *Watch) bool {
- var buf: [8192]u8 = undefined;
- var changed = false;
- while (c.read(self.fd, &buf, buf.len) > 0) changed = true;
- if (!changed) return false;
+ if (!self.watcher.flush()) return false;
self.arm();
return self.apply();
}
diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zig
index c736038..e2e3f6a 100644
--- a/src/system_monitor_tests.zig
+++ b/src/system_monitor_tests.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const platform = @import("platform");
const proc = @import("system_monitor/proc.zig");
const model = @import("system_monitor/model.zig");
const collector = @import("system_monitor/collector.zig");
@@ -119,12 +120,10 @@ test "monitor pidfd actions terminate only disposable fixtures and force a TERM-
var ready: [16]u8 = undefined;
try std.testing.expect(proc.c.read(stubborn.stdout.?.handle, &ready, ready.len) > 0);
const identity = proc.Identity{ .pid = stubborn.id.?, .start = proc.readStat(stubborn.id.?, &buf).?.start };
- const rc = std.os.linux.pidfd_open(identity.pid, 0);
- try std.testing.expectEqual(std.os.linux.E.SUCCESS, std.os.linux.errno(rc));
- const fd: i32 = @intCast(rc);
- defer _ = proc.c.close(fd);
+ const process = try platform.child.Handle.open(identity.pid);
+ defer process.close();
try actions.execute(identity, .end);
- var pollfd = proc.c.struct_pollfd{ .fd = fd, .events = proc.c.POLLIN, .revents = 0 };
+ var pollfd = proc.c.struct_pollfd{ .fd = process.fd, .events = proc.c.POLLIN, .revents = 0 };
try std.testing.expectEqual(@as(c_int, 0), proc.c.poll(&pollfd, 1, 100));
try actions.execute(identity, .force);
const killed = try stubborn.wait(io);
diff --git a/src/toplevel/create.zig b/src/toplevel/create.zig
index 79fe94c..2e3fd2d 100644
--- a/src/toplevel/create.zig
+++ b/src/toplevel/create.zig
@@ -2,6 +2,7 @@
const std = @import("std");
const Toplevel = @import("../Toplevel.zig");
+const Child = @import("../session/child.zig");
const glass = @import("../glass.zig");
const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
@@ -207,19 +208,17 @@ pub fn handleLaunchTimeout(toplevel: *Toplevel) c_int {
return 0;
}
-// Observe the same pidfd exit without reaping: services owns the child status.
-pub fn handleChildExit(_: c_int, _: wl.EventMask, toplevel: *Toplevel) c_int {
- if (toplevel.backend != .placeholder) return 0;
+// The launched process exited. The watch only observes: services owns the
+// child status, and the watch ends itself once this returns.
+pub fn handleChildExit(owner: ?*anyopaque, _: *Child, _: ?u32) void {
+ const toplevel: *Toplevel = @ptrCast(@alignCast(owner.?));
+ if (toplevel.backend != .placeholder) return;
const ph = &toplevel.backend.placeholder;
- if (ph.child_source) |source| source.remove();
- ph.child_source = null;
- if (ph.child_pidfd >= 0) _ = std.os.linux.close(ph.child_pidfd);
- ph.child_pidfd = -1;
+ ph.child = null;
if (!ph.matched and !ph.cancelled) {
if (toplevel.server.ipc) |ipc| events.onLaunchTimeout(ipc, ph.desktop_id, ph.pid);
toplevel.destroyNow();
}
- return 0;
}
pub fn createPlaceholder(
diff --git a/tests/files_terminal.py b/tests/files_terminal.py
index e957cfe..c11ad67 100644
--- a/tests/files_terminal.py
+++ b/tests/files_terminal.py
@@ -42,7 +42,7 @@ def build_engine(tmp):
'ft_free': ([C.c_void_p], None),
'ft_start': ([C.c_void_p, C.c_char_p, C.c_char_p, C.c_char_p, C.c_bool], C.c_int),
'ft_pty': ([C.c_void_p], C.c_int), 'ft_channel': ([C.c_void_p], C.c_int),
- 'ft_pidfd': ([C.c_void_p], C.c_int),
+ 'ft_exit_fd': ([C.c_void_p], C.c_int),
'ft_wants_write': ([C.c_void_p], C.c_bool),
'ft_wants_request': ([C.c_void_p], C.c_bool),
'ft_io': ([C.c_void_p, C.c_bool, C.c_bool, C.c_bool, C.c_bool], None),
@@ -73,7 +73,7 @@ class Engine:
def pump(self, timeout=.05):
poll = select.poll()
fds = [self.lib.ft_pty(self.handle), self.lib.ft_channel(self.handle),
- self.lib.ft_pidfd(self.handle)]
+ self.lib.ft_exit_fd(self.handle)]
for i, fd in enumerate(fds):
if fd >= 0:
output = (i == 0 and self.lib.ft_wants_write(self.handle)) or (